1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
/*!
* This module deals with computing different types of health for a mango account.
*
* Health is a number in USD and represents a risk-engine assessment of the account's
* positions and open orders. The larger the health the better. Negative health
* often means some action is necessary or a limitation is placed on the user.
*
* The different types of health are described in the HealthType enum.
*
* The key struct in this module is HealthCache, typically constructed by the
* new_health_cache() function. With it, the different health types can be
* computed.
*
* The HealthCache holds the data it needs in TokenInfo, Serum3Info and PerpInfo.
*/
use anchor_lang::prelude::*;
use fixed::types::I80F48;
use openbook_v2::state::OpenOrdersAccount;
use crate::error::*;
use crate::i80f48::LowPrecisionDivision;
use crate::serum3_cpi::{OpenOrdersAmounts, OpenOrdersSlim};
use crate::state::{
Bank, MangoAccountRef, OpenbookV2MarketIndex, OpenbookV2Orders, PerpMarket, PerpMarketIndex,
PerpPosition, Serum3MarketIndex, Serum3Orders, TokenIndex,
};
use super::*;
/// Information about prices for a bank or perp market.
#[derive(Clone, Debug)]
pub struct Prices {
/// The current oracle price
pub oracle: I80F48, // native/native
/// A "stable" price, provided by StablePriceModel
pub stable: I80F48, // native/native
}
impl Prices {
// intended for tests
pub fn new_single_price(price: I80F48) -> Self {
Self {
oracle: price,
stable: price,
}
}
/// The liability price to use for the given health type
#[inline(always)]
pub fn liab(&self, health_type: HealthType) -> I80F48 {
match health_type {
HealthType::Maint | HealthType::LiquidationEnd => self.oracle,
HealthType::Init => self.oracle.max(self.stable),
}
}
/// The asset price to use for the given health type
#[inline(always)]
pub fn asset(&self, health_type: HealthType) -> I80F48 {
match health_type {
HealthType::Maint | HealthType::LiquidationEnd => self.oracle,
HealthType::Init => self.oracle.min(self.stable),
}
}
}
/// There are three types of health:
/// - initial health ("init"): users can only open new positions if it's >= 0
/// - maintenance health ("maint"): users get liquidated if it's < 0
/// - liquidation end health: once liquidation started (see being_liquidated), it
/// only stops once this is >= 0
///
/// The ordering is
/// init health <= liquidation end health <= maint health
///
/// The different health types are realized by using different weights and prices:
/// - init health: init weights with scaling, stable-price adjusted prices
/// - liq end health: init weights without scaling, oracle prices
/// - maint health: maint weights, oracle prices
///
#[derive(PartialEq, Copy, Clone, AnchorSerialize, AnchorDeserialize)]
pub enum HealthType {
Init,
Maint, // aka LiquidationStart
LiquidationEnd,
}
/// Computes health for a mango account given a set of account infos
///
/// These account infos must fit the fixed layout defined by FixedOrderAccountRetriever.
pub fn compute_health_from_fixed_accounts(
account: &MangoAccountRef,
health_type: HealthType,
ais: &[AccountInfo],
now_ts: u64,
) -> Result<I80F48> {
let retriever = new_fixed_order_account_retriever(ais, account, Clock::get()?.slot)?;
Ok(new_health_cache(account, &retriever, now_ts)?.health(health_type))
}
/// Compute health with an arbitrary AccountRetriever
pub fn compute_health(
account: &MangoAccountRef,
health_type: HealthType,
retriever: &impl AccountRetriever,
now_ts: u64,
) -> Result<I80F48> {
Ok(new_health_cache(account, retriever, now_ts)?.health(health_type))
}
/// How much of a token can be taken away before health decreases to zero?
///
/// If health is negative, returns 0.
pub fn spot_amount_taken_for_health_zero(
mut health: I80F48,
starting_spot: I80F48,
asset_weighted_price: I80F48,
liab_weighted_price: I80F48,
) -> Result<I80F48> {
if health <= 0 {
return Ok(I80F48::ZERO);
}
let mut taken_spot = I80F48::ZERO;
if starting_spot > 0 {
if asset_weighted_price > 0 {
let asset_max = health / asset_weighted_price;
if asset_max <= starting_spot {
return Ok(asset_max);
}
}
taken_spot = starting_spot;
health -= starting_spot * asset_weighted_price;
}
if health > 0 {
require_gt!(liab_weighted_price, 0);
taken_spot += health / liab_weighted_price;
}
Ok(taken_spot)
}
/// How much of a token can be gained before health increases to zero?
///
/// Returns 0 if health is positive.
pub fn spot_amount_given_for_health_zero(
health: I80F48,
starting_spot: I80F48,
asset_weighted_price: I80F48,
liab_weighted_price: I80F48,
) -> Result<I80F48> {
// asset/liab prices are reversed intentionally
spot_amount_taken_for_health_zero(
-health,
-starting_spot,
liab_weighted_price,
asset_weighted_price,
)
}
#[derive(Clone, Debug)]
pub struct TokenInfo {
pub token_index: TokenIndex,
pub maint_asset_weight: I80F48,
pub init_asset_weight: I80F48,
pub init_scaled_asset_weight: I80F48,
pub maint_liab_weight: I80F48,
pub init_liab_weight: I80F48,
pub init_scaled_liab_weight: I80F48,
pub prices: Prices,
/// Freely available spot balance for the token.
///
/// Includes TokenPosition and free Serum3OpenOrders balances.
/// Does not include perp upnl or Serum3 reserved amounts.
pub balance_spot: I80F48,
pub allow_asset_liquidation: bool,
}
/// Temporary value used during health computations
#[derive(Clone, Default)]
pub struct TokenBalance {
/// Sum of token_info.balance_spot and perp health_unsettled_pnl balances
pub spot_and_perp: I80F48,
}
#[derive(Clone, Default)]
pub struct TokenMaxReserved {
/// The sum of reserved amounts over all serum3 and openbookV2 markets
pub max_spot_reserved: I80F48,
}
impl TokenInfo {
#[inline(always)]
fn asset_weight(&self, health_type: HealthType) -> I80F48 {
match health_type {
HealthType::Init => self.init_scaled_asset_weight,
HealthType::LiquidationEnd => self.init_asset_weight,
HealthType::Maint => self.maint_asset_weight,
}
}
#[inline(always)]
pub fn asset_weighted_price(&self, health_type: HealthType) -> I80F48 {
self.asset_weight(health_type) * self.prices.asset(health_type)
}
#[inline(always)]
fn liab_weight(&self, health_type: HealthType) -> I80F48 {
match health_type {
HealthType::Init => self.init_scaled_liab_weight,
HealthType::LiquidationEnd => self.init_liab_weight,
HealthType::Maint => self.maint_liab_weight,
}
}
#[inline(always)]
pub fn liab_weighted_price(&self, health_type: HealthType) -> I80F48 {
self.liab_weight(health_type) * self.prices.liab(health_type)
}
#[inline(always)]
pub fn health_contribution(&self, health_type: HealthType, balance: I80F48) -> I80F48 {
let weighted_price = if balance.is_negative() {
self.liab_weighted_price(health_type)
} else {
self.asset_weighted_price(health_type)
};
balance * weighted_price
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum SpotMarketIndex {
Serum3(Serum3MarketIndex),
OpenbookV2(OpenbookV2MarketIndex),
}
/// Information about reserved funds on Serum3 and Openbook V2 open orders accounts.
///
/// Note that all "free" funds on open orders accounts are added directly
/// to the token info. This is only about dealing with the reserved funds
/// that might end up as base OR quote tokens, depending on whether the
/// open orders execute on not.
#[derive(Clone, Debug)]
pub struct SpotInfo {
// reserved amounts as stored on the open orders
pub reserved_base: I80F48,
pub reserved_quote: I80F48,
// Reserved amounts, converted to the opposite token, while using the most extreme order price
// May be zero if the extreme bid/ask price is not available (for orders placed in the past)
pub reserved_base_as_quote_lowest_ask: I80F48,
pub reserved_quote_as_base_highest_bid: I80F48,
// Index into TokenInfos _not_ a TokenIndex
pub base_info_index: usize,
pub quote_info_index: usize,
pub spot_market_index: SpotMarketIndex,
/// The open orders account has no free or reserved funds
pub has_zero_funds: bool,
}
impl SpotInfo {
fn new_from_serum(
serum_account: &Serum3Orders,
open_orders: &impl OpenOrdersAmounts,
base_info_index: usize,
quote_info_index: usize,
) -> Self {
// track the reserved amounts
let reserved_base = I80F48::from(open_orders.native_base_reserved());
let reserved_quote = I80F48::from(open_orders.native_quote_reserved());
let reserved_base_as_quote_lowest_ask =
reserved_base * I80F48::from_num(serum_account.lowest_placed_ask);
let reserved_quote_as_base_highest_bid =
reserved_quote * I80F48::from_num(serum_account.highest_placed_bid_inv);
Self {
reserved_base,
reserved_quote,
reserved_base_as_quote_lowest_ask,
reserved_quote_as_base_highest_bid,
base_info_index,
quote_info_index,
spot_market_index: SpotMarketIndex::Serum3(serum_account.market_index),
has_zero_funds: open_orders.native_base_total() == 0
&& open_orders.native_quote_total() == 0
&& open_orders.native_rebates() == 0,
}
}
fn new_from_openbook(
open_orders_account: &OpenOrdersAccount,
open_orders: &OpenbookV2Orders,
base_info_index: usize,
quote_info_index: usize,
) -> Self {
// track the reserved amounts
let reserved_base =
I80F48::from(open_orders_account.position.asks_base_lots * open_orders.base_lot_size);
let reserved_quote =
I80F48::from(open_orders_account.position.bids_quote_lots * open_orders.quote_lot_size);
let reserved_base_as_quote_lowest_ask =
reserved_base * I80F48::from_num(open_orders.lowest_placed_ask);
let reserved_quote_as_base_highest_bid =
reserved_quote * I80F48::from_num(open_orders.highest_placed_bid_inv);
Self {
reserved_base,
reserved_quote,
reserved_base_as_quote_lowest_ask,
reserved_quote_as_base_highest_bid,
base_info_index,
quote_info_index,
spot_market_index: SpotMarketIndex::OpenbookV2(open_orders.market_index),
has_zero_funds: open_orders_account
.position
.is_empty(open_orders_account.version),
}
}
#[inline(always)]
fn all_reserved_as_base(
&self,
health_type: HealthType,
quote_info: &TokenInfo,
base_info: &TokenInfo,
) -> I80F48 {
let quote_asset = quote_info.prices.asset(health_type);
let base_liab = base_info.prices.liab(health_type);
let reserved_quote_as_base_oracle = (self.reserved_quote * quote_asset)
.checked_div_f64_precision(base_liab)
.unwrap();
if self.reserved_quote_as_base_highest_bid != 0 {
self.reserved_base
+ reserved_quote_as_base_oracle.min(self.reserved_quote_as_base_highest_bid)
} else {
self.reserved_base + reserved_quote_as_base_oracle
}
}
#[inline(always)]
fn all_reserved_as_quote(
&self,
health_type: HealthType,
quote_info: &TokenInfo,
base_info: &TokenInfo,
) -> I80F48 {
let base_asset = base_info.prices.asset(health_type);
let quote_liab = quote_info.prices.liab(health_type);
let reserved_base_as_quote_oracle = (self.reserved_base * base_asset)
.checked_div_f64_precision(quote_liab)
.unwrap();
if self.reserved_base_as_quote_lowest_ask != 0 {
self.reserved_quote
+ reserved_base_as_quote_oracle.min(self.reserved_base_as_quote_lowest_ask)
} else {
self.reserved_quote + reserved_base_as_quote_oracle
}
}
/// Compute the health contribution from active open orders.
///
/// For open orders, health is about the worst-case outcome: Consider the scenarios:
/// - all reserved base tokens convert to quote tokens
/// - all reserved quote tokens convert to base tokens
/// Which would lead to the smaller token health?
///
/// Answering this question isn't straightforward for two reasons:
/// 1. We don't have information about the actual open orders here. Just about the amount
/// of reserved tokens. Hence we assume base/quote conversion would happen at current
/// asset/liab prices.
/// 2. Technically, there are interaction effects between multiple spot markets. If the
/// account has open orders on SOL/USDC, BTC/USDC and SOL/BTC, then the worst case for
/// SOL/USDC might be dependent on what happens with the open orders on the other two
/// markets.
///
/// To simplify 2, we give up on computing the actual worst-case and instead compute something
/// that's guaranteed to be less: Get the worst case for each market independently while
/// assuming all other market open orders resolved maximally unfavorably.
///
/// To be able to do that, we compute `token_max_reserved` for each token, which is the maximum
/// token amount that would be generated if open orders in all markets that deal with the token
/// turn its way. (in the example above: the open orders in the SOL/USDC and SOL/BTC market
/// both produce SOL) See `compute_serum3_reservations()` below.
#[inline(always)]
fn health_contribution(
&self,
health_type: HealthType,
token_infos: &[TokenInfo],
token_balances: &[TokenBalance],
token_max_reserved: &[TokenMaxReserved],
market_reserved: &SpotReserved,
) -> I80F48 {
if market_reserved.all_reserved_as_base.is_zero()
|| market_reserved.all_reserved_as_quote.is_zero()
{
return I80F48::ZERO;
}
let base_info = &token_infos[self.base_info_index];
let quote_info = &token_infos[self.quote_info_index];
// How much would health increase if the reserved balance were applied to the passed
// token info?
let compute_health_effect = |token_info: &TokenInfo,
balance: &TokenBalance,
max_reserved: &TokenMaxReserved,
market_reserved: I80F48| {
// This balance includes all possible reserved funds from markets that relate to the
// token, including this market itself: `market_reserved` is already included in `max_spot_reserved`.
let max_balance = balance.spot_and_perp + max_reserved.max_spot_reserved;
// For simplicity, we assume that `market_reserved` was added to `max_balance` last
// (it underestimates health because that gives the smallest effects): how much did
// health change because of it?
let (asset_part, liab_part) = if max_balance >= market_reserved {
(market_reserved, I80F48::ZERO)
} else if max_balance.is_negative() {
(I80F48::ZERO, market_reserved)
} else {
(max_balance, market_reserved - max_balance)
};
let asset_weight = token_info.asset_weight(health_type);
let liab_weight = token_info.liab_weight(health_type);
let asset_price = token_info.prices.asset(health_type);
let liab_price = token_info.prices.liab(health_type);
asset_part * asset_weight * asset_price + liab_part * liab_weight * liab_price
};
let health_base = compute_health_effect(
base_info,
&token_balances[self.base_info_index],
&token_max_reserved[self.base_info_index],
market_reserved.all_reserved_as_base,
);
let health_quote = compute_health_effect(
quote_info,
&token_balances[self.quote_info_index],
&token_max_reserved[self.quote_info_index],
market_reserved.all_reserved_as_quote,
);
health_base.min(health_quote)
}
}
#[derive(Clone)]
pub(crate) struct SpotReserved {
/// base tokens when the spotinfo.reserved_quote get converted to base and added to reserved_base
all_reserved_as_base: I80F48,
/// ditto the other way around
all_reserved_as_quote: I80F48,
}
/// Stores information about perp market positions and their open orders.
///
/// Perp markets affect account health indirectly, though the token balance in the
/// perp market's settle token. See `effective_token_balances()`.
#[derive(Clone, Debug)]
pub struct PerpInfo {
pub perp_market_index: PerpMarketIndex,
pub settle_token_index: TokenIndex,
pub maint_base_asset_weight: I80F48,
pub init_base_asset_weight: I80F48,
pub maint_base_liab_weight: I80F48,
pub init_base_liab_weight: I80F48,
pub maint_overall_asset_weight: I80F48,
pub init_overall_asset_weight: I80F48,
pub base_lot_size: i64,
pub base_lots: i64,
pub bids_base_lots: i64,
pub asks_base_lots: i64,
// in health-reference-token native units, no asset/liab factor needed
pub quote: I80F48,
pub base_prices: Prices,
pub has_open_orders: bool,
pub has_open_fills: bool,
}
impl PerpInfo {
fn new(
perp_position: &PerpPosition,
perp_market: &PerpMarket,
base_prices: Prices,
) -> Result<Self> {
let base_lots = perp_position.base_position_lots() + perp_position.taker_base_lots;
let unsettled_funding = perp_position.unsettled_funding(perp_market);
let taker_quote = I80F48::from(perp_position.taker_quote_lots * perp_market.quote_lot_size);
let quote_current = perp_position.quote_position_native() - unsettled_funding + taker_quote;
Ok(Self {
perp_market_index: perp_market.perp_market_index,
settle_token_index: perp_market.settle_token_index,
init_base_asset_weight: perp_market.init_base_asset_weight,
init_base_liab_weight: perp_market.init_base_liab_weight,
maint_base_asset_weight: perp_market.maint_base_asset_weight,
maint_base_liab_weight: perp_market.maint_base_liab_weight,
init_overall_asset_weight: perp_market.init_overall_asset_weight,
maint_overall_asset_weight: perp_market.maint_overall_asset_weight,
base_lot_size: perp_market.base_lot_size,
base_lots,
bids_base_lots: perp_position.bids_base_lots,
asks_base_lots: perp_position.asks_base_lots,
quote: quote_current,
base_prices,
has_open_orders: perp_position.has_open_orders(),
has_open_fills: perp_position.has_open_taker_fills(),
})
}
/// The perp-risk (but not token-risk) adjusted upnl. Also called "hupnl".
///
/// In settle token native units.
///
/// This is what gets added to effective_token_balances() and then contributes
/// to account health.
///
/// For fully isolated perp markets, users may never borrow against unsettled
/// positive perp pnl, there overall_asset_weight == 0 and there can't be positive
/// health contributions from these perp market. We sometimes call these markets
/// "untrusted markets".
///
/// In these, users need to settle their perp pnl with other perp market participants
/// in order to realize their gains if they want to use them as collateral.
///
/// This is because we don't trust the perp's base price to not suddenly jump to
/// zero (if users could borrow against their perp balances they might now
/// be bankrupt) or suddenly increase a lot (if users could borrow against perp
/// balances they could now borrow other assets).
///
/// Other markets may be liquid enough that we have enough confidence to allow
/// users to borrow against unsettled positive pnl to some extend. In these cases,
/// the overall asset weights would be >0.
#[inline(always)]
pub fn health_unsettled_pnl(&self, health_type: HealthType) -> I80F48 {
let contribution = self.unweighted_health_unsettled_pnl(health_type);
self.weigh_uhupnl_overall(contribution, health_type)
}
/// Convert uhupnl to hupnl by applying the overall weight. In settle token native units.
#[inline(always)]
fn weigh_uhupnl_overall(&self, unweighted: I80F48, health_type: HealthType) -> I80F48 {
if unweighted > 0 {
let overall_weight = match health_type {
HealthType::Init | HealthType::LiquidationEnd => self.init_overall_asset_weight,
HealthType::Maint => self.maint_overall_asset_weight,
};
overall_weight * unweighted
} else {
unweighted
}
}
/// Settle token native provided by perp position and open orders, without the overall asset weight.
///
/// Also called "uhupnl".
///
/// For open orders, this computes the worst-case amount by considering the scenario where all
/// bids execute and the one where all asks execute.
///
/// It's always less than the PerpPosition's `unsettled_pnl()` for two reasons: The open orders
/// are taken into account and the base weight is applied to the base position.
///
/// Generally: hupnl <= uhupnl <= upnl
#[inline(always)]
pub fn unweighted_health_unsettled_pnl(&self, health_type: HealthType) -> I80F48 {
let order_execution_case = |orders_base_lots: i64, order_price: I80F48| {
let net_base_native =
I80F48::from((self.base_lots + orders_base_lots) * self.base_lot_size);
let weight = match (health_type, net_base_native.is_negative()) {
(HealthType::Init, true) | (HealthType::LiquidationEnd, true) => {
self.init_base_liab_weight
}
(HealthType::Init, false) | (HealthType::LiquidationEnd, false) => {
self.init_base_asset_weight
}
(HealthType::Maint, true) => self.maint_base_liab_weight,
(HealthType::Maint, false) => self.maint_base_asset_weight,
};
let base_price = if net_base_native.is_negative() {
self.base_prices.liab(health_type)
} else {
self.base_prices.asset(health_type)
};
// Total value of the order-execution adjusted base position
let base_health = net_base_native * weight * base_price;
let orders_base_native = I80F48::from(orders_base_lots * self.base_lot_size);
// The quote change from executing the bids/asks
let order_quote = -orders_base_native * order_price;
base_health + order_quote
};
// What is worse: Executing all bids at oracle_price.liab, or executing all asks at oracle_price.asset?
let bids_case =
order_execution_case(self.bids_base_lots, self.base_prices.liab(health_type));
let asks_case =
order_execution_case(-self.asks_base_lots, self.base_prices.asset(health_type));
let worst_case = bids_case.min(asks_case);
self.quote + worst_case
}
}
/// Store information needed to compute account health
///
/// This is called a cache, because it extracts information from a MangoAccount and
/// the Bank, Perp, oracle accounts once and then allows computing different types
/// of health.
///
/// For compute-saving reasons, it also allows applying adjustments to the extracted
/// positions. That's often helpful for instructions that want to re-compute health
/// after having made small, well-known changes to an account. Recomputing the
/// HealthCache from scratch would be significantly more expensive.
///
/// However, there's a real risk of getting the adjustments wrong and computing an
/// inconsistent result, so particular care needs to be taken when this is done.
#[allow(unused)]
#[derive(Clone, Debug)]
pub struct HealthCache {
pub token_infos: Vec<TokenInfo>,
pub(crate) spot_infos: Vec<SpotInfo>,
pub(crate) perp_infos: Vec<PerpInfo>,
#[allow(unused)]
pub(crate) being_liquidated: bool,
}
impl HealthCache {
pub fn health(&self, health_type: HealthType) -> I80F48 {
let token_balances = self.effective_token_balances(health_type);
let mut health = I80F48::ZERO;
let sum = |contrib| {
health += contrib;
};
self.health_sum(health_type, sum, &token_balances);
health
}
/// The health ratio is
/// - 0 if health is 0 - meaning assets = liabs
/// - 100 if there's 2x as many assets as liabs
/// - 200 if there's 3x as many assets as liabs
/// - MAX if liabs = 0
///
/// Maybe talking about the collateralization ratio assets/liabs is more intuitive?
pub fn health_ratio(&self, health_type: HealthType) -> I80F48 {
let (assets, liabs) = self.health_assets_and_liabs_stable_liabs(health_type);
let hundred = I80F48::from(100);
if liabs > 0 {
// feel free to saturate to MAX for tiny liabs
(hundred * (assets - liabs)).saturating_div(liabs)
} else {
I80F48::MAX
}
}
pub fn health_assets_and_liabs_stable_assets(
&self,
health_type: HealthType,
) -> (I80F48, I80F48) {
self.health_assets_and_liabs(health_type, true)
}
pub fn health_assets_and_liabs_stable_liabs(
&self,
health_type: HealthType,
) -> (I80F48, I80F48) {
self.health_assets_and_liabs(health_type, false)
}
/// Loop over the token, perp, spot contributions and add up all positive values into `assets`
/// and (the abs) of negative values separately into `liabs`. Return (assets, liabs).
///
/// Due to the way token and perp positions sum before being weighted, there's some flexibility
/// in how the sum is split up. It can either be split up such that the amount of liabs stays
/// constant when assets change, or the other way around.
///
/// For example, if assets are held stable: An account with $10 in SOL and -$12 hupnl in a
/// SOL-settled perp market would have:
/// - assets: $10 * SOL_asset_weight
/// - liabs: $10 * SOL_asset_weight + $2 * SOL_liab_weight
/// because some of the liabs are weighted lower as they are just compensating the assets.
///
/// Same example if liabs are held stable:
/// - liabs: $12 * SOL_liab_weight
/// - assets: $10 * SOL_liab_weight
///
/// The value `assets - liabs` is the health and the same in both cases.
fn health_assets_and_liabs(
&self,
health_type: HealthType,
stable_assets: bool,
) -> (I80F48, I80F48) {
let mut total_assets = I80F48::ZERO;
let mut total_liabs = I80F48::ZERO;
let add = |assets: &mut I80F48, liabs: &mut I80F48, value: I80F48| {
if value > 0 {
*assets += value;
} else {
*liabs += -value;
}
};
for token_info in self.token_infos.iter() {
// For each token, health only considers the effective token position. But for
// this function we want to distinguish the contribution from token deposits from
// contributions by perp markets.
// However, the overall weight is determined by the sum, so first collect all
// assets parts and all liab parts and then determine the actual values.
let mut asset_balance = I80F48::ZERO;
let mut liab_balance = I80F48::ZERO;
add(
&mut asset_balance,
&mut liab_balance,
token_info.balance_spot,
);
for perp_info in self.perp_infos.iter() {
if perp_info.settle_token_index != token_info.token_index {
continue;
}
let health_unsettled = perp_info.health_unsettled_pnl(health_type);
add(&mut asset_balance, &mut liab_balance, health_unsettled);
}
// The assignment to total_assets and total_liabs is a bit arbitrary.
// As long as the (added_assets - added_liabs) = weighted(asset_balance - liab_balance),
// the result will be consistent.
if stable_assets {
let asset_weighted_price = token_info.asset_weighted_price(health_type);
let assets = asset_balance * asset_weighted_price;
total_assets += assets;
if asset_balance >= liab_balance {
// liabs partially compensate
total_liabs += liab_balance * asset_weighted_price;
} else {
let liab_weighted_price = token_info.liab_weighted_price(health_type);
// the liabs fully compensate the assets and even add something extra
total_liabs += assets + (liab_balance - asset_balance) * liab_weighted_price;
}
} else {
let liab_weighted_price = token_info.liab_weighted_price(health_type);
let liabs = liab_balance * liab_weighted_price;
total_liabs += liabs;
if asset_balance >= liab_balance {
let asset_weighted_price = token_info.asset_weighted_price(health_type);
// the assets fully compensate the liabs and even add something extra
total_assets += liabs + (asset_balance - liab_balance) * asset_weighted_price;
} else {
// assets partially compensate
total_assets += asset_balance * liab_weighted_price;
}
}
}
let token_balances = self.effective_token_balances(health_type);
let (token_max_reserved, spot_reserved) = self.compute_spot_reservations(health_type);
for (spot_info, reserved) in self.spot_infos.iter().zip(spot_reserved.iter()) {
let contrib = spot_info.health_contribution(
health_type,
&self.token_infos,
&token_balances,
&token_max_reserved,
reserved,
);
add(&mut total_assets, &mut total_liabs, contrib);
}
(total_assets, total_liabs)
}
/// Computes the account assets and liabilities marked to market.
///
/// Contrary to health_assets_and_liabs, there's no health weighing or adjustment
/// for stable prices. It uses oracle prices directly.
///
/// Returns (assets, liabilities)
pub fn assets_and_liabs(&self) -> (I80F48, I80F48) {
let mut assets = I80F48::ZERO;
let mut liabs = I80F48::ZERO;
for token_info in self.token_infos.iter() {
if token_info.balance_spot.is_negative() {
liabs -= token_info.balance_spot * token_info.prices.oracle;
} else {
assets += token_info.balance_spot * token_info.prices.oracle;
}
}
for spot_info in self.spot_infos.iter() {
let quote = &self.token_infos[spot_info.quote_info_index];
let base = &self.token_infos[spot_info.base_info_index];
assets += spot_info.reserved_base * base.prices.oracle;
assets += spot_info.reserved_quote * quote.prices.oracle;
}
for perp_info in self.perp_infos.iter() {
let quote_price = self.token_infos[perp_info.settle_token_index as usize]
.prices
.oracle;
let quote_position_value = perp_info.quote * quote_price;
if perp_info.quote.is_negative() {
liabs -= quote_position_value;
} else {
assets += quote_position_value;
}
let base_position_value = I80F48::from(perp_info.base_lots * perp_info.base_lot_size)
* perp_info.base_prices.oracle
* quote_price;
if base_position_value.is_negative() {
liabs -= base_position_value;
} else {
assets += base_position_value;
}
}
return (assets, liabs);
}
/// Computes the account leverage as ratio of liabs / (assets - liabs)
///
/// The goal of this function is to provide a quick overview over the accounts balance sheet.
/// It's not actually used to make any margin decisions internally and doesn't account for
/// open orders or stable / oracle price differences. Use health_ratio to make risk decisions.
pub fn leverage(&self) -> I80F48 {
let (assets, liabs) = self.assets_and_liabs();
let equity = assets - liabs;
liabs / equity.max(I80F48::from_num(0.001))
}
pub fn token_info(&self, token_index: TokenIndex) -> Result<&TokenInfo> {
Ok(&self.token_infos[self.token_info_index(token_index)?])
}
pub fn token_info_index(&self, token_index: TokenIndex) -> Result<usize> {
self.token_infos
.iter()
.position(|t| t.token_index == token_index)
.ok_or_else(|| {
error_msg_typed!(
MangoError::TokenPositionDoesNotExist,
"token index {} not found",
token_index
)
})
}
pub fn has_token_info(&self, token_index: TokenIndex) -> bool {
self.token_infos
.iter()
.any(|t| t.token_index == token_index)
}
pub fn perp_info(&self, perp_market_index: PerpMarketIndex) -> Result<&PerpInfo> {
Ok(&self.perp_infos[self.perp_info_index(perp_market_index)?])
}
pub(crate) fn perp_info_index(&self, perp_market_index: PerpMarketIndex) -> Result<usize> {
self.perp_infos
.iter()
.position(|t| t.perp_market_index == perp_market_index)
.ok_or_else(|| {
error_msg_typed!(
MangoError::PerpPositionDoesNotExist,
"perp market index {} not found",
perp_market_index
)
})
}
/// Changes the cached user account token balance.
pub fn adjust_token_balance(&mut self, bank: &Bank, change: I80F48) -> Result<()> {
let entry_index = self.token_info_index(bank.token_index)?;
let mut entry = &mut self.token_infos[entry_index];
// Note: resetting the weights here assumes that the change has been applied to
// the passed in bank already
entry.init_scaled_asset_weight =
bank.scaled_init_asset_weight(entry.prices.asset(HealthType::Init));
entry.init_scaled_liab_weight =
bank.scaled_init_liab_weight(entry.prices.liab(HealthType::Init));
// Work around the fact that -((-x) * y) == x * y does not hold for I80F48:
// We need to make sure that if balance is before * price, then change = -before
// brings it to exactly zero.
let removed_contribution = -change;
entry.balance_spot -= removed_contribution;
Ok(())
}
/// Recompute the cached information about a serum market.
///
/// WARNING: You must also call recompute_token_weights() after all bank
/// deposit/withdraw changes!
pub fn recompute_serum3_info(
&mut self,
serum_account: &Serum3Orders,
open_orders: &OpenOrdersSlim,
free_base_change: I80F48,
free_quote_change: I80F48,
) -> Result<()> {
let spot_info_index = self
.spot_infos
.iter_mut()
.position(|m| {
m.spot_market_index == SpotMarketIndex::Serum3(serum_account.market_index)
})
.ok_or_else(|| error_msg!("serum3 market {} not found", serum_account.market_index))?;
let spot_info = &self.spot_infos[spot_info_index];
{
let base_entry = &mut self.token_infos[spot_info.base_info_index];
base_entry.balance_spot += free_base_change;
}
{
let quote_entry = &mut self.token_infos[spot_info.quote_info_index];
quote_entry.balance_spot += free_quote_change;
}
let spot_info = &mut self.spot_infos[spot_info_index];
*spot_info = SpotInfo::new_from_serum(
serum_account,
open_orders,
spot_info.base_info_index,
spot_info.quote_info_index,
);
Ok(())
}
/// Recompute the cached information about a serum market.
///
/// WARNING: You must also call recompute_token_weights() after all bank
/// deposit/withdraw changes!
pub fn recompute_openbook_v2_info(
&mut self,
open_orders: &OpenbookV2Orders,
open_orders_account: &OpenOrdersAccount,
free_base_change: I80F48,
free_quote_change: I80F48,
) -> Result<()> {
let spot_info_index = self
.spot_infos
.iter_mut()
.position(|m| {
m.spot_market_index == SpotMarketIndex::OpenbookV2(open_orders.market_index)
})
.ok_or_else(|| {
error_msg!("openbook v2 market {} not found", open_orders.market_index)
})?;
let spot_info = &self.spot_infos[spot_info_index];
{
let base_entry = &mut self.token_infos[spot_info.base_info_index];
base_entry.balance_spot += free_base_change;
}
{
let quote_entry = &mut self.token_infos[spot_info.quote_info_index];
quote_entry.balance_spot += free_quote_change;
}
let spot_info = &mut self.spot_infos[spot_info_index];
*spot_info = SpotInfo::new_from_openbook(
open_orders_account,
open_orders,
spot_info.base_info_index,
spot_info.quote_info_index,
);
Ok(())
}
pub fn recompute_perp_info(
&mut self,
perp_position: &PerpPosition,
perp_market: &PerpMarket,
) -> Result<()> {
let perp_entry = self
.perp_infos
.iter_mut()
.find(|m| m.perp_market_index == perp_market.perp_market_index)
.ok_or_else(|| error_msg!("perp market {} not found", perp_market.perp_market_index))?;
*perp_entry = PerpInfo::new(perp_position, perp_market, perp_entry.base_prices.clone())?;
Ok(())
}
/// Liquidatable spot assets mean: actual token deposits and also a positive effective token balance
/// and is available for asset liquidation
pub fn has_liq_spot_assets(&self) -> bool {
let health_token_balances = self.effective_token_balances(HealthType::LiquidationEnd);
self.token_infos
.iter()
.zip(health_token_balances.iter())
.any(|(ti, b)| {
// need 1 native token to use token_liq_with_token
ti.balance_spot >= 1 && b.spot_and_perp >= 1 && ti.allow_asset_liquidation
})
}
/// Liquidatable spot borrows mean: actual token borrows plus a negative effective token balance
pub fn has_liq_spot_borrows(&self) -> bool {
let health_token_balances = self.effective_token_balances(HealthType::LiquidationEnd);
self.token_infos
.iter()
.zip(health_token_balances.iter())
.any(|(ti, b)| ti.balance_spot < 0 && b.spot_and_perp < 0)
}
// This function exists separately from has_liq_spot_assets and has_liq_spot_borrows for performance reasons
pub fn has_possible_spot_liquidations(&self) -> bool {
let health_token_balances = self.effective_token_balances(HealthType::LiquidationEnd);
let all_iter = || self.token_infos.iter().zip(health_token_balances.iter());
all_iter().any(|(ti, b)| ti.balance_spot < 0 && b.spot_and_perp < 0)
&& all_iter().any(|(ti, b)| {
ti.balance_spot >= 1 && b.spot_and_perp >= 1 && ti.allow_asset_liquidation
})
}
pub fn has_spot_open_orders_funds(&self) -> bool {
self.spot_infos.iter().any(|si| !si.has_zero_funds)
}
pub fn has_perp_open_orders(&self) -> bool {
self.perp_infos.iter().any(|p| p.has_open_orders)
}
pub fn has_perp_base_positions(&self) -> bool {
self.perp_infos.iter().any(|p| p.base_lots != 0)
}
pub fn has_perp_open_fills(&self) -> bool {
self.perp_infos.iter().any(|p| p.has_open_fills)
}
pub fn has_perp_positive_pnl_no_base(&self) -> bool {
self.perp_infos
.iter()
.any(|p| p.base_lots == 0 && p.quote > 0)
}
pub fn has_perp_negative_pnl_no_base(&self) -> bool {
self.perp_infos
.iter()
.any(|p| p.base_lots == 0 && p.quote < 0)
}
/// Phase1 is spot/perp order cancellation and spot settlement since
/// neither of these come at a cost to the liqee
pub fn has_phase1_liquidatable(&self) -> bool {
self.has_spot_open_orders_funds() || self.has_perp_open_orders()
}
pub fn require_after_phase1_liquidation(&self) -> Result<()> {
require!(
!self.has_spot_open_orders_funds(),
MangoError::HasOpenOrUnsettledSpotOrders
);
require!(!self.has_perp_open_orders(), MangoError::HasOpenPerpOrders);
Ok(())
}
pub fn in_phase1_liquidation(&self) -> bool {
self.has_phase1_liquidatable()
}
/// Phase2 is for:
/// - token-token liquidation
/// - liquidation of perp base positions (an open fill isn't liquidatable, but
/// it changes the base position, so need to wait for it to be processed...)
/// - bringing positive trusted perp pnl into the spot realm
pub fn has_phase2_liquidatable(&self) -> bool {
self.has_possible_spot_liquidations()
|| self.has_perp_base_positions()
|| self.has_perp_open_fills()
|| self.has_perp_positive_pnl_no_base()
}
pub fn require_after_phase2_liquidation(&self) -> Result<()> {
self.require_after_phase1_liquidation()?;
require!(
!self.has_possible_spot_liquidations(),
MangoError::HasLiquidatableTokenPosition
);
require!(
!self.has_perp_base_positions(),
MangoError::HasLiquidatablePerpBasePosition
);
require!(
!self.has_perp_open_fills(),
MangoError::HasOpenPerpTakerFills
);
require!(
!self.has_perp_positive_pnl_no_base(),
MangoError::HasLiquidatablePositivePerpPnl
);
Ok(())
}
pub fn in_phase2_liquidation(&self) -> bool {
!self.has_phase1_liquidatable() && self.has_phase2_liquidatable()
}
/// Phase3 is bankruptcy:
/// - token bankruptcy
/// - perp bankruptcy
pub fn has_phase3_liquidatable(&self) -> bool {
self.has_liq_spot_borrows() || self.has_perp_negative_pnl_no_base()
}
pub fn in_phase3_liquidation(&self) -> bool {
!self.has_phase1_liquidatable()
&& !self.has_phase2_liquidatable()
&& self.has_phase3_liquidatable()
}
pub(crate) fn compute_spot_reservations(
&self,
health_type: HealthType,
) -> (Vec<TokenMaxReserved>, Vec<SpotReserved>) {
let mut token_max_reserved = vec![TokenMaxReserved::default(); self.token_infos.len()];
// For each spot market, compute what happened if reserved_base was converted to quote
// or reserved_quote was converted to base.
let mut spot_reserved = Vec::with_capacity(self.spot_infos.len());
for info in self.spot_infos.iter() {
let quote_info = &self.token_infos[info.quote_info_index];
let base_info = &self.token_infos[info.base_info_index];
let all_reserved_as_base =
info.all_reserved_as_base(health_type, quote_info, base_info);
let all_reserved_as_quote =
info.all_reserved_as_quote(health_type, quote_info, base_info);
token_max_reserved[info.base_info_index].max_spot_reserved += all_reserved_as_base;
token_max_reserved[info.quote_info_index].max_spot_reserved += all_reserved_as_quote;
spot_reserved.push(SpotReserved {
all_reserved_as_base,
all_reserved_as_quote,
});
}
(token_max_reserved, spot_reserved)
}
/// Returns token balances that account for spot and perp contributions
///
/// Spot contributions are just the regular deposits or borrows, as well as from free
/// funds on spot open orders accounts.
///
/// Perp contributions come from perp positions in markets that use the token as a settle token:
/// For these the hupnl is added to the total because that's the risk-adjusted expected to be
/// gained or lost from settlement.
pub fn effective_token_balances(&self, health_type: HealthType) -> Vec<TokenBalance> {
self.effective_token_balances_internal(health_type, false)
}
/// Implementation of effective_token_balances()
///
/// The ignore_negative_perp flag exists for perp_max_settle(). When it is enabled, all negative
/// token contributions from perp markets are ignored. That's useful for knowing how much token
/// collateral is available when limiting negative upnl settlement.
fn effective_token_balances_internal(
&self,
health_type: HealthType,
ignore_negative_perp: bool,
) -> Vec<TokenBalance> {
let mut token_balances = vec![TokenBalance::default(); self.token_infos.len()];
for perp_info in self.perp_infos.iter() {
let settle_token_index = self.token_info_index(perp_info.settle_token_index).unwrap();
let perp_settle_token = &mut token_balances[settle_token_index];
let health_unsettled = perp_info.health_unsettled_pnl(health_type);
if !ignore_negative_perp || health_unsettled > 0 {
perp_settle_token.spot_and_perp += health_unsettled;
}
}
for (token_info, token_balance) in self.token_infos.iter().zip(token_balances.iter_mut()) {
token_balance.spot_and_perp += token_info.balance_spot;
}
token_balances
}
pub(crate) fn health_sum(
&self,
health_type: HealthType,
mut action: impl FnMut(I80F48),
token_balances: &[TokenBalance],
) {
for (token_info, token_balance) in self.token_infos.iter().zip(token_balances.iter()) {
let contrib = token_info.health_contribution(health_type, token_balance.spot_and_perp);
action(contrib);
}
let (token_max_reserved, spot_reserved) = self.compute_spot_reservations(health_type);
for (spot_info, reserved) in self.spot_infos.iter().zip(spot_reserved.iter()) {
let contrib = spot_info.health_contribution(
health_type,
&self.token_infos,
&token_balances,
&token_max_reserved,
reserved,
);
action(contrib);
}
}
/// Returns how much pnl is settleable for a given settle token.
///
/// The idea of this limit is that settlement is only permissible as long as there are
/// non-perp assets that back it. If an account with 1 USD deposited somehow gets
/// a large negative perp upnl, it should not be allowed to settle that perp loss into
/// the spot world fully (because of perp/spot isolation, translating perp losses and
/// gains into tokens is restricted). Only 1 USD worth would be allowed.
///
/// Effectively, there's a health variant "perp settle health" that ignores negative
/// token contributions from perp markets. Settlement is allowed as long as perp settle
/// health remains >= 0.
///
/// For example, if perp_settle_health is 50 USD, then the settleable amount in SOL
/// would depend on the SOL price, the user's current spot balance and the SOL weights:
/// We need to compute how much the user's spot SOL balance may decrease before the
/// perp_settle_health becomes zero.
///
/// Note that the account's actual health would not change during settling negative upnl:
/// the spot balance goes down but the perp hupnl goes up accordingly.
///
/// Examples:
/// - An account may have maint_health < 0, but settling perp pnl could still be allowed.
/// (+100 USDC health, -50 USDT health, -50 perp health -> allow settling 50 health worth)
/// - Positive health from trusted pnl markets counts
/// - If overall health is 0 with two trusted perp pnl < 0, settling may still be possible.
/// (+100 USDC health, -150 perp1 health, -150 perp2 health -> allow settling 100 health worth)
/// - Positive trusted perp pnl can enable settling.
/// (+100 trusted perp1 health, -100 perp2 health -> allow settling of 100 health worth)
pub fn perp_max_settle(&self, settle_token_index: TokenIndex) -> Result<I80F48> {
let maint_type = HealthType::Maint;
let token_balances = self.effective_token_balances_internal(maint_type, true);
let mut perp_settle_health = I80F48::ZERO;
let sum = |contrib| {
perp_settle_health += contrib;
};
self.health_sum(maint_type, sum, &token_balances);
let token_info_index = self.token_info_index(settle_token_index)?;
let token = &self.token_infos[token_info_index];
spot_amount_taken_for_health_zero(
perp_settle_health,
token_balances[token_info_index].spot_and_perp,
token.asset_weighted_price(maint_type),
token.liab_weighted_price(maint_type),
)
}
pub fn total_spot_potential(
&self,
health_type: HealthType,
token_index: TokenIndex,
) -> Result<I80F48> {
let target_token_info_index = self.token_info_index(token_index)?;
let total_reserved = self
.spot_infos
.iter()
.filter_map(|info| {
if info.quote_info_index == target_token_info_index {
Some(info.all_reserved_as_quote(
health_type,
&self.token_infos[info.quote_info_index],
&self.token_infos[info.base_info_index],
))
} else if info.base_info_index == target_token_info_index {
Some(info.all_reserved_as_base(
health_type,
&self.token_infos[info.quote_info_index],
&self.token_infos[info.base_info_index],
))
} else {
None
}
})
.sum();
Ok(total_reserved)
}
/// Verifies that the health cache has information on all account's active spot markets that
/// touch the token_index
pub fn check_has_all_spot_infos_for_token(
&self,
account: &MangoAccountRef,
token_index: TokenIndex,
) -> Result<()> {
for serum3 in account.active_serum3_orders() {
if serum3.base_token_index == token_index || serum3.quote_token_index == token_index {
require_msg!(
self.spot_infos.iter().any(|s| s.spot_market_index == SpotMarketIndex::Serum3(serum3.market_index)),
"health cache is missing spot info for serum3 market {} involving receiver token {}; passed banks and oracles?",
serum3.market_index, token_index
);
}
}
for oov2 in account.active_openbook_v2_orders() {
if oov2.base_token_index == token_index || oov2.quote_token_index == token_index {
require_msg!(
self.spot_infos.iter().any(|s| s.spot_market_index == SpotMarketIndex::OpenbookV2(oov2.market_index)),
"health cache is missing spot info for oov2 market {} involving receiver token {}; passed banks and oracles?",
oov2.market_index, token_index
);
}
}
Ok(())
}
}
pub(crate) fn find_token_info_index(infos: &[TokenInfo], token_index: TokenIndex) -> Result<usize> {
infos
.iter()
.position(|ti| ti.token_index == token_index)
.ok_or_else(|| {
error_msg_typed!(
MangoError::TokenPositionDoesNotExist,
"token index {} not found",
token_index
)
})
}
/// Generate a HealthCache for an account and its health accounts.
pub fn new_health_cache(
account: &MangoAccountRef,
retriever: &impl AccountRetriever,
now_ts: u64,
) -> Result<HealthCache> {
new_health_cache_impl(account, retriever, now_ts, false)
}
/// Generate a special HealthCache for an account and its health accounts
/// where nonnegative token positions for bad oracles are skipped as well as missing banks.
///
/// This health cache must be used carefully, since it doesn't provide the actual
/// account health, just a value that is guaranteed to be less than it.
pub fn new_health_cache_skipping_missing_banks_and_bad_oracles(
account: &MangoAccountRef,
retriever: &impl AccountRetriever,
now_ts: u64,
) -> Result<HealthCache> {
new_health_cache_impl(account, retriever, now_ts, true)
}
// On `allow_skipping_banks`:
// If (a Bank is not provided or its oracle is stale or inconfident) and the health contribution would
// not be negative, skip it. This decreases health, but many operations are still allowed as long
// as the decreased amount stays positive.
fn new_health_cache_impl(
account: &MangoAccountRef,
retriever: &impl AccountRetriever,
now_ts: u64,
allow_skipping_banks: bool,
) -> Result<HealthCache> {
// token contribution from token accounts
let mut token_infos = Vec::with_capacity(account.active_token_positions().count());
// As a CU optimization, don't call available_banks() unless necessary
let available_banks_opt = if allow_skipping_banks {
Some(retriever.available_banks()?)
} else {
None
};
for (i, position) in account.active_token_positions().enumerate() {
// Allow skipping of missing banks only if the account has a nonnegative balance
if allow_skipping_banks {
let bank_is_available = available_banks_opt
.as_ref()
.unwrap()
.contains(&position.token_index);
if !bank_is_available {
require_msg_typed!(
position.indexed_position >= 0,
MangoError::InvalidBank,
"the bank for token index {} is a required health account when the account has a negative balance in it",
position.token_index
);
continue;
}
}
let bank_oracle_result =
retriever.bank_and_oracle(&account.fixed.group, i, position.token_index);
// Allow skipping of bad-oracle banks if the account has a nonnegative balance
if allow_skipping_banks
&& bank_oracle_result.is_oracle_error()
&& position.indexed_position >= 0
{
// Ignore the asset because the oracle is bad, decreasing total health
continue;
}
let (bank, oracle_price) = bank_oracle_result?;
let native = position.native(bank);
let prices = Prices {
oracle: oracle_price,
stable: bank.stable_price(),
};
// Use the liab price for computing weight scaling, because it's pessimistic and
// causes the most unfavorable scaling.
let liab_price = prices.liab(HealthType::Init);
let (maint_asset_weight, maint_liab_weight) = bank.maint_weights(now_ts);
token_infos.push(TokenInfo {
token_index: bank.token_index,
maint_asset_weight,
init_asset_weight: bank.init_asset_weight,
init_scaled_asset_weight: bank.scaled_init_asset_weight(liab_price),
maint_liab_weight,
init_liab_weight: bank.init_liab_weight,
init_scaled_liab_weight: bank.scaled_init_liab_weight(liab_price),
prices,
balance_spot: native,
allow_asset_liquidation: bank.allows_asset_liquidation(),
});
}
// Fill the TokenInfo balance with free funds in serum3 and openbook v2 oo accounts and build Spot3Infos.
let mut spot_infos = Vec::with_capacity(
account.active_serum3_orders().count() + account.active_openbook_v2_orders().count(),
);
for (i, serum_account) in account.active_serum3_orders().enumerate() {
let oo = retriever.serum_oo(i, &serum_account.open_orders)?;
// find the TokenInfos for the market's base and quote tokens
// and potentially skip the whole serum contribution if they are not available
let info_index_results = (
find_token_info_index(&token_infos, serum_account.base_token_index),
find_token_info_index(&token_infos, serum_account.quote_token_index),
);
let (base_info_index, quote_info_index) = match info_index_results {
(Ok(base), Ok(quote)) => (base, quote),
_ => {
require_msg_typed!(
allow_skipping_banks,
MangoError::InvalidBank,
"serum market {} misses health accounts for bank {} or {}",
serum_account.market_index,
serum_account.base_token_index,
serum_account.quote_token_index,
);
continue;
}
};
// add the amounts that are freely settleable immediately to token balances
let base_free = I80F48::from(oo.native_coin_free);
let quote_free = I80F48::from(oo.native_pc_free);
let base_info = &mut token_infos[base_info_index];
base_info.balance_spot += base_free;
let quote_info = &mut token_infos[quote_info_index];
quote_info.balance_spot += quote_free;
spot_infos.push(SpotInfo::new_from_serum(
serum_account,
oo,
base_info_index,
quote_info_index,
));
}
for (i, open_orders_account) in account.active_openbook_v2_orders().enumerate() {
let oo = retriever.openbook_oo(i, &open_orders_account.open_orders)?;
// find the TokenInfos for the market's base and quote tokens
// and potentially skip the whole openbook v2 contribution if they are not available
let info_index_results = (
find_token_info_index(&token_infos, open_orders_account.base_token_index),
find_token_info_index(&token_infos, open_orders_account.quote_token_index),
);
let (base_info_index, quote_info_index) = match info_index_results {
(Ok(base), Ok(quote)) => (base, quote),
_ => {
require_msg_typed!(
allow_skipping_banks,
MangoError::InvalidBank,
"openbook-v2 market {} misses health accounts for bank {} or {}",
open_orders_account.market_index,
open_orders_account.base_token_index,
open_orders_account.quote_token_index,
);
continue;
}
};
// add the amounts that are freely settleable immediately to token balances
let base_free = I80F48::from(oo.position.base_free_native);
let quote_free = I80F48::from(oo.position.quote_free_native);
let base_info = &mut token_infos[base_info_index];
base_info.balance_spot += base_free;
let quote_info = &mut token_infos[quote_info_index];
quote_info.balance_spot += quote_free;
spot_infos.push(SpotInfo::new_from_openbook(
&oo,
open_orders_account,
base_info_index,
quote_info_index,
));
}
// health contribution from perp accounts
let mut perp_infos = Vec::with_capacity(account.active_perp_positions().count());
for (i, perp_position) in account.active_perp_positions().enumerate() {
let (perp_market, oracle_price) = retriever.perp_market_and_oracle_price(
&account.fixed.group,
i,
perp_position.market_index,
)?;
// Ensure the settle token is available in the health cache
if allow_skipping_banks {
find_token_info_index(&token_infos, perp_market.settle_token_index)?;
}
perp_infos.push(PerpInfo::new(
perp_position,
perp_market,
Prices {
oracle: oracle_price,
stable: perp_market.stable_price(),
},
)?);
}
Ok(HealthCache {
token_infos,
spot_infos,
perp_infos,
being_liquidated: account.fixed.being_liquidated(),
})
}
#[cfg(test)]
mod tests {
use super::super::test::*;
use super::*;
use crate::state::*;
use serum_dex::state::OpenOrders;
use std::str::FromStr;
#[test]
fn test_precision() {
// I80F48 can only represent until 1/2^48
assert_ne!(
I80F48::from_num(1_u128) / I80F48::from_num(2_u128.pow(48)),
0
);
assert_eq!(
I80F48::from_num(1_u128) / I80F48::from_num(2_u128.pow(49)),
0
);
// I80F48 can only represent until 14 decimal points
assert_ne!(
I80F48::from_str(format!("0.{}1", "0".repeat(13)).as_str()).unwrap(),
0
);
assert_eq!(
I80F48::from_str(format!("0.{}1", "0".repeat(14)).as_str()).unwrap(),
0
);
}
fn health_eq(a: I80F48, b: f64) -> bool {
if (a - I80F48::from_num(b)).abs() < 0.001 {
true
} else {
println!("health is {}, but expected {}", a, b);
false
}
}
// Run a health test that includes all the side values (like referrer_rebates_accrued)
#[test]
fn test_health0() {
let buffer = MangoAccount::default_for_tests().try_to_vec().unwrap();
let mut account = MangoAccountValue::from_bytes(&buffer).unwrap();
let group = Pubkey::new_unique();
let (mut bank1, mut oracle1) = mock_bank_and_oracle(group, 0, 1.0, 0.2, 0.1); // 0.5
let (mut bank2, mut oracle2) = mock_bank_and_oracle(group, 4, 5.0, 0.5, 0.3); // 0.2
bank1
.data()
.deposit(
account.ensure_token_position(0).unwrap().0,
I80F48::from(100),
DUMMY_NOW_TS,
)
.unwrap();
bank2
.data()
.withdraw_without_fee(
account.ensure_token_position(4).unwrap().0,
I80F48::from(10),
DUMMY_NOW_TS,
)
.unwrap();
// 100 quote -10 base
let mut oo1 = TestAccount::<OpenOrders>::new_zeroed();
let serum3account = account.create_serum3_orders(2).unwrap();
serum3account.open_orders = oo1.pubkey;
serum3account.base_token_index = 4;
serum3account.quote_token_index = 0;
oo1.data().native_pc_total = 21;
oo1.data().native_coin_total = 18;
oo1.data().native_pc_free = 1;
oo1.data().native_coin_free = 3;
oo1.data().referrer_rebates_accrued = 2;
let mut oo2 = TestAccount::<OpenOrdersAccount>::new_zeroed();
let openbookv2account = account.create_openbook_v2_orders(2).unwrap();
openbookv2account.open_orders = oo2.pubkey;
openbookv2account.base_token_index = 4;
openbookv2account.quote_token_index = 0;
openbookv2account.potential_quote_tokens = 20;
openbookv2account.potential_base_tokens = 15;
openbookv2account.market_index = 2;
openbookv2account.base_lot_size = 1;
openbookv2account.quote_lot_size = 1;
oo2.data().position.quote_free_native = 1;
oo2.data().position.base_free_native = 3;
oo2.data().position.referrer_rebates_available = 2;
let mut perp1 = mock_perp_market(group, oracle2.pubkey, 5.0, 9, (0.2, 0.1), (0.05, 0.02));
let perpaccount = account.ensure_perp_position(9, 0).unwrap().0;
perpaccount.record_trade(perp1.data(), 3, -I80F48::from(310u16));
perpaccount.bids_base_lots = 7;
perpaccount.asks_base_lots = 11;
perpaccount.taker_base_lots = 1;
perpaccount.taker_quote_lots = 2;
let oracle2_ai = oracle2.as_account_info();
let ais = vec![
bank1.as_account_info(),
bank2.as_account_info(),
oracle1.as_account_info(),
oracle2_ai.clone(),
perp1.as_account_info(),
oracle2_ai,
oo1.as_account_info(),
oo2.as_account_info(),
];
let retriever = ScanningAccountRetriever::new_with_staleness(&ais, &group, None).unwrap();
// for bank1/oracle1
// including open orders (scenario: bids execute)
let serum1 = 1.0 + (20.0 + 15.0 * 5.0);
let openbook1 = 1.0 + (20.0 + 15.0 * 5.0);
// and perp (scenario: bids execute)
let perp1 =
(3.0 + 7.0 + 1.0) * 10.0 * 5.0 * 0.8 + (-310.0 + 2.0 * 100.0 - 7.0 * 10.0 * 5.0);
let health1 = (100.0 + serum1 + openbook1) * 0.8;
// for bank2/oracle2
let health2 = (-20.0 + 3.0 + 3.0) * 5.0 * 1.5;
// assert!(health_eq(
// compute_health(&account.borrow(), HealthType::Init, &retriever, 0).unwrap(),
// health1 + health2
// ));
}
#[derive(Default)]
struct BankSettings {
deposits: u64,
borrows: u64,
deposit_weight_scale_start_quote: u64,
borrow_weight_scale_start_quote: u64,
potential_serum_tokens: u64,
potential_openbook_tokens: u64,
}
#[derive(Default)]
struct TestHealth1Case {
token1: i64,
token2: i64,
token3: i64,
oo_1_2: (u64, u64),
oo_1_3: (u64, u64),
oov2_1_2: (u64, u64),
oov2_1_3: (u64, u64),
perp1: (i64, i64, i64, i64),
expected_health: f64,
bank_settings: [BankSettings; 3],
extra: Option<fn(&mut MangoAccountValue)>,
}
fn test_health1_runner(testcase: &TestHealth1Case) {
let buffer = MangoAccount::default_for_tests().try_to_vec().unwrap();
let mut account = MangoAccountValue::from_bytes(&buffer).unwrap();
let group = Pubkey::new_unique();
let (mut bank1, mut oracle1) = mock_bank_and_oracle(group, 0, 1.0, 0.2, 0.1);
let (mut bank2, mut oracle2) = mock_bank_and_oracle(group, 4, 5.0, 0.5, 0.3);
let (mut bank3, mut oracle3) = mock_bank_and_oracle(group, 5, 10.0, 0.5, 0.3);
bank1
.data()
.change_without_fee(
account.ensure_token_position(0).unwrap().0,
I80F48::from(testcase.token1),
DUMMY_NOW_TS,
)
.unwrap();
bank2
.data()
.change_without_fee(
account.ensure_token_position(4).unwrap().0,
I80F48::from(testcase.token2),
DUMMY_NOW_TS,
)
.unwrap();
bank3
.data()
.change_without_fee(
account.ensure_token_position(5).unwrap().0,
I80F48::from(testcase.token3),
DUMMY_NOW_TS,
)
.unwrap();
for (settings, bank) in testcase
.bank_settings
.iter()
.zip([&mut bank1, &mut bank2, &mut bank3].iter_mut())
{
let bank = bank.data();
bank.indexed_deposits = I80F48::from(settings.deposits) / bank.deposit_index;
bank.indexed_borrows = I80F48::from(settings.borrows) / bank.borrow_index;
bank.potential_serum_tokens = settings.potential_serum_tokens;
bank.potential_openbook_tokens = settings.potential_openbook_tokens;
if settings.deposit_weight_scale_start_quote > 0 {
bank.deposit_weight_scale_start_quote =
settings.deposit_weight_scale_start_quote as f64;
}
if settings.borrow_weight_scale_start_quote > 0 {
bank.borrow_weight_scale_start_quote =
settings.borrow_weight_scale_start_quote as f64;
}
}
let mut oo1 = TestAccount::<OpenOrders>::new_zeroed();
let serum3account1 = account.create_serum3_orders(2).unwrap();
serum3account1.open_orders = oo1.pubkey;
serum3account1.base_token_index = 4;
serum3account1.quote_token_index = 0;
oo1.data().native_pc_total = testcase.oo_1_2.0;
oo1.data().native_coin_total = testcase.oo_1_2.1;
let mut oo2 = TestAccount::<OpenOrders>::new_zeroed();
let serum3account2 = account.create_serum3_orders(3).unwrap();
serum3account2.open_orders = oo2.pubkey;
serum3account2.base_token_index = 5;
serum3account2.quote_token_index = 0;
oo2.data().native_pc_total = testcase.oo_1_3.0;
oo2.data().native_coin_total = testcase.oo_1_3.1;
let mut oov2_1 = TestAccount::<OpenOrdersAccount>::new_zeroed();
let openbookv2account = account.create_openbook_v2_orders(2).unwrap();
openbookv2account.open_orders = oov2_1.pubkey;
openbookv2account.base_token_index = 4;
openbookv2account.quote_token_index = 0;
openbookv2account.base_lot_size = 1;
openbookv2account.quote_lot_size = 1;
oov2_1.data().position.bids_quote_lots = testcase.oov2_1_2.0 as i64;
oov2_1.data().position.asks_base_lots = testcase.oov2_1_2.1 as i64;
let mut oov2_2 = TestAccount::<OpenOrdersAccount>::new_zeroed();
let openbookv2account2 = account.create_openbook_v2_orders(3).unwrap();
openbookv2account2.open_orders = oov2_2.pubkey;
openbookv2account2.base_token_index = 5;
openbookv2account2.quote_token_index = 0;
openbookv2account2.base_lot_size = 1;
openbookv2account2.quote_lot_size = 1;
oov2_2.data().position.bids_quote_lots = testcase.oov2_1_3.0 as i64;
oov2_2.data().position.asks_base_lots = testcase.oov2_1_3.1 as i64;
let mut perp1 = mock_perp_market(group, oracle2.pubkey, 5.0, 9, (0.2, 0.1), (0.05, 0.02));
let perpaccount = account.ensure_perp_position(9, 0).unwrap().0;
perpaccount.record_trade(
perp1.data(),
testcase.perp1.0,
I80F48::from(testcase.perp1.1),
);
perpaccount.bids_base_lots = testcase.perp1.2;
perpaccount.asks_base_lots = testcase.perp1.3;
if let Some(extra_fn) = testcase.extra {
extra_fn(&mut account);
}
let oracle2_ai = oracle2.as_account_info();
let ais = vec![
bank1.as_account_info(),
bank2.as_account_info(),
bank3.as_account_info(),
oracle1.as_account_info(),
oracle2_ai.clone(),
oracle3.as_account_info(),
perp1.as_account_info(),
oracle2_ai,
oo1.as_account_info(),
oo2.as_account_info(),
oov2_1.as_account_info(),
oov2_2.as_account_info(),
];
let retriever = ScanningAccountRetriever::new_with_staleness(&ais, &group, None).unwrap();
assert!(health_eq(
compute_health(&account.borrow(), HealthType::Init, &retriever, 0).unwrap(),
testcase.expected_health
));
}
// Check some specific health constellations
#[test]
fn test_health1() {
let base_price = 5.0;
let base_lots_to_quote = 10.0 * base_price;
let testcases = vec![
TestHealth1Case { // 0
token1: 100,
token2: -10,
oo_1_2: (20, 15),
perp1: (3, -131, 7, 11),
expected_health:
// for token1
0.8 * (100.0
// including open orders (scenario: bids execute)
+ (20.0 + 15.0 * base_price)
// including perp (scenario: bids execute)
+ (3.0 + 7.0) * base_lots_to_quote * 0.8 + (-131.0 - 7.0 * base_lots_to_quote))
// for token2
- 10.0 * base_price * 1.5,
..Default::default()
},
TestHealth1Case { // 1
token1: -100,
token2: 10,
oo_1_2: (20, 15),
perp1: (-10, -131, 7, 11),
expected_health:
// for token1
1.2 * (-100.0
// for perp (scenario: asks execute)
+ (-10.0 - 11.0) * base_lots_to_quote * 1.2 + (-131.0 + 11.0 * base_lots_to_quote))
// for token2, including open orders (scenario: asks execute)
+ (10.0 * base_price + (20.0 + 15.0 * base_price)) * 0.5,
..Default::default()
},
TestHealth1Case {
// 2: weighted positive perp pnl
perp1: (-1, 100, 0, 0),
expected_health: 0.8 * 0.95 * (100.0 - 1.2 * 1.0 * base_lots_to_quote),
..Default::default()
},
TestHealth1Case {
// 3: negative perp pnl is not weighted (only the settle token weight)
perp1: (1, -100, 0, 0),
expected_health: 1.2 * (-100.0 + 0.8 * 1.0 * base_lots_to_quote),
..Default::default()
},
TestHealth1Case {
// 4: perp health
perp1: (10, 100, 0, 0),
expected_health: 0.8 * 0.95 * (100.0 + 0.8 * 10.0 * base_lots_to_quote),
..Default::default()
},
TestHealth1Case {
// 5: perp health
perp1: (30, -100, 0, 0),
expected_health: 0.8 * 0.95 * (-100.0 + 0.8 * 30.0 * base_lots_to_quote),
..Default::default()
},
TestHealth1Case { // 6, reserved oo funds
token1: -100,
token2: -10,
token3: -10,
oo_1_2: (1, 1),
oo_1_3: (1, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5 - 10.0 * 10.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 5.0) * 1.2
// oo_1_3 (-> token1)
+ (1.0 + 10.0) * 1.2,
..Default::default()
},
TestHealth1Case { // 7, reserved oo funds cross the zero balance level
token1: -14,
token2: -10,
token3: -10,
oo_1_2: (1, 1),
oo_1_3: (1, 1),
expected_health:
// tokens
-14.0 * 1.2 - 10.0 * 5.0 * 1.5 - 10.0 * 10.0 * 1.5
// oo_1_2 (-> token1)
+ 3.0 * 1.2 + 3.0 * 0.8
// oo_1_3 (-> token1)
+ 8.0 * 1.2 + 3.0 * 0.8,
..Default::default()
},
TestHealth1Case { // 8, reserved oo funds in a non-quote currency
token1: -100,
token2: -100,
token3: -1,
oo_1_2: (0, 0),
oo_1_3: (10, 1),
expected_health:
// tokens
-100.0 * 1.2 - 100.0 * 5.0 * 1.5 - 10.0 * 1.5
// oo_1_3 (-> token3)
+ 10.0 * 1.5 + 10.0 * 0.5,
..Default::default()
},
TestHealth1Case { // 9, like 8 but oo_1_2 flips the oo_1_3 target
token1: -100,
token2: -100,
token3: -1,
oo_1_2: (100, 0),
oo_1_3: (10, 1),
expected_health:
// tokens
-100.0 * 1.2 - 100.0 * 5.0 * 1.5 - 10.0 * 1.5
// oo_1_2 (-> token1)
+ 80.0 * 1.2 + 20.0 * 0.8
// oo_1_3 (-> token1)
+ 20.0 * 0.8,
..Default::default()
},
TestHealth1Case { // 10, checking collateral limit
token1: 100,
token2: 100,
token3: 100,
bank_settings: [
BankSettings {
deposits: 100,
deposit_weight_scale_start_quote: 1000,
..BankSettings::default()
},
BankSettings {
deposits: 1500,
deposit_weight_scale_start_quote: 1000 * 5,
..BankSettings::default()
},
BankSettings {
deposits: 10000,
deposit_weight_scale_start_quote: 1000 * 10,
..BankSettings::default()
},
],
expected_health:
// token1
0.8 * 100.0
// token2
+ 0.5 * 100.0 * 5.0 * (5000.0 / (1500.0 * 5.0))
// token3
+ 0.5 * 100.0 * 10.0 * (10000.0 / (10000.0 * 10.0)),
..Default::default()
},
TestHealth1Case { // 11, checking borrow limit
token1: -100,
token2: -100,
token3: -100,
bank_settings: [
BankSettings {
borrows: 100,
borrow_weight_scale_start_quote: 1000,
..BankSettings::default()
},
BankSettings {
borrows: 1500,
borrow_weight_scale_start_quote: 1000 * 5,
..BankSettings::default()
},
BankSettings {
borrows: 10000,
borrow_weight_scale_start_quote: 1000 * 10,
..BankSettings::default()
},
],
expected_health:
// token1
-1.2 * 100.0
// token2
- 1.5 * 100.0 * 5.0 * (1500.0 * 5.0 / 5000.0)
// token3
- 1.5 * 100.0 * 10.0 * (10000.0 * 10.0 / 10000.0),
..Default::default()
},
TestHealth1Case {
// 12: positive perp health offsets token borrow
token1: -100,
perp1: (1, 100, 0, 0),
expected_health: 0.8 * (-100.0 + 0.95 * (100.0 + 0.8 * 1.0 * base_lots_to_quote)),
..Default::default()
},
TestHealth1Case {
// 13: negative perp health offsets token deposit
token1: 100,
perp1: (-1, -100, 0, 0),
expected_health: 1.2 * (100.0 - 100.0 - 1.2 * 1.0 * base_lots_to_quote),
..Default::default()
},
TestHealth1Case {
// 14, reserved oo funds with max bid/min ask
token1: -100,
token2: -10,
token3: 0,
oo_1_2: (1, 1),
oo_1_3: (11, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 3.0) * 1.2
// oo_1_3 (-> token3)
+ (11.0 / 12.0 + 1.0) * 10.0 * 0.5,
extra: Some(|account: &mut MangoAccountValue| {
let s2 = account.serum3_orders_mut(2).unwrap();
s2.lowest_placed_ask = 3.0;
let s3 = account.serum3_orders_mut(3).unwrap();
s3.highest_placed_bid_inv = 1.0 / 12.0;
}),
..Default::default()
},
TestHealth1Case {
// 15, reserved oo funds with max bid/min ask not crossing oracle
token1: -100,
token2: -10,
token3: 0,
oo_1_2: (1, 1),
oo_1_3: (11, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 5.0) * 1.2
// oo_1_3 (-> token3)
+ (11.0 / 10.0 + 1.0) * 10.0 * 0.5,
extra: Some(|account: &mut MangoAccountValue| {
let s2 = account.serum3_orders_mut(2).unwrap();
s2.lowest_placed_ask = 6.0;
let s3 = account.serum3_orders_mut(3).unwrap();
s3.highest_placed_bid_inv = 1.0 / 9.0;
}),
..Default::default()
},
TestHealth1Case {
// 16, base case for 17
token1: 100,
token2: 100,
token3: 100,
oo_1_2: (0, 100),
oo_1_3: (0, 100),
expected_health:
// tokens
100.0 * 0.8 + 100.0 * 5.0 * 0.5 + 100.0 * 10.0 * 0.5
// oo_1_2 (-> token2)
+ 100.0 * 5.0 * 0.5
// oo_1_3 (-> token1)
+ 100.0 * 10.0 * 0.5,
..Default::default()
},
TestHealth1Case {
// 17, potential_serum_tokens counts for deposit weight scaling
token1: 100,
token2: 100,
token3: 100,
oo_1_2: (0, 100),
oo_1_3: (0, 100),
bank_settings: [
BankSettings {
..BankSettings::default()
},
BankSettings {
deposits: 100,
deposit_weight_scale_start_quote: 100 * 5,
potential_serum_tokens: 100,
..BankSettings::default()
},
BankSettings {
deposits: 600,
deposit_weight_scale_start_quote: 500 * 10,
potential_serum_tokens: 100,
..BankSettings::default()
},
],
expected_health:
// tokens
100.0 * 0.8 + 100.0 * 5.0 * 0.5 * (100.0 / 200.0) + 100.0 * 10.0 * 0.5 * (500.0 / 700.0)
// oo_1_2 (-> token2)
+ 100.0 * 5.0 * 0.5 * (100.0 / 200.0)
// oo_1_3 (-> token1)
+ 100.0 * 10.0 * 0.5 * (500.0 / 700.0),
..Default::default()
},
TestHealth1Case { // 18, like 0 with obv2
token1: 100,
token2: -10,
oov2_1_2: (20, 15),
expected_health:
// for token1
0.8 * (100.0
// including open orders (scenario: bids execute)
+ (20.0 + 15.0 * base_price))
// for token2
- 10.0 * base_price * 1.5,
..Default::default()
},
TestHealth1Case { // 19, like 1 with obv2
token1: -100,
token2: 10,
oov2_1_2: (20, 15),
expected_health:
// for token1
1.2 * (-100.0)
// for token2, including open orders (scenario: asks execute)
+ (10.0 * base_price + (20.0 + 15.0 * base_price)) * 0.5,
..Default::default()
},
TestHealth1Case { // 20, reserved oo funds, like 6 with obv2
token1: -100,
token2: -10,
token3: -10,
oov2_1_2: (1, 1),
oov2_1_3: (1, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5 - 10.0 * 10.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 5.0) * 1.2
// oo_1_3 (-> token1)
+ (1.0 + 10.0) * 1.2,
..Default::default()
},
TestHealth1Case { // 21, reserved oo funds cross the zero balance level, like 7 with obv2
token1: -14,
token2: -10,
token3: -10,
oov2_1_2: (1, 1),
oov2_1_3: (1, 1),
expected_health:
// tokens
-14.0 * 1.2 - 10.0 * 5.0 * 1.5 - 10.0 * 10.0 * 1.5
// oo_1_2 (-> token1)
+ 3.0 * 1.2 + 3.0 * 0.8
// oo_1_3 (-> token1)
+ 8.0 * 1.2 + 3.0 * 0.8,
..Default::default()
},
TestHealth1Case { // 22, reserved oo funds in a non-quote currency, like 8 with obv2
token1: -100,
token2: -100,
token3: -1,
oov2_1_2: (0, 0),
oov2_1_3: (10, 1),
expected_health:
// tokens
-100.0 * 1.2 - 100.0 * 5.0 * 1.5 - 10.0 * 1.5
// oo_1_3 (-> token3)
+ 10.0 * 1.5 + 10.0 * 0.5,
..Default::default()
},
TestHealth1Case { // 23, like 8 but oo_1_2 flips the oo_1_3 target, like 9 with obv2
token1: -100,
token2: -100,
token3: -1,
oov2_1_2: (100, 0),
oov2_1_3: (10, 1),
expected_health:
// tokens
-100.0 * 1.2 - 100.0 * 5.0 * 1.5 - 10.0 * 1.5
// oo_1_2 (-> token1)
+ 80.0 * 1.2 + 20.0 * 0.8
// oo_1_3 (-> token1)
+ 20.0 * 0.8,
..Default::default()
},
TestHealth1Case {
// 24, reserved oo funds with max bid/min ask, like 14 with obv2
token1: -100,
token2: -10,
token3: 0,
oov2_1_2: (1, 1),
oov2_1_3: (11, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 3.0) * 1.2
// oo_1_3 (-> token3)
+ (11.0 / 12.0 + 1.0) * 10.0 * 0.5,
extra: Some(|account: &mut MangoAccountValue| {
let s2 = account.openbook_v2_orders_mut(2).unwrap();
s2.lowest_placed_ask = 3.0;
let s3 = account.openbook_v2_orders_mut(3).unwrap();
s3.highest_placed_bid_inv = 1.0 / 12.0;
}),
..Default::default()
},
TestHealth1Case {
// 25, reserved oo funds with max bid/min ask not crossing oracle, like 15 with obv2
token1: -100,
token2: -10,
token3: 0,
oov2_1_2: (1, 1),
oov2_1_3: (11, 1),
expected_health:
// tokens
-100.0 * 1.2 - 10.0 * 5.0 * 1.5
// oo_1_2 (-> token1)
+ (1.0 + 5.0) * 1.2
// oo_1_3 (-> token3)
+ (11.0 / 10.0 + 1.0) * 10.0 * 0.5,
extra: Some(|account: &mut MangoAccountValue| {
let s2 = account.openbook_v2_orders_mut(2).unwrap();
s2.lowest_placed_ask = 6.0;
let s3 = account.openbook_v2_orders_mut(3).unwrap();
s3.highest_placed_bid_inv = 1.0 / 9.0;
}),
..Default::default()
},
TestHealth1Case {
// 26, base case for 27, like 16 with obv2
token1: 100,
token2: 100,
token3: 100,
oov2_1_2: (0, 100),
oov2_1_3: (0, 100),
expected_health:
// tokens
100.0 * 0.8 + 100.0 * 5.0 * 0.5 + 100.0 * 10.0 * 0.5
// oo_1_2 (-> token2)
+ 100.0 * 5.0 * 0.5
// oo_1_3 (-> token1)
+ 100.0 * 10.0 * 0.5,
..Default::default()
},
TestHealth1Case {
// 27, potential_openbook_tokens counts for deposit weight scaling, like 17 with obv2
token1: 100,
token2: 100,
token3: 100,
oov2_1_2: (0, 100),
oov2_1_3: (0, 100),
bank_settings: [
BankSettings {
..BankSettings::default()
},
BankSettings {
deposits: 100,
deposit_weight_scale_start_quote: 100 * 5,
potential_openbook_tokens: 100,
..BankSettings::default()
},
BankSettings {
deposits: 600,
deposit_weight_scale_start_quote: 500 * 10,
potential_openbook_tokens: 100,
..BankSettings::default()
},
],
expected_health:
// tokens
100.0 * 0.8 + 100.0 * 5.0 * 0.5 * (100.0 / 200.0) + 100.0 * 10.0 * 0.5 * (500.0 / 700.0)
// oo_1_2 (-> token2)
+ 100.0 * 5.0 * 0.5 * (100.0 / 200.0)
// oo_1_3 (-> token1)
+ 100.0 * 10.0 * 0.5 * (500.0 / 700.0),
..Default::default()
},
];
for (i, testcase) in testcases.iter().enumerate() {
println!("checking testcase {}", i);
test_health1_runner(testcase);
}
}
#[test]
fn test_health_with_skips() {
let testcase = TestHealth1Case {
// 6, reserved oo funds
token1: 100,
token2: 10,
token3: -10,
oo_1_2: (5, 1),
oo_1_3: (0, 0),
..Default::default()
};
let buffer = MangoAccount::default_for_tests().try_to_vec().unwrap();
let mut account = MangoAccountValue::from_bytes(&buffer).unwrap();
let group = Pubkey::new_unique();
account.fixed.group = group;
let (mut bank1, mut oracle1) = mock_bank_and_oracle(group, 0, 1.0, 0.2, 0.1);
let (mut bank2, mut oracle2) = mock_bank_and_oracle(group, 4, 5.0, 0.5, 0.3);
let (mut bank3, mut oracle3) = mock_bank_and_oracle(group, 5, 10.0, 0.5, 0.3);
bank1
.data()
.change_without_fee(
account.ensure_token_position(0).unwrap().0,
I80F48::from(testcase.token1),
DUMMY_NOW_TS,
)
.unwrap();
bank2
.data()
.change_without_fee(
account.ensure_token_position(4).unwrap().0,
I80F48::from(testcase.token2),
DUMMY_NOW_TS,
)
.unwrap();
bank3
.data()
.change_without_fee(
account.ensure_token_position(5).unwrap().0,
I80F48::from(testcase.token3),
DUMMY_NOW_TS,
)
.unwrap();
let mut oo1 = TestAccount::<OpenOrders>::new_zeroed();
let serum3account1 = account.create_serum3_orders(2).unwrap();
serum3account1.open_orders = oo1.pubkey;
serum3account1.base_token_index = 4;
serum3account1.quote_token_index = 0;
oo1.data().native_pc_total = testcase.oo_1_2.0;
oo1.data().native_coin_total = testcase.oo_1_2.1;
fn compute_health_with_retriever<'a, 'info>(
ais: &[AccountInfo],
account: &MangoAccountValue,
group: Pubkey,
kind: bool,
) -> Result<I80F48> {
let hc = if kind {
let retriever =
ScanningAccountRetriever::new_with_staleness(&ais, &group, None).unwrap();
new_health_cache_skipping_missing_banks_and_bad_oracles(
&account.borrow(),
&retriever,
DUMMY_NOW_TS,
)?
} else {
let retriever = new_fixed_order_account_retriever_with_optional_banks(
&ais,
&account.borrow(),
0,
)
.unwrap();
new_health_cache_skipping_missing_banks_and_bad_oracles(
&account.borrow(),
&retriever,
DUMMY_NOW_TS,
)?
};
Ok(hc.health(HealthType::Init))
}
for retriever_kind in [false, true] {
// baseline with everything
{
let ais = vec![
bank1.as_account_info(),
bank2.as_account_info(),
bank3.as_account_info(),
oracle1.as_account_info(),
oracle2.as_account_info(),
oracle3.as_account_info(),
oo1.as_account_info(),
];
let health =
compute_health_with_retriever(&ais, &account, group, retriever_kind).unwrap();
assert!(health_eq(
health,
0.8 * 100.0 + 0.5 * 5.0 * (10.0 + 2.0) - 1.5 * 10.0 * 10.0
));
}
// missing bank1
{
let ais = vec![
bank2.as_account_info(),
bank3.as_account_info(),
oracle2.as_account_info(),
oracle3.as_account_info(),
oo1.as_account_info(),
];
let health =
compute_health_with_retriever(&ais, &account, group, retriever_kind).unwrap();
assert!(health_eq(health, 0.5 * 5.0 * 10.0 - 1.5 * 10.0 * 10.0));
}
// missing bank2
{
let ais = vec![
bank1.as_account_info(),
bank3.as_account_info(),
oracle1.as_account_info(),
oracle3.as_account_info(),
oo1.as_account_info(),
];
let health =
compute_health_with_retriever(&ais, &account, group, retriever_kind).unwrap();
assert!(health_eq(health, 0.8 * 100.0 - 1.5 * 10.0 * 10.0));
}
// missing bank1 and 2
{
let ais = vec![
bank3.as_account_info(),
oracle3.as_account_info(),
oo1.as_account_info(),
];
let health =
compute_health_with_retriever(&ais, &account, group, retriever_kind).unwrap();
assert!(health_eq(health, -1.5 * 10.0 * 10.0));
}
// missing bank3
{
let ais = vec![
bank1.as_account_info(),
bank2.as_account_info(),
oracle1.as_account_info(),
oracle2.as_account_info(),
oo1.as_account_info(),
];
// bank3 has a negative balance and can't be skipped!
assert!(
compute_health_with_retriever(&ais, &account, group, retriever_kind).is_err()
);
}
}
}
}