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
|
|
|
$wallet = app(WalletService::class) |
22
|
|
|
->getWallet($this); |
|
|
|
|
23
|
|
|
|
24
|
|
|
app(CommonService::class) |
25
|
|
|
->verifyWithdraw($wallet, $amount); |
26
|
|
|
|
27
|
|
|
return $this->forceExchange($to, $amount); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @inheritDoc |
32
|
|
|
*/ |
33
|
|
|
public function safeExchange(Wallet $to, int $amount): ?Transfer |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
|
|
return $this->exchange($to, $amount); |
37
|
|
|
} catch (\Throwable $throwable) { |
38
|
|
|
return null; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @inheritDoc |
44
|
|
|
*/ |
45
|
|
|
public function forceExchange(Wallet $to, int $amount): Transfer |
46
|
|
|
{ |
47
|
|
|
/** |
48
|
|
|
* @var Wallet $from |
49
|
|
|
*/ |
50
|
|
|
$from = app(WalletService::class)->getWallet($this); |
|
|
|
|
51
|
|
|
|
52
|
|
|
return DB::transaction(function() use ($from, $to, $amount) { |
53
|
|
|
$rate = app(ExchangeService::class)->rate($from, $to); |
54
|
|
|
$fee = app(WalletService::class)->fee($to, $amount); |
55
|
|
|
$withdraw = $from->forceWithdraw($amount + $fee); |
56
|
|
|
$deposit = $to->deposit($amount * $rate); |
|
|
|
|
57
|
|
|
|
58
|
|
|
$transfers = app(CommonService::class)->multiBrings([ |
59
|
|
|
(new Bring()) |
60
|
|
|
->setStatus(Transfer::STATUS_EXCHANGE) |
61
|
|
|
->setDeposit($deposit) |
62
|
|
|
->setWithdraw($withdraw) |
63
|
|
|
->setFrom($from) |
64
|
|
|
->setTo($to) |
65
|
|
|
]); |
66
|
|
|
|
67
|
|
|
return current($transfers); |
68
|
|
|
}); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
} |
72
|
|
|
|