1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Wallet; |
6
|
|
|
use Bavix\Wallet\Models\Transfer; |
7
|
|
|
use Bavix\Wallet\Objects\Bring; |
8
|
|
|
use Bavix\Wallet\Services\CommonService; |
9
|
|
|
use Bavix\Wallet\Services\ExchangeService; |
10
|
|
|
use Bavix\Wallet\Services\WalletService; |
11
|
|
|
use Illuminate\Support\Facades\DB; |
12
|
|
|
|
13
|
|
|
trait CanExchange |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @inheritDoc |
18
|
|
|
*/ |
19
|
|
|
public function exchange(Wallet $to, int $amount): Transfer |
20
|
|
|
{ |
21
|
|
|
app(WalletService::class)->checkAmount($amount); |
22
|
|
|
return $this->forceExchange($to, $amount); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @inheritDoc |
27
|
|
|
*/ |
28
|
|
|
public function safeExchange(Wallet $to, int $amount): ?Transfer |
29
|
|
|
{ |
30
|
|
|
try { |
31
|
|
|
return $this->exchange($to, $amount); |
32
|
|
|
} catch (\Throwable $throwable) { |
33
|
|
|
return null; |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @inheritDoc |
39
|
|
|
*/ |
40
|
|
|
public function forceExchange(Wallet $to, int $amount): Transfer |
41
|
|
|
{ |
42
|
|
|
/** |
43
|
|
|
* @var Wallet $from |
44
|
|
|
*/ |
45
|
|
|
$from = app(WalletService::class)->getWallet($this); |
|
|
|
|
46
|
|
|
|
47
|
|
|
return DB::transaction(function () use ($from, $to, $amount) { |
48
|
|
|
$rate = app(ExchangeService::class)->rate($from, $to); |
49
|
|
|
$fee = app(WalletService::class)->fee($to, $amount); |
50
|
|
|
$withdraw = $from->forceWithdraw($amount + $fee); |
51
|
|
|
$deposit = $to->deposit($amount * $rate); |
|
|
|
|
52
|
|
|
|
53
|
|
|
$transfers = app(CommonService::class)->multiBrings([ |
54
|
|
|
(new Bring()) |
55
|
|
|
->setStatus(Transfer::STATUS_EXCHANGE) |
56
|
|
|
->setDeposit($deposit) |
57
|
|
|
->setWithdraw($withdraw) |
58
|
|
|
->setFrom($from) |
59
|
|
|
->setTo($to) |
60
|
|
|
]); |
61
|
|
|
|
62
|
|
|
return current($transfers); |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
} |
67
|
|
|
|