poolStateHelpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. const { ethers } = require("hardhat")
  2. const { expect } = require("chai")
  3. const { BigNumber } = require("ethers")
  4. const { CHAIN_ID_TO_NAME, POOL_ID_TO_NAME } = require("./constants")
  5. const util = require("util")
  6. printEndpoints = (endpoints) => {
  7. let printFriendly = JSON.parse(JSON.stringify(endpoints))
  8. for (const [endpointId, endpoint] of Object.entries(printFriendly)) {
  9. endpoint.factory = endpoint.factory.address
  10. endpoint.router = endpoint.router.address
  11. endpoint.bridge = endpoint.bridge.address
  12. endpoint.lzEndpoint = endpoint.lzEndpoint.address
  13. endpoint.feeLibrary = endpoint.feeLibrary.address
  14. endpoint.pools = Object.fromEntries(
  15. Object.entries(endpoint.pools).map(([poolId, value]) => {
  16. const chainPaths = {}
  17. for (const [chainId, _chainPaths] of Object.entries(value.chainPaths)) {
  18. chainPaths[CHAIN_ID_TO_NAME[chainId]] = Object.fromEntries(
  19. Object.entries(_chainPaths).map(([x, y]) => [POOL_ID_TO_NAME[x], y])
  20. )
  21. }
  22. delete value.dstChainWeights
  23. return [poolId, { ...value, token: value.token.address, pool: value.pool.address, chainPaths }]
  24. })
  25. )
  26. delete Object.assign(printFriendly, { [CHAIN_ID_TO_NAME[endpointId]]: printFriendly[endpointId] })[endpointId]
  27. }
  28. console.log(util.inspect(printFriendly, { showHidden: false, depth: null, colors: true }))
  29. }
  30. stringifyBigNumbers = (resp) => {
  31. if (resp instanceof Array) {
  32. return resp.map((x) => stringifyBigNumbers(x))
  33. } else if (BigNumber.isBigNumber(resp)) {
  34. return resp.toString()
  35. } else if (resp instanceof Object) {
  36. return Object.fromEntries(Object.entries(resp).map(([k, v]) => [k, stringifyBigNumbers(v)]))
  37. } else {
  38. return resp
  39. }
  40. }
  41. getPoolState = async (poolObj) => {
  42. return {
  43. actualLiquidity: await poolObj.token.balanceOf(poolObj.pool.address),
  44. totalLiquidity: await poolObj.pool.totalLiquidity(),
  45. totalSupply: await poolObj.pool.totalSupply(),
  46. protocolFeeBalance: await poolObj.pool.protocolFeeBalance(),
  47. eqFeePool: await poolObj.pool.eqFeePool(),
  48. mintFeeBalance: await poolObj.pool.mintFeeBalance(),
  49. deltaCredit: await poolObj.pool.deltaCredit(),
  50. convertRate: await poolObj.pool.convertRate(),
  51. }
  52. }
  53. getPoolStates = async (endpoints, poolIds) => {
  54. let resp = []
  55. for (const chainId of Object.keys(endpoints)) {
  56. let chain = endpoints[chainId]
  57. for (const poolId of poolIds) {
  58. let poolObj = chain.pools[poolId]
  59. resp.push(await getPoolState(poolObj))
  60. }
  61. }
  62. return resp
  63. }
  64. getTokenState = async (endpoints, tokenId) => {
  65. let resp = {}
  66. for (const endpoint of Object.values(endpoints)) {
  67. for (const [k, v] of Object.entries(await getPoolState(endpoint.pools[tokenId]))) {
  68. resp[k] = (resp[k] || BigNumber.from(0)).add(v)
  69. }
  70. }
  71. return resp
  72. }
  73. getPooledTokenState = async (endpoints, tokenIds) => {
  74. const resp = {}
  75. for (const tokenId of tokenIds) {
  76. for (const [k, v] of Object.entries(await getTokenState(endpoints, tokenId))) {
  77. resp[k] = (resp[k] || BigNumber.from(0)).add(v)
  78. }
  79. }
  80. return resp
  81. }
  82. // only pass token ids that are sharing pools of liquidity
  83. // for individual tokens, just pass a list of 1
  84. checkTokenState = async (endpoints, tokenIds) => {
  85. const tokenState = await getPooledTokenState(endpoints, tokenIds)
  86. const { actualLiquidity, totalLiquidity, protocolFeeBalance, eqFeePool, mintFeeBalance, deltaCredit } = tokenState
  87. const inferredLiquidity = totalLiquidity.add(protocolFeeBalance).add(eqFeePool).add(mintFeeBalance).add(deltaCredit)
  88. const diff = actualLiquidity.sub(inferredLiquidity)
  89. if (diff > 0) throw `Mismatched liquidity/fee balances -> ${diff}`
  90. return tokenState
  91. }
  92. getTokenBalances = async (listOfTokens, user) => {
  93. const resp = []
  94. for (const u of Array.isArray(user) ? user : [user]) {
  95. for (const [tokenName, token] of Object.entries(listOfTokens)) {
  96. const balance = await token.balanceOf(u.address)
  97. resp.push({ name: tokenName, balance })
  98. }
  99. }
  100. return resp
  101. }
  102. getTokenBalancesFromPools = async (listOfPoolObj, user) => {
  103. const listOfLpPools = Object.fromEntries(listOfPoolObj.map((poolObj) => [poolObj.name, poolObj.token]))
  104. return await getTokenBalances(listOfLpPools, user)
  105. }
  106. getLpBalancesFromPools = async (listOfPoolObj, user) => {
  107. const listOfTokens = Object.fromEntries(listOfPoolObj.map((poolObj) => [poolObj.name, poolObj.pool]))
  108. return await getTokenBalances(listOfTokens, user)
  109. }
  110. getChainPath = async (srcPoolObj, dstPoolObj) => {
  111. const cpIndex = await srcPoolObj.pool.chainPathIndexLookup(dstPoolObj.chainId, dstPoolObj.id)
  112. const deltaCredit = await srcPoolObj.pool.deltaCredit()
  113. let { dstChainId, dstPoolId, weight, balance, credits, lkb, idealBalance } = await srcPoolObj.pool.chainPaths(cpIndex)
  114. return { dstChainId, dstPoolId, weight, balance, credits, lkb, deltaCredit, idealBalance }
  115. }
  116. getChainPaths = async (srcPoolObj, dstPoolObj) => {
  117. return {
  118. srcChainPath: await getChainPath(srcPoolObj, dstPoolObj),
  119. dstChainPath: await getChainPath(dstPoolObj, srcPoolObj),
  120. }
  121. }
  122. getAllChainPaths = async (LisOfPoolObj) => {
  123. const resp = {}
  124. for (let a = 0; a < LisOfPoolObj.length; a++) {
  125. for (let b = 0; b < LisOfPoolObj.length; b++) {
  126. const srcPoolObj = LisOfPoolObj[a]
  127. const dstPoolObj = LisOfPoolObj[b]
  128. if (srcPoolObj.chainId === dstPoolObj.chainId) continue
  129. const chainPathName = `${srcPoolObj.name}->${dstPoolObj.name}`
  130. resp[chainPathName] = await getChainPath(srcPoolObj, dstPoolObj)
  131. }
  132. }
  133. return resp
  134. }
  135. printPoolStates = async (poolObjs) => {
  136. console.log("\nPool States: ")
  137. let totals = {}
  138. for (const poolObj of poolObjs) {
  139. const poolState = stringifyBigNumbers(await getPoolState(poolObj))
  140. for (const [k, v] of Object.entries(poolState)) {
  141. totals[k] = (totals[k] || BigNumber.from(0)).add(v)
  142. }
  143. console.log(
  144. `${poolObj.name} -> `,
  145. `actualLiquidity: ${poolState.actualLiquidity} `,
  146. `totalLiquidity: ${poolState.totalLiquidity} `,
  147. `totalSupply: ${poolState.totalSupply} `,
  148. `protocolFeeBalance: ${poolState.protocolFeeBalance} `,
  149. `eqFeePool: ${poolState.eqFeePool} `,
  150. `mintFeeBalance: ${poolState.mintFeeBalance} `,
  151. `deltaCredit: ${poolState.deltaCredit} `,
  152. `convertRate: ${poolState.convertRate}`
  153. )
  154. }
  155. console.log(
  156. ` TOTALS: `,
  157. `TotalActualLiquidity: ${totals.actualLiquidity} `,
  158. `TotalTotalLiquidity: ${totals.totalLiquidity} `,
  159. `TotalTotalSupply: ${totals.totalSupply} `,
  160. `TotalProtocolFeeBalance: ${totals.protocolFeeBalance} `,
  161. `TotalEqFeePool: ${totals.eqFeePool} `,
  162. `TotalMintFeeBalance: ${totals.mintFeeBalance} `,
  163. `TotalDeltaCredit: ${totals.deltaCredit} `
  164. )
  165. }
  166. printTokenStates = async (endpoints, tokenIds) => {
  167. console.log("\nToken States: ")
  168. for (const tokenId of tokenIds) {
  169. const tokenState = stringifyBigNumbers(await getTokenState(endpoints, tokenId))
  170. console.log(
  171. `actualLiquidity: ${tokenState.actualLiquidity} `,
  172. `totalLiquidity: ${tokenState.totalLiquidity} `,
  173. `totalSupply: ${tokenState.totalSupply} `,
  174. `deltaCredit: ${tokenState.deltaCredit} `
  175. )
  176. }
  177. }
  178. printPooledTokenStates = async (endpoints, tokenIds) => {
  179. console.log("\nPooled Token States:")
  180. const tokenState = stringifyBigNumbers(await getPooledTokenState(endpoints, tokenIds))
  181. console.log(
  182. `actualLiquidity: ${tokenState.actualLiquidity} `,
  183. `totalLiquidity: ${tokenState.totalLiquidity} `,
  184. `totalSupply: ${tokenState.totalSupply} `,
  185. `deltaCredit: ${tokenState.deltaCredit} `
  186. )
  187. }
  188. printChainPaths = async (listOfPoolObj) => {
  189. console.log("\nChain Paths: ")
  190. let totals = {}
  191. let a = await getAllChainPaths(listOfPoolObj)
  192. const chainPaths = stringifyBigNumbers(a)
  193. for (const [name, chainPath] of Object.entries(chainPaths)) {
  194. for (const [k, v] of Object.entries(chainPath)) {
  195. totals[k] = (totals[k] || BigNumber.from(0)).add(v)
  196. }
  197. console.log(
  198. `${name}: `,
  199. `balance: ${chainPath.balance} `,
  200. `credits: ${chainPath.credits} `,
  201. `lkb: ${chainPath.lkb} `,
  202. `weight: ${chainPath.weight}`,
  203. `ideal balance: ${chainPath.idealBalance}`
  204. )
  205. }
  206. console.log(
  207. ` TOTALS: `,
  208. `balance: ${totals.balance} `,
  209. `credits: ${totals.credits} `,
  210. `lkb: ${totals.lkb} `,
  211. `weight: ${totals.weight}`
  212. )
  213. }
  214. printLpBalancesFromPool = async (listOfPoolObj, users) => {
  215. console.log("\nLp Balances:")
  216. for (const user of users) {
  217. let a = await getLpBalancesFromPools(listOfPoolObj, user)
  218. const lpBalances = stringifyBigNumbers(a)
  219. for (const lpBalance of lpBalances) {
  220. console.log(`${user.name}: lp-${lpBalance.name} -> ${lpBalance.balance}`)
  221. }
  222. }
  223. }
  224. printTokenBalancesFromPool = async (listOfPoolObj, users) => {
  225. console.log("\nToken Balances: ")
  226. for (const user of users) {
  227. let a = await getTokenBalancesFromPools(listOfPoolObj, user)
  228. const tokenBalances = stringifyBigNumbers(a)
  229. for (const tokenBalance of tokenBalances) {
  230. console.log(`${user.name}: ${tokenBalance.name} -> ${tokenBalance.balance}`)
  231. }
  232. }
  233. }
  234. audit = async (endpoints, poolObjs) => {
  235. /*
  236. compute global metrics across all chains
  237. - globalBookedLiquidity = (pool.totalLiquidity) sum by chains
  238. - globalPromisedLiquidity = (unallocated liquidity (deltaCredits)
  239. + allocated liquidity (lkb + credits)) sum by chains
  240. */
  241. let globalBookedLiquidity = ethers.BigNumber.from(0)
  242. let globalPromisedLiquidity = ethers.BigNumber.from(0)
  243. // for each chain
  244. for (const endpoint of endpoints) {
  245. let { chainId: srcChainId } = endpoint
  246. // filter for pools that are on this endpoint
  247. const srcPoolObjs = poolObjs.filter((pool) => pool.chainId == srcChainId)
  248. for (const srcPoolObj of srcPoolObjs) {
  249. //loop over chain paths of pool
  250. const { pool: srcPool, token, chainPaths, id: srcPoolId } = srcPoolObj
  251. let totalQueryBalance = (await token.balanceOf(srcPool.address))
  252. .div(await srcPool.convertRate())
  253. .sub(await srcPool.eqFeePool())
  254. .sub(await srcPool.protocolFeeBalance())
  255. .sub(await srcPool.mintFeeBalance())
  256. let totalPromisedBalance = await srcPool.deltaCredit()
  257. globalBookedLiquidity = globalBookedLiquidity.add(await srcPool.totalLiquidity())
  258. // for each iterate by destination chain
  259. for (const [dstChainId, dstPools] of Object.entries(chainPaths)) {
  260. for (const dstPoolId of Object.keys(dstPools)) {
  261. const srcCP = await srcPool.chainPaths(await srcPool.chainPathIndexLookup(dstChainId, dstPoolId))
  262. const dstPoolObjs = poolObjs.filter((pool) => pool.chainId == dstChainId && pool.id == dstPoolId)
  263. for (const dstPoolObj of dstPoolObjs) {
  264. const dstCP = await dstPoolObj.pool.chainPaths(await dstPoolObj.pool.chainPathIndexLookup(srcChainId, srcPoolId))
  265. // if no msg inFlight, dstCp.lkb === srcCp.balance
  266. const transactionInbound = srcCP.lkb.sub(dstCP.balance)
  267. const promisedBalance = dstCP.balance.add(srcCP.credits)
  268. totalPromisedBalance = totalPromisedBalance.add(transactionInbound).add(promisedBalance)
  269. }
  270. }
  271. }
  272. if (totalPromisedBalance.toString() !== totalQueryBalance.toString()) {
  273. console.log("\n\n", "totalPromise: ", totalPromisedBalance.toString(), "totalQueryBalance: ", totalQueryBalance.toString())
  274. }
  275. /*
  276. ASSERT - IFG constraints for Pool to all its associated chainPaths
  277. */
  278. expect(totalPromisedBalance).to.equal(totalQueryBalance)
  279. globalPromisedLiquidity = globalPromisedLiquidity.add(totalPromisedBalance)
  280. }
  281. }
  282. // this can only be asserted globally, as any transaction would temporarily make the pool imbalanced
  283. expect(globalPromisedLiquidity).to.equal(globalBookedLiquidity)
  284. }
  285. module.exports = {
  286. getPoolState,
  287. getPoolStates,
  288. printEndpoints,
  289. getTokenBalancesFromPools,
  290. getLpBalancesFromPools,
  291. getChainPath,
  292. getChainPaths,
  293. getAllChainPaths,
  294. stringifyBigNumbers,
  295. printPoolStates,
  296. printPooledTokenStates,
  297. printTokenStates,
  298. getTokenState,
  299. printChainPaths,
  300. printLpBalancesFromPool,
  301. printTokenBalancesFromPool,
  302. audit,
  303. }