1010use Bavix \Wallet \Internal \Exceptions \TransactionFailedException ;
1111use Bavix \Wallet \Internal \Service \DatabaseServiceInterface ;
1212use Bavix \Wallet \Internal \Service \LockServiceInterface ;
13+ use Bavix \Wallet \Internal \Service \StateServiceInterface ;
1314use Illuminate \Database \RecordsNotFoundException ;
1415
1516/**
@@ -19,6 +20,7 @@ final class AtomicService implements AtomicServiceInterface
1920{
2021 public function __construct (
2122 private DatabaseServiceInterface $ databaseService ,
23+ private StateServiceInterface $ stateService ,
2224 private LockServiceInterface $ lockService ,
2325 private CastServiceInterface $ castService
2426 ) {
@@ -37,7 +39,17 @@ public function blocks(array $objects, callable $callback): mixed
3739 $ callable = fn () => $ this ->databaseService ->transaction ($ callback );
3840 foreach ($ objects as $ object ) {
3941 $ wallet = $ this ->castService ->getWallet ($ object );
40- $ callable = fn () => $ this ->lockService ->block ($ wallet ->uuid , $ callable );
42+ $ callable = fn () => $ this ->lockService ->block (
43+ $ wallet ->uuid ,
44+ function () use ($ wallet , $ callable ) {
45+ try {
46+ $ this ->stateService ->fork ($ wallet ->uuid , $ wallet ->balance );
47+ return $ callable ();
48+ } finally {
49+ $ this ->stateService ->drop ($ wallet ->uuid );
50+ }
51+ }
52+ );
4153 }
4254
4355 return $ callable ();
0 commit comments