BlockchainTransaction.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. namespace App\Module\Blockchain\Models;
  3. use App\Module\Transaction\Enums\ACCOUNT_TYPE;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Cache;
  8. /**
  9. *
  10. *
  11. * field start
  12. * @property int $id
  13. * @property string $tx_hash 交易哈希
  14. * @property string $from_address 发送地址
  15. * @property string $to_address 接收地址
  16. * @property float $amount 转账金额
  17. * @property int $token_type 代币类型:1=bnb, 2=usdt, 3=uraus
  18. * @property float $gas_price 矿工费单价(GWEI)
  19. * @property int $gas_used 消耗的Gas数量
  20. * @property float $gas_fee 矿工费总额(BNB)
  21. * @property int $status 状态:0=待确认,1=成功,2=失败
  22. * @property int $block_number 区块号
  23. * @property \Carbon\Carbon $created_at
  24. * @property \Carbon\Carbon $updated_at
  25. * field end
  26. */
  27. class BlockchainTransaction extends Model
  28. {
  29. protected $table = 'blockchain_transactions';
  30. // attrlist start
  31. protected $fillable = [
  32. 'id',
  33. 'tx_hash',
  34. 'from_address',
  35. 'to_address',
  36. 'amount',
  37. 'token_type',
  38. 'gas_price',
  39. 'gas_used',
  40. 'gas_fee',
  41. 'status',
  42. 'block_number',
  43. ];
  44. // attrlist end
  45. protected $casts = [
  46. 'token_type' => ACCOUNT_TYPE::class,
  47. 'amount' => 'decimal:18',
  48. 'gas_price' => 'decimal:18',
  49. 'gas_used' => 'integer',
  50. 'gas_fee' => 'decimal:18',
  51. 'status' => 'integer',
  52. 'block_number' => 'integer'
  53. ];
  54. protected static function booted()
  55. {
  56. static::creating(function ($transaction) {
  57. // 自动计算矿工费
  58. if ($transaction->gas_price && $transaction->gas_used) {
  59. $transaction->gas_fee = bcdiv(
  60. bcmul($transaction->gas_price, (string)$transaction->gas_used),
  61. '1000000000',
  62. 18
  63. );
  64. }
  65. });
  66. static::updating(function ($transaction) {
  67. // 当 gas_price 或 gas_used 更新时重新计算矿工费
  68. if ($transaction->isDirty('gas_price') || $transaction->isDirty('gas_used')) {
  69. $transaction->gas_fee = bcdiv(
  70. bcmul($transaction->gas_price, (string)$transaction->gas_used),
  71. '1000000000',
  72. 18
  73. );
  74. }
  75. });
  76. static::updated(function ($transaction) {
  77. if ($transaction->isDirty('status')) {
  78. if ($transaction->status === 1) { // 交易成功
  79. $transaction->updateWalletBalances();
  80. }
  81. }
  82. });
  83. }
  84. public function fromWallet(): BelongsTo
  85. {
  86. return $this->belongsTo(BlockchainWallet::class, 'from_address', 'address');
  87. }
  88. public function toWallet(): BelongsTo
  89. {
  90. return $this->belongsTo(BlockchainWallet::class, 'to_address', 'address');
  91. }
  92. public function getStatusLabelAttribute(): string
  93. {
  94. return match($this->status) {
  95. 0 => '待确认',
  96. 1 => '成功',
  97. 2 => '失败',
  98. default => '未知'
  99. };
  100. }
  101. public function updateWalletBalances(): void
  102. {
  103. DB::transaction(function () {
  104. // 更新发送方钱包余额
  105. $fromWallet = $this->fromWallet;
  106. if ($fromWallet) {
  107. $newBalance = bcsub($fromWallet->balance, $this->amount, 18);
  108. $fromWallet->updateBalance($newBalance);
  109. }
  110. // 更新接收方钱包余额
  111. $toWallet = $this->toWallet;
  112. if ($toWallet) {
  113. $newBalance = bcadd($toWallet->balance, $this->amount, 18);
  114. $toWallet->updateBalance($newBalance);
  115. }
  116. });
  117. }
  118. public function getConfirmations(): int
  119. {
  120. if (!$this->block_number) {
  121. return 0;
  122. }
  123. $latestBlockNumber = Cache::remember('latest_block_number', 60, function () {
  124. $bscScanService = app(BscScanService::class);
  125. return $bscScanService->getLatestBlockNumber();
  126. });
  127. return max(0, $latestBlockNumber - $this->block_number);
  128. }
  129. public function isSafe(): bool
  130. {
  131. $requiredConfirmations = config('blockchain.transaction.confirmations', 12);
  132. return $this->getConfirmations() >= $requiredConfirmations;
  133. }
  134. public function getTotalGasFee(): float
  135. {
  136. if (!$this->gas_price || !$this->gas_used) {
  137. return 0;
  138. }
  139. return bcmul($this->gas_price, (string)$this->gas_used, 18);
  140. }
  141. /**
  142. * 获取交易的总成本(转账金额 + 矿工费)
  143. * 仅当代币类型为 BNB 时才包含矿工费
  144. */
  145. public function getTotalCost(): string
  146. {
  147. if ($this->token_type === ACCOUNT_TYPE::BNB) {
  148. return bcadd($this->amount, $this->gas_fee, 18);
  149. }
  150. return $this->amount;
  151. }
  152. /**
  153. * 获取格式化的矿工费(带单位)
  154. */
  155. public function getFormattedGasFeeAttribute(): string
  156. {
  157. return $this->gas_fee . ' BNB';
  158. }
  159. /**
  160. * 获取预估的矿工费
  161. */
  162. public static function estimateGasFee(ACCOUNT_TYPE $tokenType, float $gasPrice): float
  163. {
  164. $gasLimit = $tokenType === ACCOUNT_TYPE::BNB ? 21000 : 65000;
  165. return bcdiv(bcmul((string)$gasPrice, (string)$gasLimit), '1000000000', 18);
  166. }
  167. /**
  168. * 检查矿工费是否超过最大限制
  169. */
  170. public function isGasFeeTooHigh(): bool
  171. {
  172. $maxGasPrice = config('blockchain.transaction.max_gas_price', 10); // GWEI
  173. return bccomp($this->gas_price, (string)$maxGasPrice, 18) === 1;
  174. }
  175. }