Pārlūkot izejas kodu

token creation service

ljoaquim 2 nedēļas atpakaļ
vecāks
revīzija
f7a124e508
5 mainītis faili ar 245 papildinājumiem un 1 dzēšanām
  1. 5 0
      .env.example
  2. 2 1
      TODO.md
  3. BIN
      bin/easycli
  4. 141 0
      services/TokenCreateService.php
  5. 97 0
      test/token_create_test.php

+ 5 - 0
.env.example

@@ -9,6 +9,11 @@ ACCOUNT1=
 ACCOUNT1_KEY=
 ACCOUNT1_NAME=
 DOCUMENT_NUMBER=
+EASY_COIN_ADDR=0x065FB961Df42F2fdE1705007AFA24b8697d5C899
+EASY_TOKEN_ADDR=0x5F5776584b69d4C61590b9911EdcE2aBA0f0BA93
+EASY_ADMIM_PUBLIC_KEY=
+EASY_ADMIM_PRIVATE_KEY=
+POLYGON_RPC_URL=
 
 #================= B3 ======================
 B3_CLIENT_ID=

+ 2 - 1
TODO.md

@@ -43,4 +43,5 @@
 ### - GET ORDER SELL
 ### - GET with grafico
 ---
-### - GET WALLET
+### - GET WALLET
+

BIN
bin/easycli


+ 141 - 0
services/TokenCreateService.php

@@ -0,0 +1,141 @@
+<?php
+
+namespace Services;
+
+use Libs\BashExecutor;
+
+class TokenCreateService
+{
+    private \PDO $pdo;
+    private string $easyCliPath;
+
+    public function __construct()
+    {
+        if (!isset($GLOBALS['pdo']) || !$GLOBALS['pdo'] instanceof \PDO) {
+            throw new \RuntimeException('Global PDO connection not initialized');
+        }
+
+        $this->pdo = $GLOBALS['pdo'];
+        $this->easyCliPath = dirname(__DIR__) . '/bin/easycli';
+    }
+
+    public function createToken(
+        int $tokenCommoditiesAmount,
+        int $tokenCommoditiesValue,
+        string $tokenUf,
+        string $tokenCity,
+        string $tokenContent,
+        string $tokenFlag,
+        int $walletId,
+        int $chainId,
+        int $commoditiesId,
+        int $cprId,
+        int $userId
+    ): array {
+        $mintData = $this->mintToken($tokenContent);
+        $tokenExternalId = $mintData['tokenId'];
+        $txHash = $mintData['tx'];
+
+        $tokenId = $this->insertToken([
+            'token_external_id' => $tokenExternalId,
+            'token_commodities_amount' => $tokenCommoditiesAmount,
+            'token_commodities_value' => $tokenCommoditiesValue,
+            'token_uf' => $tokenUf,
+            'token_city' => $tokenCity,
+            'token_content' => $tokenContent,
+            'token_flag' => $tokenFlag,
+            'wallet_id' => $walletId,
+            'chain_id' => $chainId,
+            'commodities_id' => $commoditiesId,
+            'cpr_id' => $cprId,
+            'user_id' => $userId,
+        ]);
+
+        return [
+            'token_id' => $tokenId,
+            'token_external_id' => $tokenExternalId,
+            'tx_hash' => $txHash,
+            'raw_output' => $mintData['raw_output'],
+        ];
+    }
+
+    private function mintToken(string $content): array
+    {
+        if (!is_file($this->easyCliPath) || !is_executable($this->easyCliPath)) {
+            throw new \RuntimeException('easycli executable not found or not executable');
+        }
+
+        $command = sprintf('%s token mint %s', escapeshellarg($this->easyCliPath), escapeshellarg($content));
+        $result = BashExecutor::run($command, 120);
+
+        if (($result['exitCode'] ?? 1) !== 0) {
+            $message = $result['error'] ?: $result['output'] ?: 'Unknown easycli error';
+            throw new \RuntimeException('easycli mint failed: ' . $message);
+        }
+
+        $combinedOutput = trim(implode("\n", array_filter([
+            trim($result['output'] ?? ''),
+            trim($result['error'] ?? ''),
+        ])));
+
+        $tokenId = $this->extractValue('tokenId', $combinedOutput);
+        $txHash = $this->extractValue('tx', $combinedOutput);
+
+        if ($tokenId === null) {
+            throw new \RuntimeException('Unable to parse tokenId from easycli output: ' . $combinedOutput);
+        }
+
+        return [
+            'tokenId' => $tokenId,
+            'tx' => $txHash,
+            'raw_output' => $combinedOutput,
+        ];
+    }
+
+    private function extractValue(string $key, string $content): ?string
+    {
+        $pattern = sprintf('/%s\s*=\s*([^\s]+)/i', preg_quote($key, '/'));
+        if (preg_match($pattern, $content, $matches)) {
+            return trim($matches[1]);
+        }
+
+        return null;
+    }
+
+    private function insertToken(array $data): int
+    {
+        $stmt = $this->pdo->prepare(
+            'INSERT INTO "token" (
+                token_external_id,
+                token_commodities_amount,
+                token_commodities_value,
+                token_uf,
+                token_city,
+                token_content,
+                token_flag,
+                wallet_id,
+                chain_id,
+                commodities_id,
+                cpr_id,
+                user_id
+            ) VALUES (
+                :token_external_id,
+                :token_commodities_amount,
+                :token_commodities_value,
+                :token_uf,
+                :token_city,
+                :token_content,
+                :token_flag,
+                :wallet_id,
+                :chain_id,
+                :commodities_id,
+                :cpr_id,
+                :user_id
+            ) RETURNING token_id'
+        );
+
+        $stmt->execute($data);
+
+        return (int) $stmt->fetchColumn();
+    }
+}

