1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Mathable; |
6
|
|
|
use Bavix\Wallet\Interfaces\Wallet; |
7
|
|
|
use Bavix\Wallet\Models\Transfer; |
8
|
|
|
use Bavix\Wallet\Objects\Bring; |
9
|
|
|
use Bavix\Wallet\Services\CommonService; |
10
|
|
|
use Bavix\Wallet\Services\DbService; |
11
|
|
|
use Bavix\Wallet\Services\ExchangeService; |
12
|
|
|
use Bavix\Wallet\Services\LockService; |
13
|
|
|
use Bavix\Wallet\Services\WalletService; |
14
|
|
|
|
15
|
|
|
trait CanExchange |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
2 |
|
public function exchange(Wallet $to, $amount, ?array $meta = null): Transfer |
21
|
|
|
{ |
22
|
2 |
|
$wallet = app(WalletService::class) |
23
|
2 |
|
->getWallet($this); |
|
|
|
|
24
|
|
|
|
25
|
2 |
|
app(CommonService::class) |
26
|
2 |
|
->verifyWithdraw($wallet, $amount); |
27
|
|
|
|
28
|
1 |
|
return $this->forceExchange($to, $amount, $meta); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
1 |
|
public function safeExchange(Wallet $to, $amount, ?array $meta = null): ?Transfer |
35
|
|
|
{ |
36
|
|
|
try { |
37
|
1 |
|
return $this->exchange($to, $amount, $meta); |
38
|
1 |
|
} catch (\Throwable $throwable) { |
39
|
1 |
|
return null; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* {@inheritdoc} |
45
|
|
|
*/ |
46
|
1 |
|
public function forceExchange(Wallet $to, $amount, ?array $meta = null): Transfer |
47
|
|
|
{ |
48
|
|
|
/** |
49
|
|
|
* @var Wallet $from |
50
|
|
|
*/ |
51
|
1 |
|
$from = app(WalletService::class)->getWallet($this); |
|
|
|
|
52
|
|
|
|
53
|
|
|
return app(LockService::class)->lock($this, __FUNCTION__, static function () use ($from, $to, $amount, $meta) { |
54
|
|
|
return app(DbService::class)->transaction(static function () use ($from, $to, $amount, $meta) { |
55
|
1 |
|
$math = app(Mathable::class); |
56
|
1 |
|
$rate = app(ExchangeService::class)->rate($from, $to); |
57
|
1 |
|
$fee = app(WalletService::class)->fee($to, $amount); |
58
|
|
|
|
59
|
1 |
|
$withdraw = app(CommonService::class) |
60
|
1 |
|
->forceWithdraw($from, $math->add($amount, $fee), $meta); |
|
|
|
|
61
|
|
|
|
62
|
1 |
|
$deposit = app(CommonService::class) |
63
|
1 |
|
->deposit($to, $math->floor($math->mul($amount, $rate, 1)), $meta); |
|
|
|
|
64
|
|
|
|
65
|
1 |
|
$transfers = app(CommonService::class)->multiBrings([ |
66
|
1 |
|
app(Bring::class) |
67
|
1 |
|
->setDiscount(0) |
68
|
1 |
|
->setStatus(Transfer::STATUS_EXCHANGE) |
69
|
1 |
|
->setDeposit($deposit) |
70
|
1 |
|
->setWithdraw($withdraw) |
71
|
1 |
|
->setFrom($from) |
72
|
1 |
|
->setFee($fee) |
|
|
|
|
73
|
1 |
|
->setTo($to), |
74
|
|
|
]); |
75
|
|
|
|
76
|
1 |
|
return current($transfers); |
77
|
1 |
|
}); |
78
|
1 |
|
}); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|