@@ -5,7 +5,7 @@ import { ICollateralManager } from "../interfaces/ICollateralManager.sol";
55import { SafeCastLib } from "solady/utils/SafeCastLib.sol " ;
66
77library CollateralUtils {
8- using SafeCastLib for * ;
8+ using SafeCastLib for uint256 ;
99 uint256 constant AMOUNT_BITS = 96 ;
1010 uint256 constant AMOUNT_MASK = (uint256 (1 ) << AMOUNT_BITS) - 1 ;
1111
@@ -18,23 +18,44 @@ library CollateralUtils {
1818 amount = _packed.toUint96 ();
1919 }
2020
21- function add (ICollateralManager.CollateralStore storage _store , address _token , uint96 _amount ) internal {
22- if (_store.index[_token] != 0 ) revert ();
23- _store.slot.push (pack (_token, _amount));
24- _store.index[_token] = _store.slot.length ;
21+ function add (ICollateralManager.CollateralStore storage _store , address _token , uint96 _amount )
22+ internal
23+ returns (uint96 newBalance )
24+ {
25+ uint256 idx = _store.index[_token];
26+
27+ if (idx == 0 ) {
28+ _store.slot.push (pack (_token, _amount));
29+ _store.index[_token] = _store.slot.length ;
30+ newBalance = _amount;
31+ } else {
32+ (, uint96 amount ) = unpack (_store.slot[idx - 1 ]);
33+ newBalance = _amount + amount;
34+ _store.slot[idx - 1 ] = pack (_token, newBalance);
35+ }
2536 }
2637
27- function update (ICollateralManager.CollateralStore storage _store , address _token , uint96 _amount ) internal {
38+ function sub (ICollateralManager.CollateralStore storage _store , address _token , uint96 _amount )
39+ internal
40+ returns (uint96 newBalance )
41+ {
2842 uint256 idx = _store.index[_token];
2943 if (idx == 0 ) revert ();
3044
31- _store.slot[idx - 1 ] = pack (_token, _amount);
45+ (, uint96 amount ) = unpack (_store.slot[idx - 1 ]);
46+
47+ if (_amount > amount) revert ();
48+
49+ newBalance = amount - _amount;
50+ if (newBalance != 0 ) {
51+ _store.slot[idx - 1 ] = pack (_token, newBalance);
52+ } else {
53+ _remove (_store, _token, idx);
54+ }
3255 }
3356
34- function remove (ICollateralManager.CollateralStore storage _store , address _token ) internal {
35- uint256 idx = _store.index[_token];
57+ function _remove (ICollateralManager.CollateralStore storage _store , address _token , uint256 idx ) internal {
3658 uint256 slotLength = _store.slot.length ;
37-
3859 if (idx != slotLength) {
3960 uint256 lastPack = _store.slot[slotLength - 1 ];
4061 (address lastToken ,) = unpack (lastPack);
0 commit comments