+ 97 - 0
test/token_create_test.php

@@ -0,0 +1,97 @@
+#!/usr/bin/env php
+<?php
+declare(strict_types=1);
+
+require __DIR__ . '/../vendor/autoload.php';
+
+use Services\TokenCreateService;
+
+if (class_exists(Dotenv\Dotenv::class) && file_exists(__DIR__ . '/../.env')) {
+    Dotenv\Dotenv::createImmutable(dirname(__DIR__), null, true)->safeLoad();
+}
+
+$dsn = $_ENV['DB_DSN'] ?? (function () {
+    $host = $_ENV['DB_HOST'] ?? 'localhost';
+    $port = $_ENV['DB_PORT'] ?? '5432';
+    $name = $_ENV['DB_NAME'] ?? 'postgres';
+    return "pgsql:host={$host};port={$port};dbname={$name}";
+})();
+$dbUser = $_ENV['DB_USER'] ?? 'postgres';
+$dbPass = $_ENV['DB_PASSWORD'] ?? '';
+
+$GLOBALS['pdo'] = new PDO($dsn, $dbUser, $dbPass);
+$GLOBALS['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+$payloadFile = $argv[1] ?? null;
+if ($payloadFile) {
+    if (!is_file($payloadFile)) {
+        fwrite(STDERR, "[error] Payload file '{$payloadFile}' not found" . PHP_EOL);
+        exit(1);
+    }
+    $data = json_decode(file_get_contents($payloadFile), true);
+    if (!is_array($data)) {
+        fwrite(STDERR, "[error] Invalid JSON payload" . PHP_EOL);
+        exit(1);
+    }
+} else {
+    $data = [
+        'token_commodities_amount' => 1,
+        'token_commodities_value' => 100,
+        'token_uf' => 'SP',
+        'token_city' => 'SAO PAULO',
+        'token_content' => 'sample-content-' . time(),
+        'token_flag' => 'a',
+        'wallet_id' => 1,
+        'chain_id' => 1,
+        'commodities_id' => 1,
+        'cpr_id' => 1,
+        'user_id' => 1,
+    ];
+}
+
+$required = [
+    'token_commodities_amount',
+    'token_commodities_value',
+    'token_uf',
+    'token_city',
+    'token_content',
+    'token_flag',
+    'wallet_id',
+    'chain_id',
+    'commodities_id',
+    'cpr_id',
+    'user_id',
+];
+
+foreach ($required as $field) {
+    if (!array_key_exists($field, $data)) {
+        fwrite(STDERR, "[error] Missing required field: {$field}" . PHP_EOL);
+        exit(1);
+    }
+}
+
+$service = new TokenCreateService();
+
+try {
+    $result = $service->createToken(
+        (int)$data['token_commodities_amount'],
+        (int)$data['token_commodities_value'],
+        (string)$data['token_uf'],
+        (string)$data['token_city'],
+        (string)$data['token_content'],
+        (string)$data['token_flag'],
+        (int)$data['wallet_id'],
+        (int)$data['chain_id'],
+        (int)$data['commodities_id'],
+        (int)$data['cpr_id'],
+        (int)$data['user_id']
+    );
+
+    echo json_encode([
+        'status' => 'ok',
+        'data' => $result,
+    ], JSON_PRETTY_PRINT) . PHP_EOL;
+} catch (Throwable $e) {
+    fwrite(STDERR, '[error] ' . $e->getMessage() . PHP_EOL);
+    exit(1);
+}