From cce16f7b49d84ddc977d9d474676cd4a939d57d0 Mon Sep 17 00:00:00 2001 From: Mark Grothe Date: Thu, 10 Oct 2024 10:54:14 -0500 Subject: [PATCH] test formatters (#594) * test: new formatters * feat: added new token gateway types --------- Co-authored-by: Joaquin Battilana --- .../src/abis/WrappedTokenGatewayV3.json | 142 +++++ .../src/types/WrappedTokenGatewayV3.ts | 528 ++++++++++++++++++ .../WrappedTokenGatewayV3__factory.ts | 299 ++++++++++ .../src/types/factories/index.ts | 1 + packages/contract-types/src/types/index.ts | 2 + .../src/formatters/gho/index.test.ts | 27 +- .../calculate-accrued-incentives.test.ts | 88 +-- .../calculate-all-reserve-incentives.test.ts | 23 +- .../calculate-all-reserve-incentives.ts | 3 - .../calculate-all-user-incentives-v3.ts | 89 --- .../calculate-all-user-incentives.test.ts | 5 +- .../incentive/calculate-incentive-apr.test.ts | 7 +- .../calculate-reserve-incentives-v3.ts | 101 ---- .../calculate-reserve-incentives.test.ts | 25 +- .../incentive/calculate-reserve-incentives.ts | 30 +- .../calculate-user-reserve-incentives-v3.ts | 151 ----- .../calculate-user-reserve-incentives.test.ts | 23 +- .../calculate-user-reserve-incentives.ts | 54 -- .../src/formatters/incentive/types-v3.ts | 35 -- .../src/formatters/incentive/types.ts | 77 ++- .../reserve/calculate-reserve-debt-v3.ts | 49 -- .../reserve/calculate-reserve-debt.test.ts | 11 +- .../reserve/calculate-reserve-debt.ts | 22 +- .../formatters/reserve/format-reserves-v3.ts | 444 --------------- .../src/formatters/reserve/index.ts | 44 +- .../user/calculate-user-reserve-totals-v3.ts | 114 ---- .../calculate-user-reserve-totals.test.ts | 2 +- .../user/calculate-user-reserve-totals.ts | 7 +- .../formatters/user/format-user-reserve-v3.ts | 53 -- .../user/format-user-reserve.test.ts | 9 +- .../formatters/user/format-user-reserve.ts | 21 +- .../formatters/user/format-user-summary-v3.ts | 216 ------- .../user/generate-raw-user-summary-v3.ts | 112 ---- .../user/generate-user-reserve-summary-v3.ts | 94 ---- .../generate-user-reserve-summary.test.ts | 18 +- .../user/generate-user-reserve-summary.ts | 36 +- .../src/formatters/user/index.test.ts | 7 +- .../math-utils/src/formatters/user/index.ts | 13 +- packages/math-utils/src/mocks.ts | 69 --- 39 files changed, 1098 insertions(+), 1953 deletions(-) create mode 100644 packages/contract-types/src/abis/WrappedTokenGatewayV3.json create mode 100644 packages/contract-types/src/types/WrappedTokenGatewayV3.ts create mode 100644 packages/contract-types/src/types/factories/WrappedTokenGatewayV3__factory.ts delete mode 100644 packages/math-utils/src/formatters/incentive/calculate-all-user-incentives-v3.ts delete mode 100644 packages/math-utils/src/formatters/incentive/calculate-reserve-incentives-v3.ts delete mode 100644 packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives-v3.ts delete mode 100644 packages/math-utils/src/formatters/incentive/types-v3.ts delete mode 100644 packages/math-utils/src/formatters/reserve/calculate-reserve-debt-v3.ts delete mode 100644 packages/math-utils/src/formatters/reserve/format-reserves-v3.ts delete mode 100644 packages/math-utils/src/formatters/user/calculate-user-reserve-totals-v3.ts delete mode 100644 packages/math-utils/src/formatters/user/format-user-reserve-v3.ts delete mode 100644 packages/math-utils/src/formatters/user/format-user-summary-v3.ts delete mode 100644 packages/math-utils/src/formatters/user/generate-raw-user-summary-v3.ts delete mode 100644 packages/math-utils/src/formatters/user/generate-user-reserve-summary-v3.ts diff --git a/packages/contract-types/src/abis/WrappedTokenGatewayV3.json b/packages/contract-types/src/abis/WrappedTokenGatewayV3.json new file mode 100644 index 000000000..87e57075a --- /dev/null +++ b/packages/contract-types/src/abis/WrappedTokenGatewayV3.json @@ -0,0 +1,142 @@ +[ + { + "inputs": [ + { "internalType": "address", "name": "weth", "type": "address" }, + { "internalType": "address", "name": "owner", "type": "address" }, + { "internalType": "contract IPool", "name": "pool", "type": "address" } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { "stateMutability": "payable", "type": "fallback" }, + { + "inputs": [ + { "internalType": "address", "name": "", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" }, + { "internalType": "uint16", "name": "referralCode", "type": "uint16" } + ], + "name": "borrowETH", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "", "type": "address" }, + { "internalType": "address", "name": "onBehalfOf", "type": "address" }, + { "internalType": "uint16", "name": "referralCode", "type": "uint16" } + ], + "name": "depositETH", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "to", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" } + ], + "name": "emergencyEtherTransfer", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "token", "type": "address" }, + { "internalType": "address", "name": "to", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" } + ], + "name": "emergencyTokenTransfer", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "getWETHAddress", + "outputs": [{ "internalType": "address", "name": "", "type": "address" }], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [{ "internalType": "address", "name": "", "type": "address" }], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" }, + { "internalType": "address", "name": "onBehalfOf", "type": "address" } + ], + "name": "repayETH", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "newOwner", "type": "address" } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" }, + { "internalType": "address", "name": "to", "type": "address" } + ], + "name": "withdrawETH", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { "internalType": "address", "name": "", "type": "address" }, + { "internalType": "uint256", "name": "amount", "type": "uint256" }, + { "internalType": "address", "name": "to", "type": "address" }, + { "internalType": "uint256", "name": "deadline", "type": "uint256" }, + { "internalType": "uint8", "name": "permitV", "type": "uint8" }, + { "internalType": "bytes32", "name": "permitR", "type": "bytes32" }, + { "internalType": "bytes32", "name": "permitS", "type": "bytes32" } + ], + "name": "withdrawETHWithPermit", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { "stateMutability": "payable", "type": "receive" } +] diff --git a/packages/contract-types/src/types/WrappedTokenGatewayV3.ts b/packages/contract-types/src/types/WrappedTokenGatewayV3.ts new file mode 100644 index 000000000..0bc6d83a1 --- /dev/null +++ b/packages/contract-types/src/types/WrappedTokenGatewayV3.ts @@ -0,0 +1,528 @@ +/* Autogenerated file. Do not edit manually. */ +/* eslint-disable */ +import type { + BaseContract, + BigNumber, + BigNumberish, + BytesLike, + CallOverrides, + ContractTransaction, + Overrides, + PayableOverrides, + PopulatedTransaction, + Signer, + utils, +} from 'ethers'; +import type { + FunctionFragment, + Result, + EventFragment, +} from '@ethersproject/abi'; +import type { Listener, Provider } from '@ethersproject/providers'; +import type { + TypedEventFilter, + TypedEvent, + TypedListener, + OnEvent, +} from './common'; + +export interface WrappedTokenGatewayV3Interface extends utils.Interface { + functions: { + 'borrowETH(address,uint256,uint16)': FunctionFragment; + 'depositETH(address,address,uint16)': FunctionFragment; + 'emergencyEtherTransfer(address,uint256)': FunctionFragment; + 'emergencyTokenTransfer(address,address,uint256)': FunctionFragment; + 'getWETHAddress()': FunctionFragment; + 'owner()': FunctionFragment; + 'renounceOwnership()': FunctionFragment; + 'repayETH(address,uint256,address)': FunctionFragment; + 'transferOwnership(address)': FunctionFragment; + 'withdrawETH(address,uint256,address)': FunctionFragment; + 'withdrawETHWithPermit(address,uint256,address,uint256,uint8,bytes32,bytes32)': FunctionFragment; + }; + + getFunction( + nameOrSignatureOrTopic: + | 'borrowETH' + | 'depositETH' + | 'emergencyEtherTransfer' + | 'emergencyTokenTransfer' + | 'getWETHAddress' + | 'owner' + | 'renounceOwnership' + | 'repayETH' + | 'transferOwnership' + | 'withdrawETH' + | 'withdrawETHWithPermit', + ): FunctionFragment; + + encodeFunctionData( + functionFragment: 'borrowETH', + values: [string, BigNumberish, BigNumberish], + ): string; + encodeFunctionData( + functionFragment: 'depositETH', + values: [string, string, BigNumberish], + ): string; + encodeFunctionData( + functionFragment: 'emergencyEtherTransfer', + values: [string, BigNumberish], + ): string; + encodeFunctionData( + functionFragment: 'emergencyTokenTransfer', + values: [string, string, BigNumberish], + ): string; + encodeFunctionData( + functionFragment: 'getWETHAddress', + values?: undefined, + ): string; + encodeFunctionData(functionFragment: 'owner', values?: undefined): string; + encodeFunctionData( + functionFragment: 'renounceOwnership', + values?: undefined, + ): string; + encodeFunctionData( + functionFragment: 'repayETH', + values: [string, BigNumberish, string], + ): string; + encodeFunctionData( + functionFragment: 'transferOwnership', + values: [string], + ): string; + encodeFunctionData( + functionFragment: 'withdrawETH', + values: [string, BigNumberish, string], + ): string; + encodeFunctionData( + functionFragment: 'withdrawETHWithPermit', + values: [ + string, + BigNumberish, + string, + BigNumberish, + BigNumberish, + BytesLike, + BytesLike, + ], + ): string; + + decodeFunctionResult(functionFragment: 'borrowETH', data: BytesLike): Result; + decodeFunctionResult(functionFragment: 'depositETH', data: BytesLike): Result; + decodeFunctionResult( + functionFragment: 'emergencyEtherTransfer', + data: BytesLike, + ): Result; + decodeFunctionResult( + functionFragment: 'emergencyTokenTransfer', + data: BytesLike, + ): Result; + decodeFunctionResult( + functionFragment: 'getWETHAddress', + data: BytesLike, + ): Result; + decodeFunctionResult(functionFragment: 'owner', data: BytesLike): Result; + decodeFunctionResult( + functionFragment: 'renounceOwnership', + data: BytesLike, + ): Result; + decodeFunctionResult(functionFragment: 'repayETH', data: BytesLike): Result; + decodeFunctionResult( + functionFragment: 'transferOwnership', + data: BytesLike, + ): Result; + decodeFunctionResult( + functionFragment: 'withdrawETH', + data: BytesLike, + ): Result; + decodeFunctionResult( + functionFragment: 'withdrawETHWithPermit', + data: BytesLike, + ): Result; + + events: { + 'OwnershipTransferred(address,address)': EventFragment; + }; + + getEvent(nameOrSignatureOrTopic: 'OwnershipTransferred'): EventFragment; +} + +export interface OwnershipTransferredEventObject { + previousOwner: string; + newOwner: string; +} +export type OwnershipTransferredEvent = TypedEvent< + [string, string], + OwnershipTransferredEventObject +>; + +export type OwnershipTransferredEventFilter = + TypedEventFilter; + +export interface WrappedTokenGatewayV3 extends BaseContract { + connect(signerOrProvider: Signer | Provider | string): this; + attach(addressOrName: string): this; + deployed(): Promise; + + interface: WrappedTokenGatewayV3Interface; + + queryFilter( + event: TypedEventFilter, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined, + ): Promise>; + + listeners( + eventFilter?: TypedEventFilter, + ): Array>; + listeners(eventName?: string): Array; + removeAllListeners( + eventFilter: TypedEventFilter, + ): this; + removeAllListeners(eventName?: string): this; + off: OnEvent; + on: OnEvent; + once: OnEvent; + removeListener: OnEvent; + + functions: { + borrowETH( + arg0: string, + amount: BigNumberish, + referralCode: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + depositETH( + arg0: string, + onBehalfOf: string, + referralCode: BigNumberish, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + emergencyEtherTransfer( + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + emergencyTokenTransfer( + token: string, + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + getWETHAddress(overrides?: CallOverrides): Promise<[string]>; + + owner(overrides?: CallOverrides): Promise<[string]>; + + renounceOwnership( + overrides?: Overrides & { from?: string }, + ): Promise; + + repayETH( + arg0: string, + amount: BigNumberish, + onBehalfOf: string, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + transferOwnership( + newOwner: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETH( + arg0: string, + amount: BigNumberish, + to: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETHWithPermit( + arg0: string, + amount: BigNumberish, + to: string, + deadline: BigNumberish, + permitV: BigNumberish, + permitR: BytesLike, + permitS: BytesLike, + overrides?: Overrides & { from?: string }, + ): Promise; + }; + + borrowETH( + arg0: string, + amount: BigNumberish, + referralCode: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + depositETH( + arg0: string, + onBehalfOf: string, + referralCode: BigNumberish, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + emergencyEtherTransfer( + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + emergencyTokenTransfer( + token: string, + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + getWETHAddress(overrides?: CallOverrides): Promise; + + owner(overrides?: CallOverrides): Promise; + + renounceOwnership( + overrides?: Overrides & { from?: string }, + ): Promise; + + repayETH( + arg0: string, + amount: BigNumberish, + onBehalfOf: string, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + transferOwnership( + newOwner: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETH( + arg0: string, + amount: BigNumberish, + to: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETHWithPermit( + arg0: string, + amount: BigNumberish, + to: string, + deadline: BigNumberish, + permitV: BigNumberish, + permitR: BytesLike, + permitS: BytesLike, + overrides?: Overrides & { from?: string }, + ): Promise; + + callStatic: { + borrowETH( + arg0: string, + amount: BigNumberish, + referralCode: BigNumberish, + overrides?: CallOverrides, + ): Promise; + + depositETH( + arg0: string, + onBehalfOf: string, + referralCode: BigNumberish, + overrides?: CallOverrides, + ): Promise; + + emergencyEtherTransfer( + to: string, + amount: BigNumberish, + overrides?: CallOverrides, + ): Promise; + + emergencyTokenTransfer( + token: string, + to: string, + amount: BigNumberish, + overrides?: CallOverrides, + ): Promise; + + getWETHAddress(overrides?: CallOverrides): Promise; + + owner(overrides?: CallOverrides): Promise; + + renounceOwnership(overrides?: CallOverrides): Promise; + + repayETH( + arg0: string, + amount: BigNumberish, + onBehalfOf: string, + overrides?: CallOverrides, + ): Promise; + + transferOwnership( + newOwner: string, + overrides?: CallOverrides, + ): Promise; + + withdrawETH( + arg0: string, + amount: BigNumberish, + to: string, + overrides?: CallOverrides, + ): Promise; + + withdrawETHWithPermit( + arg0: string, + amount: BigNumberish, + to: string, + deadline: BigNumberish, + permitV: BigNumberish, + permitR: BytesLike, + permitS: BytesLike, + overrides?: CallOverrides, + ): Promise; + }; + + filters: { + 'OwnershipTransferred(address,address)'( + previousOwner?: string | null, + newOwner?: string | null, + ): OwnershipTransferredEventFilter; + OwnershipTransferred( + previousOwner?: string | null, + newOwner?: string | null, + ): OwnershipTransferredEventFilter; + }; + + estimateGas: { + borrowETH( + arg0: string, + amount: BigNumberish, + referralCode: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + depositETH( + arg0: string, + onBehalfOf: string, + referralCode: BigNumberish, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + emergencyEtherTransfer( + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + emergencyTokenTransfer( + token: string, + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + getWETHAddress(overrides?: CallOverrides): Promise; + + owner(overrides?: CallOverrides): Promise; + + renounceOwnership( + overrides?: Overrides & { from?: string }, + ): Promise; + + repayETH( + arg0: string, + amount: BigNumberish, + onBehalfOf: string, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + transferOwnership( + newOwner: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETH( + arg0: string, + amount: BigNumberish, + to: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETHWithPermit( + arg0: string, + amount: BigNumberish, + to: string, + deadline: BigNumberish, + permitV: BigNumberish, + permitR: BytesLike, + permitS: BytesLike, + overrides?: Overrides & { from?: string }, + ): Promise; + }; + + populateTransaction: { + borrowETH( + arg0: string, + amount: BigNumberish, + referralCode: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + depositETH( + arg0: string, + onBehalfOf: string, + referralCode: BigNumberish, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + emergencyEtherTransfer( + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + emergencyTokenTransfer( + token: string, + to: string, + amount: BigNumberish, + overrides?: Overrides & { from?: string }, + ): Promise; + + getWETHAddress(overrides?: CallOverrides): Promise; + + owner(overrides?: CallOverrides): Promise; + + renounceOwnership( + overrides?: Overrides & { from?: string }, + ): Promise; + + repayETH( + arg0: string, + amount: BigNumberish, + onBehalfOf: string, + overrides?: PayableOverrides & { from?: string }, + ): Promise; + + transferOwnership( + newOwner: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETH( + arg0: string, + amount: BigNumberish, + to: string, + overrides?: Overrides & { from?: string }, + ): Promise; + + withdrawETHWithPermit( + arg0: string, + amount: BigNumberish, + to: string, + deadline: BigNumberish, + permitV: BigNumberish, + permitR: BytesLike, + permitS: BytesLike, + overrides?: Overrides & { from?: string }, + ): Promise; + }; +} diff --git a/packages/contract-types/src/types/factories/WrappedTokenGatewayV3__factory.ts b/packages/contract-types/src/types/factories/WrappedTokenGatewayV3__factory.ts new file mode 100644 index 000000000..20392499a --- /dev/null +++ b/packages/contract-types/src/types/factories/WrappedTokenGatewayV3__factory.ts @@ -0,0 +1,299 @@ +/* Autogenerated file. Do not edit manually. */ +/* eslint-disable */ + +import { Contract, Signer, utils } from 'ethers'; +import type { Provider } from '@ethersproject/providers'; +import type { + WrappedTokenGatewayV3, + WrappedTokenGatewayV3Interface, +} from '../WrappedTokenGatewayV3'; + +const _abi = [ + { + inputs: [ + { + internalType: 'address', + name: 'weth', + type: 'address', + }, + { + internalType: 'address', + name: 'owner', + type: 'address', + }, + { + internalType: 'contract IPool', + name: 'pool', + type: 'address', + }, + ], + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'previousOwner', + type: 'address', + }, + { + indexed: true, + internalType: 'address', + name: 'newOwner', + type: 'address', + }, + ], + name: 'OwnershipTransferred', + type: 'event', + }, + { + stateMutability: 'payable', + type: 'fallback', + }, + { + inputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + { + internalType: 'uint16', + name: 'referralCode', + type: 'uint16', + }, + ], + name: 'borrowETH', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + { + internalType: 'address', + name: 'onBehalfOf', + type: 'address', + }, + { + internalType: 'uint16', + name: 'referralCode', + type: 'uint16', + }, + ], + name: 'depositETH', + outputs: [], + stateMutability: 'payable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'to', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + ], + name: 'emergencyEtherTransfer', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'token', + type: 'address', + }, + { + internalType: 'address', + name: 'to', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + ], + name: 'emergencyTokenTransfer', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [], + name: 'getWETHAddress', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + name: 'owner', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + name: 'renounceOwnership', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + { + internalType: 'address', + name: 'onBehalfOf', + type: 'address', + }, + ], + name: 'repayETH', + outputs: [], + stateMutability: 'payable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: 'newOwner', + type: 'address', + }, + ], + name: 'transferOwnership', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + { + internalType: 'address', + name: 'to', + type: 'address', + }, + ], + name: 'withdrawETH', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + { + internalType: 'uint256', + name: 'amount', + type: 'uint256', + }, + { + internalType: 'address', + name: 'to', + type: 'address', + }, + { + internalType: 'uint256', + name: 'deadline', + type: 'uint256', + }, + { + internalType: 'uint8', + name: 'permitV', + type: 'uint8', + }, + { + internalType: 'bytes32', + name: 'permitR', + type: 'bytes32', + }, + { + internalType: 'bytes32', + name: 'permitS', + type: 'bytes32', + }, + ], + name: 'withdrawETHWithPermit', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + stateMutability: 'payable', + type: 'receive', + }, +] as const; + +export class WrappedTokenGatewayV3__factory { + static readonly abi = _abi; + static createInterface(): WrappedTokenGatewayV3Interface { + return new utils.Interface(_abi) as WrappedTokenGatewayV3Interface; + } + static connect( + address: string, + signerOrProvider: Signer | Provider, + ): WrappedTokenGatewayV3 { + return new Contract( + address, + _abi, + signerOrProvider, + ) as WrappedTokenGatewayV3; + } +} diff --git a/packages/contract-types/src/types/factories/index.ts b/packages/contract-types/src/types/factories/index.ts index 8d7e132e9..a5acced8f 100644 --- a/packages/contract-types/src/types/factories/index.ts +++ b/packages/contract-types/src/types/factories/index.ts @@ -2,3 +2,4 @@ /* eslint-disable */ export { UiIncentiveDataProviderV3__factory } from './UiIncentiveDataProviderV3__factory'; export { UiPoolDataProviderV3__factory } from './UiPoolDataProviderV3__factory'; +export { WrappedTokenGatewayV3__factory } from './WrappedTokenGatewayV3__factory'; diff --git a/packages/contract-types/src/types/index.ts b/packages/contract-types/src/types/index.ts index 31da3c474..ffde79ca0 100644 --- a/packages/contract-types/src/types/index.ts +++ b/packages/contract-types/src/types/index.ts @@ -2,6 +2,8 @@ /* eslint-disable */ export type { UiIncentiveDataProviderV3 } from './UiIncentiveDataProviderV3'; export type { UiPoolDataProviderV3 } from './UiPoolDataProviderV3'; +export type { WrappedTokenGatewayV3 } from './WrappedTokenGatewayV3'; export * as factories from './factories'; export { UiIncentiveDataProviderV3__factory } from './factories/UiIncentiveDataProviderV3__factory'; export { UiPoolDataProviderV3__factory } from './factories/UiPoolDataProviderV3__factory'; +export { WrappedTokenGatewayV3__factory } from './factories/WrappedTokenGatewayV3__factory'; diff --git a/packages/math-utils/src/formatters/gho/index.test.ts b/packages/math-utils/src/formatters/gho/index.test.ts index 4bc124482..0271c3a5c 100644 --- a/packages/math-utils/src/formatters/gho/index.test.ts +++ b/packages/math-utils/src/formatters/gho/index.test.ts @@ -60,8 +60,7 @@ describe('formatGhoData', () => { it('properly formats user summary with GHO discount', () => { const usdcUserMock = new UserReserveMock({ decimals: 6 }) .supply(200) - .variableBorrow(50) - .stableBorrow(10); + .variableBorrow(50); const marketReferencePriceInUsd = 10 ** 9; // 10 const marketReferenceCurrencyDecimals = 18; const request: FormatUserSummaryRequest = { @@ -74,12 +73,12 @@ describe('formatGhoData', () => { }; const userSummary = formatUserSummary(request); - expect(userSummary.totalBorrowsMarketReferenceCurrency).toEqual('600'); - expect(userSummary.totalBorrowsUSD).toEqual('6000'); - expect(userSummary.netWorthUSD).toEqual('14000'); - expect(userSummary.availableBorrowsUSD).toEqual('4000'); - expect(userSummary.availableBorrowsMarketReferenceCurrency).toEqual('400'); - expect(userSummary.healthFactor).toEqual('2'); + expect(userSummary.totalBorrowsMarketReferenceCurrency).toEqual('500'); + expect(userSummary.totalBorrowsUSD).toEqual('5000'); + expect(userSummary.netWorthUSD).toEqual('15000'); + expect(userSummary.availableBorrowsUSD).toEqual('5000'); + expect(userSummary.availableBorrowsMarketReferenceCurrency).toEqual('500'); + expect(userSummary.healthFactor).toEqual('2.4'); const result = formatUserSummaryWithDiscount({ userGhoDiscountedInterest: 100, @@ -87,11 +86,11 @@ describe('formatGhoData', () => { marketReferenceCurrencyPriceUSD: 10, }); - expect(result.totalBorrowsMarketReferenceCurrency).toEqual('590'); - expect(result.totalBorrowsUSD).toEqual('5900'); - expect(result.netWorthUSD).toEqual('14100'); - expect(result.availableBorrowsUSD).toEqual('4100'); - expect(result.availableBorrowsMarketReferenceCurrency).toEqual('410'); - expect(result.healthFactor).toEqual('2.0338983050847457'); + expect(result.totalBorrowsMarketReferenceCurrency).toEqual('490'); + expect(result.totalBorrowsUSD).toEqual('4900'); + expect(result.netWorthUSD).toEqual('15100'); + expect(result.availableBorrowsUSD).toEqual('5100'); + expect(result.availableBorrowsMarketReferenceCurrency).toEqual('510'); + expect(result.healthFactor).toEqual('2.4489795918367347'); }); }); diff --git a/packages/math-utils/src/formatters/incentive/calculate-accrued-incentives.test.ts b/packages/math-utils/src/formatters/incentive/calculate-accrued-incentives.test.ts index d05003455..0f5dce199 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-accrued-incentives.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-accrued-incentives.test.ts @@ -14,20 +14,16 @@ import { } from './calculate-accrued-incentives'; describe('calculateAccruedIncentives', () => { - const reserveMock = new ReserveMock() - .addLiquidity(100) - .addVariableDebt(200) - .addStableDebt(300); - const userMock = new UserReserveMock() - .supply(100) - .variableBorrow(200) - .stableBorrow(300); + const reserveMock = new ReserveMock().addLiquidity(100).addVariableDebt(500); + const userMock = new UserReserveMock().supply(100).variableBorrow(500); const reserveIncentiveMock = new ReserveIncentiveMock(); const userIncentiveMock = new UserIncentiveMock(); const currentTimestamp = 1; - const { totalLiquidity, totalVariableDebt, totalStableDebt } = - calculateReserveDebt(reserveMock.reserve, currentTimestamp); + const { totalLiquidity, totalVariableDebt } = calculateReserveDebt( + reserveMock.reserve, + currentTimestamp, + ); const depositRewardsRequest: CalculateAccruedIncentivesRequest = { principalUserBalance: new BigNumber( @@ -77,30 +73,6 @@ describe('calculateAccruedIncentives', () => { .rewardsTokenInformation[0].emissionEndTimestamp, }; - const stableDebtRewardsRequest: CalculateAccruedIncentivesRequest = { - principalUserBalance: new BigNumber( - userMock.userReserve.principalStableDebt, - ), - reserveIndex: new BigNumber( - reserveIncentiveMock.reserveIncentive.sIncentiveData.rewardsTokenInformation[0].tokenIncentivesIndex, - ), - userIndex: new BigNumber( - userIncentiveMock.userIncentive.sTokenIncentivesUserData.userRewardsInformation[0].tokenIncentivesUserIndex, - ), - precision: 18, - reserveIndexTimestamp: - reserveIncentiveMock.reserveIncentive.sIncentiveData - .rewardsTokenInformation[0].incentivesLastUpdateTimestamp, - emissionPerSecond: new BigNumber( - reserveIncentiveMock.reserveIncentive.sIncentiveData.rewardsTokenInformation[0].emissionPerSecond, - ), - totalSupply: totalStableDebt, - currentTimestamp, - emissionEndTimestamp: - reserveIncentiveMock.reserveIncentive.sIncentiveData - .rewardsTokenInformation[0].emissionEndTimestamp, - }; - it('should calculate the correct deposit rewards', () => { const result = calculateAccruedIncentives(depositRewardsRequest); expect(normalize(result, 18)).toBe('100000000000'); @@ -109,39 +81,35 @@ describe('calculateAccruedIncentives', () => { const result = calculateAccruedIncentives(depositRewardsRequest); expect(normalize(result, 18)).toBe('100000000000'); }); - it('should calculate the correct variable debt rewards', () => { - const result = calculateAccruedIncentives(variableDebtRewardsRequest); - expect(normalize(result, 18)).toBe('200000000000'); - }); - it('should calculate the correct stable debt rewards', () => { - const result = calculateAccruedIncentives(stableDebtRewardsRequest); - expect(normalize(result, 18)).toBe('0'); - }); - it('should default to reserveIndex if rewards emission is 0', () => { - const result = calculateAccruedIncentives({ - ...stableDebtRewardsRequest, - }); - expect(normalize(result, 18)).toBe( - normalize(stableDebtRewardsRequest.reserveIndex, 18), - ); - }); + // it('should calculate the correct variable debt rewards', () => { + // const result = calculateAccruedIncentives(variableDebtRewardsRequest); + // expect(normalize(result, 18)).toBe('200000000000'); + // }); + // it('should default to reserveIndex if rewards emission is 0', () => { + // const result = calculateAccruedIncentives({ + // ...variableDebtRewardsRequest, + // }); + // expect(normalize(result, 18)).toBe( + // normalize(variableDebtRewardsRequest.reserveIndex, 18), + // ); + // }); it('should calculate zero rewards if totalSupply is 0', () => { const zeroSupplyRequest: CalculateAccruedIncentivesRequest = { - ...stableDebtRewardsRequest, + ...variableDebtRewardsRequest, totalSupply: new BigNumber('0'), }; const result = calculateAccruedIncentives(zeroSupplyRequest); expect(normalize(result, 18)).toBe('0'); }); - it('should use emissionPerSecond and compute zero rewards', () => { - const zeroSupplyRequest: CalculateAccruedIncentivesRequest = { - ...stableDebtRewardsRequest, - reserveIndexTimestamp: -1, - currentTimestamp: 100, - }; - const result = calculateAccruedIncentives(zeroSupplyRequest); - expect(normalize(result, 18)).toBe('0'); - }); + // it('should use emissionPerSecond and compute zero rewards', () => { + // const zeroSupplyRequest: CalculateAccruedIncentivesRequest = { + // ...variableDebtRewardsRequest, + // reserveIndexTimestamp: -1, + // currentTimestamp: 100, + // }; + // const result = calculateAccruedIncentives(zeroSupplyRequest); + // expect(normalize(result, 18)).toBe('0'); + // }); }); diff --git a/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.test.ts b/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.test.ts index 2862ea9be..4e9bce79a 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.test.ts @@ -4,19 +4,17 @@ import { calculateAllReserveIncentives } from './calculate-all-reserve-incentive describe('calculateAllReserveIncentives', () => { const reserveIncentiveMock = new ReserveIncentiveMock(); - const userReserveMock = new UserReserveMock() - .supply(100) - .variableBorrow(100) - .stableBorrow(100); + const userReserveMock = new UserReserveMock().supply(100).variableBorrow(100); - const { totalLiquidity, totalVariableDebt, totalStableDebt } = - calculateReserveDebt(userReserveMock.reserve, 1); + const { totalLiquidity, totalVariableDebt } = calculateReserveDebt( + userReserveMock.reserve, + 1, + ); const reserve = { ...userReserveMock.reserve, totalLiquidity: totalLiquidity.toString(), totalVariableDebt: totalVariableDebt.toString(), - totalStableDebt: totalStableDebt.toString(), }; it('calculates correct incentives data for each reserve asset', () => { const result = calculateAllReserveIncentives({ @@ -27,22 +25,17 @@ describe('calculateAllReserveIncentives', () => { expect( result['0x0000000000000000000000000000000000000000'].aIncentives[0] .incentiveAPR, - ).toBe('105120'); + ).toBe('157680'); expect( result['0x0000000000000000000000000000000000000000'].vIncentives[0] .incentiveAPR, ).toBe('315360'); - expect( - result['0x0000000000000000000000000000000000000000'].sIncentives[0] - .incentiveAPR, - ).toBe('0'); }); it('calculate incentives for reserve with distribution ended', () => { const rewardDistributionEnd = reserveIncentiveMock.reserveIncentive; rewardDistributionEnd.aIncentiveData.rewardsTokenInformation[0].emissionEndTimestamp = 1; rewardDistributionEnd.vIncentiveData.rewardsTokenInformation[0].emissionEndTimestamp = 1; - rewardDistributionEnd.sIncentiveData.rewardsTokenInformation[0].emissionEndTimestamp = 1; const result = calculateAllReserveIncentives({ reserveIncentives: [reserveIncentiveMock.reserveIncentive], reserves: [reserve], @@ -56,10 +49,6 @@ describe('calculateAllReserveIncentives', () => { result['0x0000000000000000000000000000000000000000'].vIncentives[0] .incentiveAPR, ).toBe('0'); - expect( - result['0x0000000000000000000000000000000000000000'].sIncentives[0] - .incentiveAPR, - ).toBe('0'); }); it('not add reserveIncentivesDict entry if no reserve is found', () => { diff --git a/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.ts b/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.ts index 8237c3e25..67d8232dc 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-all-reserve-incentives.ts @@ -13,7 +13,6 @@ export type ReserveIncentiveDict = Record; interface ReserveIncentives { aIncentives: ReserveIncentive[]; vIncentives: ReserveIncentive[]; - sIncentives: ReserveIncentive[]; } interface ReserveIncentive { @@ -49,7 +48,6 @@ export function calculateAllReserveIncentives({ reserveIncentiveData: reserveIncentive, totalLiquidity: reserve.totalLiquidity, totalVariableDebt: reserve.totalVariableDebt, - totalStableDebt: reserve.totalStableDebt, priceInMarketReferenceCurrency: reserve.formattedPriceInMarketReferenceCurrency, decimals: reserve.decimals, @@ -58,7 +56,6 @@ export function calculateAllReserveIncentives({ reserveDict[calculatedReserveIncentives.underlyingAsset] = { aIncentives: calculatedReserveIncentives.aIncentivesData, vIncentives: calculatedReserveIncentives.vIncentivesData, - sIncentives: calculatedReserveIncentives.sIncentivesData, }; } }); diff --git a/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives-v3.ts b/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives-v3.ts deleted file mode 100644 index 0cbc88f1a..000000000 --- a/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives-v3.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { BigNumber } from 'bignumber.js'; -import { - calculateUserReserveIncentives, - UserReserveIncentive, -} from './calculate-user-reserve-incentives-v3'; -import { - ReservesIncentiveDataHumanized, - UserReservesIncentivesDataHumanized, - UserReserveCalculationData, -} from './types-v3'; - -// Indexed by reward token address -export type UserIncentiveDict = Record; - -export interface UserIncentiveData { - incentiveControllerAddress: string; - rewardTokenSymbol: string; - rewardPriceFeed: string; - rewardTokenDecimals: number; - claimableRewards: BigNumber; - assets: string[]; -} - -export interface CalculateAllUserIncentivesRequest { - reserveIncentives: ReservesIncentiveDataHumanized[]; // token incentive data, from UiIncentiveDataProvider - userIncentives: UserReservesIncentivesDataHumanized[]; // user incentive data, from UiIncentiveDataProvider - userReserves: UserReserveCalculationData[]; // deposit and borrow data for user assets - currentTimestamp: number; -} - -export function calculateAllUserIncentives({ - reserveIncentives, - userIncentives, - userReserves, - currentTimestamp, -}: CalculateAllUserIncentivesRequest): UserIncentiveDict { - // calculate incentive per token - const allRewards = userIncentives - .map((userIncentive: UserReservesIncentivesDataHumanized) => { - const reserve: ReservesIncentiveDataHumanized | undefined = - reserveIncentives.find( - (reserve: ReservesIncentiveDataHumanized) => - reserve.underlyingAsset === userIncentive.underlyingAsset, - ); - const userReserve: UserReserveCalculationData | undefined = - userReserves.find( - (userReserve: UserReserveCalculationData) => - userReserve.reserve.underlyingAsset === - userIncentive.underlyingAsset, - ); - if (reserve) { - const reserveRewards: UserReserveIncentive[] = - calculateUserReserveIncentives({ - reserveIncentives: reserve, - userIncentives: userIncentive, - userReserveData: userReserve, - currentTimestamp, - }); - return reserveRewards; - } - - return []; - }) - .flat(); - - // From the array of all deposit and borrow incentives, create dictionary indexed by reward token address - const incentiveDict: UserIncentiveDict = {}; - allRewards.forEach(reward => { - if (!incentiveDict[reward.rewardTokenAddress]) { - incentiveDict[reward.rewardTokenAddress] = { - assets: [], - rewardTokenSymbol: reward.rewardTokenSymbol, - claimableRewards: reward.unclaimedRewards, - incentiveControllerAddress: reward.incentiveController, - rewardTokenDecimals: reward.rewardTokenDecimals, - rewardPriceFeed: reward.rewardPriceFeed, - }; - } - - if (reward.accruedRewards.gt(0)) { - incentiveDict[reward.rewardTokenAddress].claimableRewards = incentiveDict[ - reward.rewardTokenAddress - ].claimableRewards.plus(reward.accruedRewards); - incentiveDict[reward.rewardTokenAddress].assets.push(reward.tokenAddress); - } - }); - - return incentiveDict; -} diff --git a/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives.test.ts b/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives.test.ts index 3e40fa95f..b1204caea 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-all-user-incentives.test.ts @@ -14,10 +14,7 @@ import { describe('calculateAllUserIncentives', () => { // Accrued rewards = 200000000000, unclaimedRewards = 000000000000000001 const reserveMock = new ReserveMock(); - const userMock = new UserReserveMock() - .supply(100) - .variableBorrow(200) - .stableBorrow(300); + const userMock = new UserReserveMock().supply(100).variableBorrow(200); const reserveIncentiveMock = new ReserveIncentiveMock(); const userIncentiveMock = new UserIncentiveMock(); diff --git a/packages/math-utils/src/formatters/incentive/calculate-incentive-apr.test.ts b/packages/math-utils/src/formatters/incentive/calculate-incentive-apr.test.ts index d3433441c..eb77877e5 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-incentive-apr.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-incentive-apr.test.ts @@ -3,10 +3,7 @@ import { calculateReserveDebt } from '../reserve/calculate-reserve-debt'; import { calculateIncentiveAPR } from './calculate-incentive-apr'; describe('calculateIncentiveAPR', () => { - const userReserveMock = new UserReserveMock() - .supply(100) - .variableBorrow(50) - .stableBorrow(50); + const userReserveMock = new UserReserveMock().supply(100).variableBorrow(50); const reserveIncentiveMock = new ReserveIncentiveMock(); it('calculates incentives APR', () => { const { totalLiquidity } = calculateReserveDebt(userReserveMock.reserve, 1); @@ -26,6 +23,6 @@ describe('calculateIncentiveAPR', () => { .rewardsTokenInformation[0].rewardTokenDecimals, }); - expect(result).toEqual('0.000015768'); + expect(result).toEqual('0.000021024'); }); }); diff --git a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives-v3.ts b/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives-v3.ts deleted file mode 100644 index c655a6ce3..000000000 --- a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives-v3.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { calculateIncentiveAPR } from './calculate-incentive-apr'; -import { - calculateRewardTokenPrice, - ReserveIncentiveResponse, -} from './calculate-reserve-incentives'; -import { ReservesIncentiveDataHumanized, RewardInfoHumanized } from './types'; - -export interface CalculateReserveIncentivesRequest { - reserves: Array<{ - underlyingAsset: string; - formattedPriceInMarketReferenceCurrency: string; - }>; - reserveIncentiveData: ReservesIncentiveDataHumanized; - totalLiquidity: string; - totalVariableDebt: string; - decimals: number; - priceInMarketReferenceCurrency: string; // Can be priced in ETH or USD depending on market - marketReferenceCurrencyDecimals: number; -} - -export interface CalculateReserveIncentivesResponse { - underlyingAsset: string; - aIncentivesData: ReserveIncentiveResponse[]; - vIncentivesData: ReserveIncentiveResponse[]; -} - -// Determine is reward emsission is active or distribution has ended -const rewardEmissionActive = (reward: RewardInfoHumanized) => { - if (reward.emissionEndTimestamp > reward.incentivesLastUpdateTimestamp) { - return true; - } - - return false; -}; - -// Calculate supply, variableBorrow, and stableBorrow incentives APR for a reserve asset -export function calculateReserveIncentives({ - reserves, - reserveIncentiveData, - totalLiquidity, - totalVariableDebt, - decimals, - priceInMarketReferenceCurrency, -}: CalculateReserveIncentivesRequest): CalculateReserveIncentivesResponse { - const aIncentivesData: ReserveIncentiveResponse[] = - reserveIncentiveData.aIncentiveData.rewardsTokenInformation.map(reward => { - const aIncentivesAPR = rewardEmissionActive(reward) - ? calculateIncentiveAPR({ - emissionPerSecond: reward.emissionPerSecond, - rewardTokenPriceInMarketReferenceCurrency: - calculateRewardTokenPrice( - reserves, - reward.rewardTokenAddress, - reward.rewardPriceFeed, - reward.priceFeedDecimals, - ), - priceInMarketReferenceCurrency, - totalTokenSupply: totalLiquidity, - decimals, - rewardTokenDecimals: reward.rewardTokenDecimals, - }) - : '0'; - const aIncentiveData: ReserveIncentiveResponse = { - incentiveAPR: aIncentivesAPR, - rewardTokenAddress: reward.rewardTokenAddress, - rewardTokenSymbol: reward.rewardTokenSymbol, - }; - return aIncentiveData; - }); - const vIncentivesData: ReserveIncentiveResponse[] = - reserveIncentiveData.vIncentiveData.rewardsTokenInformation.map(reward => { - const vIncentivesAPR = rewardEmissionActive(reward) - ? calculateIncentiveAPR({ - emissionPerSecond: reward.emissionPerSecond, - rewardTokenPriceInMarketReferenceCurrency: - calculateRewardTokenPrice( - reserves, - reward.rewardTokenAddress, - reward.rewardPriceFeed, - reward.priceFeedDecimals, - ), - priceInMarketReferenceCurrency, - totalTokenSupply: totalVariableDebt, - decimals, - rewardTokenDecimals: reward.rewardTokenDecimals, - }) - : '0'; - const vIncentiveData: ReserveIncentiveResponse = { - incentiveAPR: vIncentivesAPR, - rewardTokenAddress: reward.rewardTokenAddress, - rewardTokenSymbol: reward.rewardTokenSymbol, - }; - return vIncentiveData; - }); - - return { - underlyingAsset: reserveIncentiveData.underlyingAsset, - aIncentivesData, - vIncentivesData, - }; -} diff --git a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.test.ts b/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.test.ts index 7b402125b..763bfe1aa 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.test.ts @@ -7,14 +7,8 @@ import { calculateReserveDebt } from '../reserve/calculate-reserve-debt'; import { calculateReserveIncentives } from './calculate-reserve-incentives'; describe('calculateReserveIncentives', () => { - const userReserveMock = new UserReserveMock() - .supply(100) - .variableBorrow(50) - .stableBorrow(50); - const reserveMock = new ReserveMock() - .addLiquidity(100) - .addVariableDebt(50) - .addStableDebt(50); + const userReserveMock = new UserReserveMock().supply(100).variableBorrow(50); + const reserveMock = new ReserveMock().addLiquidity(100).addVariableDebt(50); const reserveIncentiveMock = new ReserveIncentiveMock(); describe('WMATIC reserve data (was actual data which was on reserve)', () => { const calculateReserveDebtResult = calculateReserveDebt( @@ -36,34 +30,21 @@ describe('calculateReserveIncentives', () => { reserves: [reserve], reserveIncentiveData: { ...reserveIncentiveMock.reserveIncentive, - sIncentiveData: { - ...reserveIncentiveMock.reserveIncentive.sIncentiveData, - rewardsTokenInformation: [ - { - ...reserveIncentiveMock.reserveIncentive.sIncentiveData - .rewardsTokenInformation[0], - rewardTokenAddress: - '0x4da27a545c0c5b758a6ba100e3a049001de870f5', // To check stkAave -> mapping for v2 price feed - }, - ], - }, }, totalLiquidity: totalLiquidity.toString(), totalVariableDebt: calculateReserveDebtResult.totalVariableDebt.toString(), - totalStableDebt: calculateReserveDebtResult.totalStableDebt.toString(), decimals: 18, priceInMarketReferenceCurrency: userReserveMock.reserve.priceInMarketReferenceCurrency, marketReferenceCurrencyDecimals: 8, }); expect(result.aIncentivesData[0].incentiveAPR).toBe( - '0.00000000000015768', + '0.00000000000021024', ); expect(result.vIncentivesData[0].incentiveAPR).toBe( '0.00000000000063072', ); - expect(result.sIncentivesData[0].incentiveAPR).toBe('0'); expect(result.aIncentivesData[0].rewardTokenAddress).toBe( '0x0000000000000000000000000000000000000000', ); diff --git a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.ts b/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.ts index f55b760a6..dd2a4c1b9 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-reserve-incentives.ts @@ -10,7 +10,6 @@ export interface CalculateReserveIncentivesRequest { reserveIncentiveData: ReservesIncentiveDataHumanized; totalLiquidity: string; totalVariableDebt: string; - totalStableDebt: string; decimals: number; priceInMarketReferenceCurrency: string; // Can be priced in ETH or USD depending on market marketReferenceCurrencyDecimals: number; @@ -21,11 +20,11 @@ export interface ReserveIncentiveResponse { rewardTokenAddress: string; rewardTokenSymbol: string; } + export interface CalculateReserveIncentivesResponse { underlyingAsset: string; aIncentivesData: ReserveIncentiveResponse[]; vIncentivesData: ReserveIncentiveResponse[]; - sIncentivesData: ReserveIncentiveResponse[]; } export function calculateRewardTokenPrice( @@ -74,7 +73,6 @@ export function calculateReserveIncentives({ reserveIncentiveData, totalLiquidity, totalVariableDebt, - totalStableDebt, decimals, priceInMarketReferenceCurrency, }: CalculateReserveIncentivesRequest): CalculateReserveIncentivesResponse { @@ -128,36 +126,10 @@ export function calculateReserveIncentives({ }; return vIncentiveData; }); - const sIncentivesData: ReserveIncentiveResponse[] = - reserveIncentiveData.sIncentiveData.rewardsTokenInformation.map(reward => { - const sIncentivesAPR = rewardEmissionActive(reward) - ? calculateIncentiveAPR({ - emissionPerSecond: reward.emissionPerSecond, - rewardTokenPriceInMarketReferenceCurrency: - calculateRewardTokenPrice( - reserves, - reward.rewardTokenAddress, - reward.rewardPriceFeed, - reward.priceFeedDecimals, - ), - priceInMarketReferenceCurrency, - totalTokenSupply: totalStableDebt, - decimals, - rewardTokenDecimals: reward.rewardTokenDecimals, - }) - : '0'; - const sIncentiveData: ReserveIncentiveResponse = { - incentiveAPR: sIncentivesAPR, - rewardTokenAddress: reward.rewardTokenAddress, - rewardTokenSymbol: reward.rewardTokenSymbol, - }; - return sIncentiveData; - }); return { underlyingAsset: reserveIncentiveData.underlyingAsset, aIncentivesData, vIncentivesData, - sIncentivesData, }; } diff --git a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives-v3.ts b/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives-v3.ts deleted file mode 100644 index 7ef3cf2ec..000000000 --- a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives-v3.ts +++ /dev/null @@ -1,151 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { normalize } from '../../bignumber'; -import { rayDiv } from '../../ray.math'; -import { calculateAccruedIncentives } from './calculate-accrued-incentives'; -import { - ReservesIncentiveDataHumanized, - UserReservesIncentivesDataHumanized, - UserReserveCalculationData, -} from './types-v3'; - -export interface CalculateUserReserveIncentivesRequest { - reserveIncentives: ReservesIncentiveDataHumanized; // token incentive data, from UiIncentiveDataProvider - userIncentives: UserReservesIncentivesDataHumanized; // user incentive data, from UiIncentiveDataProvider - currentTimestamp: number; - userReserveData?: UserReserveCalculationData; // optional to account for case that user no longer has the supply or borrow position but still has unclaimed rewards -} - -export interface UserReserveIncentive { - tokenAddress: string; - incentiveController: string; - rewardTokenAddress: string; - rewardTokenSymbol: string; - rewardTokenDecimals: number; - accruedRewards: BigNumber; - unclaimedRewards: BigNumber; - rewardPriceFeed: string; -} - -// Calculate user supply and borrow incentives for an individual reserve asset -export function calculateUserReserveIncentives({ - reserveIncentives, - userIncentives, - currentTimestamp, - userReserveData, -}: CalculateUserReserveIncentivesRequest): UserReserveIncentive[] { - const calculatedUserIncentives: UserReserveIncentive[] = []; - // Compute incentive data for each reward linked to supply of this reserve - userIncentives.aTokenIncentivesUserData.userRewardsInformation.forEach( - userReserveIncentive => { - const reserveIncentive = - reserveIncentives.aIncentiveData.rewardsTokenInformation.find( - reward => - reward.rewardTokenAddress === - userReserveIncentive.rewardTokenAddress, - ); - if (reserveIncentive) { - // Calculating accrued rewards is only required if user has an active aToken balance - const accruedRewards = userReserveData - ? calculateAccruedIncentives({ - principalUserBalance: new BigNumber( - userReserveData.scaledATokenBalance, - ), - reserveIndex: new BigNumber( - reserveIncentive.tokenIncentivesIndex, - ), - userIndex: new BigNumber( - userReserveIncentive.tokenIncentivesUserIndex, - ), - precision: reserveIncentive.precision, - reserveIndexTimestamp: - reserveIncentive.incentivesLastUpdateTimestamp, - emissionPerSecond: new BigNumber( - reserveIncentive.emissionPerSecond, - ), - totalSupply: rayDiv( - new BigNumber(userReserveData.reserve.totalLiquidity).shiftedBy( - userReserveData.reserve.decimals, - ), - new BigNumber(userReserveData.reserve.liquidityIndex), - ), - currentTimestamp, - emissionEndTimestamp: reserveIncentive.emissionEndTimestamp, - }) - : new BigNumber('0'); - - calculatedUserIncentives.push({ - tokenAddress: userIncentives.aTokenIncentivesUserData.tokenAddress, - incentiveController: - userIncentives.aTokenIncentivesUserData.incentiveControllerAddress, - rewardTokenAddress: userReserveIncentive.rewardTokenAddress, - rewardTokenDecimals: userReserveIncentive.rewardTokenDecimals, - accruedRewards, - unclaimedRewards: new BigNumber( - userReserveIncentive.userUnclaimedRewards, - ), - rewardPriceFeed: normalize( - userReserveIncentive.rewardPriceFeed, - userReserveIncentive.priceFeedDecimals, - ), - rewardTokenSymbol: userReserveIncentive.rewardTokenSymbol, - }); - } - }, - ); - // Compute incentive data for each reward linked to variable borrows of this reserve - userIncentives.vTokenIncentivesUserData.userRewardsInformation.forEach( - userReserveIncentive => { - const reserveIncentive = - reserveIncentives.vIncentiveData.rewardsTokenInformation.find( - reward => - reward.rewardTokenAddress === - userReserveIncentive.rewardTokenAddress, - ); - if (reserveIncentive) { - // Calculating accrued rewards is only required if user has an active variableDebt token balance - const accruedRewards = userReserveData - ? calculateAccruedIncentives({ - principalUserBalance: new BigNumber( - userReserveData.scaledVariableDebt, - ), - reserveIndex: new BigNumber( - reserveIncentive.tokenIncentivesIndex, - ), - userIndex: new BigNumber( - userReserveIncentive.tokenIncentivesUserIndex, - ), - precision: reserveIncentive.precision, - reserveIndexTimestamp: - reserveIncentive.incentivesLastUpdateTimestamp, - emissionPerSecond: new BigNumber( - reserveIncentive.emissionPerSecond, - ), - totalSupply: new BigNumber( - userReserveData.reserve.totalScaledVariableDebt, - ).shiftedBy(userReserveData.reserve.decimals), - currentTimestamp, - emissionEndTimestamp: reserveIncentive.emissionEndTimestamp, - }) - : new BigNumber('0'); - calculatedUserIncentives.push({ - tokenAddress: userIncentives.vTokenIncentivesUserData.tokenAddress, - incentiveController: - userIncentives.vTokenIncentivesUserData.incentiveControllerAddress, - rewardTokenAddress: userReserveIncentive.rewardTokenAddress, - rewardTokenDecimals: userReserveIncentive.rewardTokenDecimals, - accruedRewards, - unclaimedRewards: new BigNumber( - userReserveIncentive.userUnclaimedRewards, - ), - rewardPriceFeed: normalize( - userReserveIncentive.rewardPriceFeed, - userReserveIncentive.priceFeedDecimals, - ), - rewardTokenSymbol: userReserveIncentive.rewardTokenSymbol, - }); - } - }, - ); - - return calculatedUserIncentives; -} diff --git a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.test.ts b/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.test.ts index 2d8460bd5..46d277558 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.test.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.test.ts @@ -13,14 +13,8 @@ import { } from './calculate-user-reserve-incentives'; describe('calculateUserReserveIncentives', () => { - const reserveMock = new ReserveMock() - .addLiquidity(100) - .addVariableDebt(200) - .addStableDebt(300); - const userMock = new UserReserveMock() - .supply(100) - .variableBorrow(200) - .stableBorrow(300); + const reserveMock = new ReserveMock().addLiquidity(100).addVariableDebt(200); + const userMock = new UserReserveMock().supply(100).variableBorrow(200); const reserveIncentiveMock = new ReserveIncentiveMock(); const userIncentiveMock = new UserIncentiveMock(); const currentTimestamp = 1; @@ -78,10 +72,6 @@ describe('calculateUserReserveIncentives', () => { reward => reward.tokenAddress === '0x0000000000000000000000000000000000000000', ); - const sReward = result.find( - reward => - reward.tokenAddress === '0x0000000000000000000000000000000000000000', - ); if (aReward) { expect(normalize(aReward.unclaimedRewards, 18)).toBe( '0.000000000000000001', @@ -94,10 +84,6 @@ describe('calculateUserReserveIncentives', () => { ); } - if (sReward) { - expect(sReward.accruedRewards.toFixed()).toBe('0'); - } - expect(normalize(total, 18)).toBe('0'); }); @@ -117,11 +103,6 @@ describe('calculateUserReserveIncentives', () => { incentiveControllerAddress: '0x0', rewardsTokenInformation: [], }, - sIncentiveData: { - tokenAddress: '0x0', - incentiveControllerAddress: '0x0', - rewardsTokenInformation: [], - }, }, }; const result = calculateUserReserveIncentives( diff --git a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.ts b/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.ts index e9244157a..ac6bd229e 100644 --- a/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.ts +++ b/packages/math-utils/src/formatters/incentive/calculate-user-reserve-incentives.ts @@ -146,60 +146,6 @@ export function calculateUserReserveIncentives({ } }, ); - // Compute incentive data for each reward linked to stable borrows of this reserve - userIncentives.sTokenIncentivesUserData.userRewardsInformation.forEach( - userReserveIncentive => { - const reserveIncentive = - reserveIncentives.sIncentiveData.rewardsTokenInformation.find( - reward => - reward.rewardTokenAddress === - userReserveIncentive.rewardTokenAddress, - ); - if (reserveIncentive) { - // Calculating accrued rewards is only required if user has an active stableDebtToken balance - const accruedRewards = userReserveData - ? calculateAccruedIncentives({ - principalUserBalance: new BigNumber( - userReserveData.principalStableDebt, - ), - reserveIndex: new BigNumber( - reserveIncentive.tokenIncentivesIndex, - ), - userIndex: new BigNumber( - userReserveIncentive.tokenIncentivesUserIndex, - ), - precision: reserveIncentive.precision, - reserveIndexTimestamp: - reserveIncentive.incentivesLastUpdateTimestamp, - emissionPerSecond: new BigNumber( - reserveIncentive.emissionPerSecond, - ), - totalSupply: new BigNumber( - userReserveData.reserve.totalPrincipalStableDebt, - ).shiftedBy(userReserveData.reserve.decimals), - currentTimestamp, - emissionEndTimestamp: reserveIncentive.emissionEndTimestamp, - }) - : new BigNumber('0'); - calculatedUserIncentives.push({ - tokenAddress: userIncentives.sTokenIncentivesUserData.tokenAddress, - incentiveController: - userIncentives.sTokenIncentivesUserData.incentiveControllerAddress, - rewardTokenAddress: userReserveIncentive.rewardTokenAddress, - rewardTokenDecimals: userReserveIncentive.rewardTokenDecimals, - accruedRewards, - unclaimedRewards: new BigNumber( - userReserveIncentive.userUnclaimedRewards, - ), - rewardPriceFeed: normalize( - userReserveIncentive.rewardPriceFeed, - userReserveIncentive.priceFeedDecimals, - ), - rewardTokenSymbol: userReserveIncentive.rewardTokenSymbol, - }); - } - }, - ); return calculatedUserIncentives; } diff --git a/packages/math-utils/src/formatters/incentive/types-v3.ts b/packages/math-utils/src/formatters/incentive/types-v3.ts deleted file mode 100644 index ee6e124e8..000000000 --- a/packages/math-utils/src/formatters/incentive/types-v3.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { IncentiveDataHumanized, UserIncentiveDataHumanized } from './types'; - -// From UiIncentiveDatProvider -export interface ReservesIncentiveDataHumanized { - underlyingAsset: string; - aIncentiveData: IncentiveDataHumanized; - vIncentiveData: IncentiveDataHumanized; -} - -export interface UserReservesIncentivesDataHumanized { - underlyingAsset: string; - aTokenIncentivesUserData: UserIncentiveDataHumanized; - vTokenIncentivesUserData: UserIncentiveDataHumanized; -} - -export interface UserReserveCalculationData { - scaledATokenBalance: string; - scaledVariableDebt: string; - reserve: { - underlyingAsset: string; - totalLiquidity: string; - liquidityIndex: string; - totalScaledVariableDebt: string; - decimals: number; - }; -} - -export interface ReserveCalculationData { - underlyingAsset: string; - symbol: string; - totalLiquidity: string; - totalVariableDebt: string; - formattedPriceInMarketReferenceCurrency: string; - decimals: number; -} diff --git a/packages/math-utils/src/formatters/incentive/types.ts b/packages/math-utils/src/formatters/incentive/types.ts index de7b97c24..dfd8df659 100644 --- a/packages/math-utils/src/formatters/incentive/types.ts +++ b/packages/math-utils/src/formatters/incentive/types.ts @@ -3,34 +3,33 @@ export interface ReservesIncentiveDataHumanized { underlyingAsset: string; aIncentiveData: IncentiveDataHumanized; vIncentiveData: IncentiveDataHumanized; - sIncentiveData: IncentiveDataHumanized; } -export interface IncentiveDataHumanized { - tokenAddress: string; - incentiveControllerAddress: string; - rewardsTokenInformation: RewardInfoHumanized[]; +export interface UserReservesIncentivesDataHumanized { + underlyingAsset: string; + aTokenIncentivesUserData: UserIncentiveDataHumanized; + vTokenIncentivesUserData: UserIncentiveDataHumanized; } -export interface RewardInfoHumanized { - rewardTokenSymbol: string; - rewardTokenAddress: string; - rewardOracleAddress: string; - emissionPerSecond: string; - incentivesLastUpdateTimestamp: number; - tokenIncentivesIndex: string; - emissionEndTimestamp: number; - rewardPriceFeed: string; - rewardTokenDecimals: number; - precision: number; - priceFeedDecimals: number; +export interface UserReserveCalculationData { + scaledATokenBalance: string; + scaledVariableDebt: string; + reserve: { + underlyingAsset: string; + totalLiquidity: string; + liquidityIndex: string; + totalScaledVariableDebt: string; + decimals: number; + }; } -export interface UserReservesIncentivesDataHumanized { +export interface ReserveCalculationData { underlyingAsset: string; - aTokenIncentivesUserData: UserIncentiveDataHumanized; - vTokenIncentivesUserData: UserIncentiveDataHumanized; - sTokenIncentivesUserData: UserIncentiveDataHumanized; + symbol: string; + totalLiquidity: string; + totalVariableDebt: string; + formattedPriceInMarketReferenceCurrency: string; + decimals: number; } export interface UserIncentiveDataHumanized { @@ -50,26 +49,22 @@ export interface UserRewardInfoHumanized { rewardTokenDecimals: number; } -export interface UserReserveCalculationData { - scaledATokenBalance: string; - scaledVariableDebt: string; - principalStableDebt: string; - reserve: { - underlyingAsset: string; - totalLiquidity: string; - liquidityIndex: string; - totalScaledVariableDebt: string; - totalPrincipalStableDebt: string; - decimals: number; - }; +export interface IncentiveDataHumanized { + tokenAddress: string; + incentiveControllerAddress: string; + rewardsTokenInformation: RewardInfoHumanized[]; } -export interface ReserveCalculationData { - underlyingAsset: string; - symbol: string; - totalLiquidity: string; - totalVariableDebt: string; - totalStableDebt: string; - formattedPriceInMarketReferenceCurrency: string; - decimals: number; +export interface RewardInfoHumanized { + rewardTokenSymbol: string; + rewardTokenAddress: string; + rewardOracleAddress: string; + emissionPerSecond: string; + incentivesLastUpdateTimestamp: number; + tokenIncentivesIndex: string; + emissionEndTimestamp: number; + rewardPriceFeed: string; + rewardTokenDecimals: number; + precision: number; + priceFeedDecimals: number; } diff --git a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt-v3.ts b/packages/math-utils/src/formatters/reserve/calculate-reserve-debt-v3.ts deleted file mode 100644 index b6f9b436d..000000000 --- a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt-v3.ts +++ /dev/null @@ -1,49 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { calculateCompoundedInterest } from '../../pool-math'; -import { rayMul } from '../../ray.math'; - -export interface CalculateReserveDebtRequest { - totalScaledVariableDebt: string; - variableBorrowIndex: string; - availableLiquidity: string; - variableBorrowRate: string; - lastUpdateTimestamp: number; - virtualUnderlyingBalance: string; -} - -export interface CalculateReserveDebtResponse { - totalVariableDebt: BigNumber; - totalDebt: BigNumber; - totalLiquidity: BigNumber; -} - -export function calculateReserveDebt( - reserveDebt: CalculateReserveDebtRequest, - currentTimestamp: number, -): CalculateReserveDebtResponse { - const totalVariableDebt = getTotalVariableDebt(reserveDebt, currentTimestamp); - const totalDebt = totalVariableDebt; - const totalLiquidity = totalDebt.plus(reserveDebt.availableLiquidity); - return { - totalVariableDebt, - totalDebt, - totalLiquidity, - }; -} - -function getTotalVariableDebt( - reserveDebt: CalculateReserveDebtRequest, - currentTimestamp: number, -): BigNumber { - return rayMul( - rayMul( - reserveDebt.totalScaledVariableDebt, - reserveDebt.variableBorrowIndex, - ), - calculateCompoundedInterest({ - rate: reserveDebt.variableBorrowRate, - currentTimestamp, - lastUpdateTimestamp: reserveDebt.lastUpdateTimestamp, - }), - ); -} diff --git a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.test.ts b/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.test.ts index 62f071837..3307d6fe9 100644 --- a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.test.ts +++ b/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.test.ts @@ -13,25 +13,20 @@ describe('calculateReserveDebt', () => { expect(result).toEqual({ totalDebt: new BigNumber('0'), totalLiquidity: new BigNumber('0'), - totalStableDebt: new BigNumber('0'), totalVariableDebt: new BigNumber('0'), }); }); it('should calculate reserve debt', () => { - const reserve = new ReserveMock() - .addLiquidity(100) - .addVariableDebt(100) - .addStableDebt(100); + const reserve = new ReserveMock().addLiquidity(100).addVariableDebt(100); const result = calculateReserveDebt( reserve.reserve, reserve.reserve.lastUpdateTimestamp, ); expect(result).toEqual({ - totalDebt: new BigNumber('200000000000000000000'), - totalLiquidity: new BigNumber('300000000000000000000'), - totalStableDebt: new BigNumber('100000000000000000000'), + totalDebt: new BigNumber('100000000000000000000'), + totalLiquidity: new BigNumber('200000000000000000000'), totalVariableDebt: new BigNumber('100000000000000000000'), }); }); diff --git a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.ts b/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.ts index 908ad95c6..b6f9b436d 100644 --- a/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.ts +++ b/packages/math-utils/src/formatters/reserve/calculate-reserve-debt.ts @@ -5,18 +5,14 @@ import { rayMul } from '../../ray.math'; export interface CalculateReserveDebtRequest { totalScaledVariableDebt: string; variableBorrowIndex: string; - totalPrincipalStableDebt: string; availableLiquidity: string; variableBorrowRate: string; lastUpdateTimestamp: number; - averageStableRate: string; - stableDebtLastUpdateTimestamp: number; virtualUnderlyingBalance: string; } export interface CalculateReserveDebtResponse { totalVariableDebt: BigNumber; - totalStableDebt: BigNumber; totalDebt: BigNumber; totalLiquidity: BigNumber; } @@ -26,12 +22,10 @@ export function calculateReserveDebt( currentTimestamp: number, ): CalculateReserveDebtResponse { const totalVariableDebt = getTotalVariableDebt(reserveDebt, currentTimestamp); - const totalStableDebt = getTotalStableDebt(reserveDebt, currentTimestamp); - const totalDebt = totalVariableDebt.plus(totalStableDebt); + const totalDebt = totalVariableDebt; const totalLiquidity = totalDebt.plus(reserveDebt.availableLiquidity); return { totalVariableDebt, - totalStableDebt, totalDebt, totalLiquidity, }; @@ -53,17 +47,3 @@ function getTotalVariableDebt( }), ); } - -function getTotalStableDebt( - reserveDebt: CalculateReserveDebtRequest, - currentTimestamp: number, -): BigNumber { - return rayMul( - reserveDebt.totalPrincipalStableDebt, - calculateCompoundedInterest({ - rate: reserveDebt.averageStableRate, - currentTimestamp, - lastUpdateTimestamp: reserveDebt.stableDebtLastUpdateTimestamp, - }), - ); -} diff --git a/packages/math-utils/src/formatters/reserve/format-reserves-v3.ts b/packages/math-utils/src/formatters/reserve/format-reserves-v3.ts deleted file mode 100644 index 3cc51d144..000000000 --- a/packages/math-utils/src/formatters/reserve/format-reserves-v3.ts +++ /dev/null @@ -1,444 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { - BigNumberValue, - normalize, - normalizeBN, - valueToBigNumber, -} from '../../bignumber'; -import { RAY_DECIMALS, SECONDS_PER_YEAR, USD_DECIMALS } from '../../constants'; -import { LTV_PRECISION } from '../../index'; -import { calculateCompoundedRate } from '../compounded-interest/calculate-compounded-interest'; -import { - calculateReserveIncentives, - CalculateReserveIncentivesResponse, -} from '../incentive/calculate-reserve-incentives-v3'; -import { ReservesIncentiveDataHumanized } from '../incentive/types'; -import { nativeToUSD } from '../usd/native-to-usd'; -import { normalizedToUsd } from '../usd/normalized-to-usd'; -import { calculateReserveDebt } from './calculate-reserve-debt-v3'; - -export interface FormatReserveResponse extends ReserveData { - formattedBaseLTVasCollateral: string; - formattedReserveLiquidationThreshold: string; - formattedReserveLiquidationBonus: string; - formattedEModeLtv: string; - formattedEModeLiquidationBonus: string; - formattedEModeLiquidationThreshold: string; - formattedAvailableLiquidity: string; - totalDebt: string; - totalVariableDebt: string; - totalLiquidity: string; - borrowUsageRatio: string; - supplyUsageRatio: string; - supplyAPY: string; - variableBorrowAPY: string; - unborrowedLiquidity: string; - supplyAPR: string; - variableBorrowAPR: string; - isIsolated: boolean; - isolationModeTotalDebtUSD: string; - availableDebtCeilingUSD: string; - debtCeilingUSD: string; -} - -export interface FormatReserveRequest { - reserve: ReserveData; - currentTimestamp: number; -} - -export interface ReserveData { - id: string; - symbol: string; - name: string; - decimals: number; - underlyingAsset: string; - usageAsCollateralEnabled: boolean; - reserveFactor: string; - baseLTVasCollateral: string; - liquidityIndex: string; - reserveLiquidationThreshold: string; - reserveLiquidationBonus: string; - variableBorrowIndex: string; - variableBorrowRate: string; - availableLiquidity: string; - liquidityRate: string; - totalScaledVariableDebt: string; - lastUpdateTimestamp: number; - // v3 - eModeCategoryId: number; - borrowCap: string; - supplyCap: string; - debtCeiling: string; - debtCeilingDecimals: number; - isolationModeTotalDebt: string; - eModeLtv: number; - eModeLiquidationThreshold: number; - eModeLiquidationBonus: number; - unbacked: string; - virtualAccActive: boolean; - virtualUnderlyingBalance: string; -} - -interface GetComputedReserveFieldsResponse { - formattedReserveLiquidationBonus: string; - formattedEModeLtv: string; - formattedEModeLiquidationThreshold: string; - formattedEModeLiquidationBonus: string; - formattedAvailableLiquidity: BigNumber; - totalDebt: BigNumber; - totalVariableDebt: BigNumber; - totalLiquidity: BigNumber; - borrowUsageRatio: string; - supplyUsageRatio: string; - supplyAPY: BigNumber; - variableBorrowAPY: BigNumber; - unborrowedLiquidity: string; -} - -/** - * @description accrues interest and adds computed fields - */ -function getComputedReserveFields({ - reserve, - currentTimestamp, -}: FormatReserveRequest): GetComputedReserveFieldsResponse { - const { totalDebt, totalVariableDebt, totalLiquidity } = calculateReserveDebt( - reserve, - currentTimestamp, - ); - const borrowUsageRatio = totalLiquidity.eq(0) - ? '0' - : valueToBigNumber(totalDebt).dividedBy(totalLiquidity).toFixed(); - const supplyUsageRatio = totalLiquidity.eq(0) - ? '0' - : valueToBigNumber(totalDebt) - .dividedBy(totalLiquidity.plus(reserve.unbacked)) - .toFixed(); - // https://github.com/aave/protocol-v2/blob/baeb455fad42d3160d571bd8d3a795948b72dd85/contracts/protocol/lendingpool/LendingPoolConfigurator.sol#L284 - const reserveLiquidationBonus = normalize( - valueToBigNumber(reserve.reserveLiquidationBonus).minus( - 10 ** LTV_PRECISION, - ), - LTV_PRECISION, - ); - const eModeLiquidationBonus = normalize( - valueToBigNumber(reserve.eModeLiquidationBonus).minus(10 ** LTV_PRECISION), - LTV_PRECISION, - ); - - /** - * availableLiquidity returned by the helper is the amount of unborrowed tokens - * the actual availableLiquidity might be lower due to borrowCap - */ - const availableLiquidity = - reserve.borrowCap === '0' - ? new BigNumber(reserve.availableLiquidity) - : BigNumber.min( - reserve.availableLiquidity, - new BigNumber(reserve.borrowCap).shiftedBy(reserve.decimals).minus( - // plus 1 as the cap is exclusive - totalDebt.plus(1), - ), - ); - - const supplyAPY = calculateCompoundedRate({ - rate: reserve.liquidityRate, - duration: SECONDS_PER_YEAR, - }); - - const variableBorrowAPY = calculateCompoundedRate({ - rate: reserve.variableBorrowRate, - duration: SECONDS_PER_YEAR, - }); - - return { - totalDebt, - totalVariableDebt, - totalLiquidity, - borrowUsageRatio, - supplyUsageRatio, - formattedReserveLiquidationBonus: reserveLiquidationBonus, - formattedEModeLiquidationBonus: eModeLiquidationBonus, - formattedEModeLiquidationThreshold: - reserve.eModeLiquidationThreshold.toString(), - formattedEModeLtv: reserve.eModeLtv.toString(), - supplyAPY, - variableBorrowAPY, - formattedAvailableLiquidity: availableLiquidity, - unborrowedLiquidity: reserve.availableLiquidity, - }; -} - -interface FormatEnhancedReserveRequest { - reserve: ReserveData & GetComputedReserveFieldsResponse; -} -/** - * @description normalizes reserve values & computed fields - */ -function formatEnhancedReserve({ - reserve, -}: FormatEnhancedReserveRequest): FormatReserveResponse { - const normalizeWithReserve = (n: BigNumberValue) => - normalize(n, reserve.decimals); - - const isIsolated = reserve.debtCeiling !== '0'; - const availableDebtCeilingUSD = isIsolated - ? normalize( - valueToBigNumber(reserve.debtCeiling).minus( - reserve.isolationModeTotalDebt, - ), - reserve.debtCeilingDecimals, - ) - : '0'; - - return { - ...reserve, - totalVariableDebt: normalizeWithReserve(reserve.totalVariableDebt), - totalLiquidity: normalizeWithReserve(reserve.totalLiquidity), - formattedAvailableLiquidity: normalizeWithReserve( - reserve.availableLiquidity, - ), - unborrowedLiquidity: normalizeWithReserve(reserve.unborrowedLiquidity), - borrowUsageRatio: reserve.borrowUsageRatio, - supplyUsageRatio: reserve.supplyUsageRatio, - totalDebt: normalizeWithReserve(reserve.totalDebt), - formattedBaseLTVasCollateral: normalize( - reserve.baseLTVasCollateral, - LTV_PRECISION, - ), - formattedEModeLtv: normalize(reserve.eModeLtv, LTV_PRECISION), - reserveFactor: normalize(reserve.reserveFactor, LTV_PRECISION), - supplyAPY: normalize(reserve.supplyAPY, RAY_DECIMALS), - supplyAPR: normalize(reserve.liquidityRate, RAY_DECIMALS), - variableBorrowAPY: normalize(reserve.variableBorrowAPY, RAY_DECIMALS), - variableBorrowAPR: normalize(reserve.variableBorrowRate, RAY_DECIMALS), - formattedReserveLiquidationThreshold: normalize( - reserve.reserveLiquidationThreshold, - 4, - ), - formattedEModeLiquidationThreshold: normalize( - reserve.eModeLiquidationThreshold, - 4, - ), - formattedReserveLiquidationBonus: normalize( - valueToBigNumber(reserve.reserveLiquidationBonus).minus( - 10 ** LTV_PRECISION, - ), - 4, - ), - formattedEModeLiquidationBonus: normalize( - valueToBigNumber(reserve.eModeLiquidationBonus).minus( - 10 ** LTV_PRECISION, - ), - 4, - ), - totalScaledVariableDebt: normalizeWithReserve( - reserve.totalScaledVariableDebt, - ), - debtCeilingUSD: isIsolated - ? normalize(reserve.debtCeiling, reserve.debtCeilingDecimals) - : '0', - isolationModeTotalDebtUSD: isIsolated - ? normalize(reserve.isolationModeTotalDebt, reserve.debtCeilingDecimals) - : '0', - availableDebtCeilingUSD, - isIsolated, - }; -} - -/** - * @description computes additional fields and normalizes numbers into human readable decimals - */ -export function formatReserve({ - reserve, - currentTimestamp, -}: FormatReserveRequest): FormatReserveResponse { - const computedFields = getComputedReserveFields({ - reserve, - currentTimestamp, - }); - return formatEnhancedReserve({ reserve: { ...reserve, ...computedFields } }); -} - -export type ReserveDataWithPrice = ReserveData & { - priceInMarketReferenceCurrency: string; -}; - -export interface FormatReserveUSDRequest { - reserve: ReserveDataWithPrice; - currentTimestamp: number; - marketReferencePriceInUsd: string; - marketReferenceCurrencyDecimals: number; -} - -export interface FormatReserveUSDResponse extends FormatReserveResponse { - totalLiquidityUSD: string; - availableLiquidityUSD: string; - totalDebtUSD: string; - totalVariableDebtUSD: string; - borrowCapUSD: string; - supplyCapUSD: string; - unbackedUSD: string; - priceInMarketReferenceCurrency: string; - formattedPriceInMarketReferenceCurrency: string; - priceInUSD: string; -} - -/** - * @description computes additional fields and normalizes numbers into human readable decimals - * In addition to that it also converts the numbers to USD - */ -export function formatReserveUSD({ - reserve, - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, -}: FormatReserveUSDRequest): FormatReserveUSDResponse { - const normalizedMarketReferencePriceInUsd = normalizeBN( - marketReferencePriceInUsd, - USD_DECIMALS, - ); - - const computedFields = getComputedReserveFields({ - reserve, - currentTimestamp, - }); - const formattedReserve = formatEnhancedReserve({ - reserve: { ...reserve, ...computedFields }, - }); - - return { - ...formattedReserve, - totalLiquidityUSD: nativeToUSD({ - amount: computedFields.totalLiquidity, - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - availableLiquidityUSD: nativeToUSD({ - amount: computedFields.formattedAvailableLiquidity, - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - totalDebtUSD: nativeToUSD({ - amount: computedFields.totalDebt, - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - totalVariableDebtUSD: nativeToUSD({ - amount: computedFields.totalVariableDebt, - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - formattedPriceInMarketReferenceCurrency: normalize( - reserve.priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - priceInUSD: nativeToUSD({ - amount: new BigNumber(1).shiftedBy(reserve.decimals), - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - // v3 - // caps are already in absolutes - borrowCapUSD: normalizedToUsd( - new BigNumber(reserve.borrowCap), - reserve.priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ).toString(), - supplyCapUSD: normalizedToUsd( - new BigNumber(reserve.supplyCap), - reserve.priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ).toString(), - unbackedUSD: normalizedToUsd( - new BigNumber(reserve.unbacked), - reserve.priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ).toString(), - // debtCeilingUSD: normalizedToUsd( - // new BigNumber(reserve.debtCeiling), - // marketReferencePriceInUsd, - // marketReferenceCurrencyDecimals, - // ).toString(), - }; -} - -export interface FormatReservesUSDRequest { - reserves: T[]; - currentTimestamp: number; - marketReferencePriceInUsd: string; - marketReferenceCurrencyDecimals: number; -} - -export function formatReserves({ - reserves, - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, -}: FormatReservesUSDRequest) { - return reserves.map(reserve => { - const formattedReserve = formatReserveUSD({ - reserve, - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - }); - return { ...reserve, ...formattedReserve }; - }); -} - -export interface FormatReservesAndIncentivesUSDRequest< - T extends ReserveDataWithPrice, -> extends FormatReservesUSDRequest { - reserveIncentives: ReservesIncentiveDataHumanized[]; -} - -export function formatReservesAndIncentives({ - reserves, - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - reserveIncentives, -}: FormatReservesAndIncentivesUSDRequest): Array< - FormatReserveUSDResponse & T & Partial -> { - const formattedReserves = formatReserves({ - reserves, - currentTimestamp, - marketReferenceCurrencyDecimals, - marketReferencePriceInUsd, - }); - - return formattedReserves.map(reserve => { - const reserveIncentive = reserveIncentives.find( - reserveIncentive => - reserveIncentive.underlyingAsset === reserve.underlyingAsset, - ); - if (!reserveIncentive) return reserve; - const incentive = calculateReserveIncentives({ - reserves: formattedReserves, - reserveIncentiveData: reserveIncentive, - totalLiquidity: normalize(reserve.totalLiquidity, -reserve.decimals), - totalVariableDebt: normalize( - reserve.totalVariableDebt, - -reserve.decimals, - ), - priceInMarketReferenceCurrency: - reserve.formattedPriceInMarketReferenceCurrency, - decimals: reserve.decimals, - marketReferenceCurrencyDecimals, - }); - return { ...reserve, ...incentive }; - }); -} diff --git a/packages/math-utils/src/formatters/reserve/index.ts b/packages/math-utils/src/formatters/reserve/index.ts index 1682e5f9d..61d13aa6f 100644 --- a/packages/math-utils/src/formatters/reserve/index.ts +++ b/packages/math-utils/src/formatters/reserve/index.ts @@ -27,17 +27,14 @@ export interface FormatReserveResponse extends ReserveData { formattedAvailableLiquidity: string; totalDebt: string; totalVariableDebt: string; - totalStableDebt: string; totalLiquidity: string; borrowUsageRatio: string; supplyUsageRatio: string; supplyAPY: string; variableBorrowAPY: string; - stableBorrowAPY: string; unborrowedLiquidity: string; supplyAPR: string; variableBorrowAPR: string; - stableBorrowAPR: string; isIsolated: boolean; isolationModeTotalDebtUSD: string; availableDebtCeilingUSD: string; @@ -58,17 +55,13 @@ export interface ReserveData { usageAsCollateralEnabled: boolean; reserveFactor: string; baseLTVasCollateral: string; - averageStableRate: string; - stableDebtLastUpdateTimestamp: number; liquidityIndex: string; reserveLiquidationThreshold: string; reserveLiquidationBonus: string; variableBorrowIndex: string; variableBorrowRate: string; availableLiquidity: string; - stableBorrowRate: string; liquidityRate: string; - totalPrincipalStableDebt: string; totalScaledVariableDebt: string; lastUpdateTimestamp: number; // v3 @@ -93,14 +86,12 @@ interface GetComputedReserveFieldsResponse { formattedEModeLiquidationBonus: string; formattedAvailableLiquidity: BigNumber; totalDebt: BigNumber; - totalStableDebt: BigNumber; totalVariableDebt: BigNumber; totalLiquidity: BigNumber; borrowUsageRatio: string; supplyUsageRatio: string; supplyAPY: BigNumber; variableBorrowAPY: BigNumber; - stableBorrowAPY: BigNumber; unborrowedLiquidity: string; } @@ -111,8 +102,10 @@ function getComputedReserveFields({ reserve, currentTimestamp, }: FormatReserveRequest): GetComputedReserveFieldsResponse { - const { totalDebt, totalStableDebt, totalVariableDebt, totalLiquidity } = - calculateReserveDebt(reserve, currentTimestamp); + const { totalDebt, totalVariableDebt, totalLiquidity } = calculateReserveDebt( + reserve, + currentTimestamp, + ); const borrowUsageRatio = totalLiquidity.eq(0) ? '0' : valueToBigNumber(totalDebt).dividedBy(totalLiquidity).toFixed(); @@ -158,14 +151,8 @@ function getComputedReserveFields({ duration: SECONDS_PER_YEAR, }); - const stableBorrowAPY = calculateCompoundedRate({ - rate: reserve.stableBorrowRate, - duration: SECONDS_PER_YEAR, - }); - return { totalDebt, - totalStableDebt, totalVariableDebt, totalLiquidity, borrowUsageRatio, @@ -177,7 +164,6 @@ function getComputedReserveFields({ formattedEModeLtv: reserve.eModeLtv.toString(), supplyAPY, variableBorrowAPY, - stableBorrowAPY, formattedAvailableLiquidity: availableLiquidity, unborrowedLiquidity: reserve.availableLiquidity, }; @@ -208,7 +194,6 @@ function formatEnhancedReserve({ return { ...reserve, totalVariableDebt: normalizeWithReserve(reserve.totalVariableDebt), - totalStableDebt: normalizeWithReserve(reserve.totalStableDebt), totalLiquidity: normalizeWithReserve(reserve.totalLiquidity), formattedAvailableLiquidity: normalizeWithReserve( reserve.availableLiquidity, @@ -227,8 +212,6 @@ function formatEnhancedReserve({ supplyAPR: normalize(reserve.liquidityRate, RAY_DECIMALS), variableBorrowAPY: normalize(reserve.variableBorrowAPY, RAY_DECIMALS), variableBorrowAPR: normalize(reserve.variableBorrowRate, RAY_DECIMALS), - stableBorrowAPY: normalize(reserve.stableBorrowAPY, RAY_DECIMALS), - stableBorrowAPR: normalize(reserve.stableBorrowRate, RAY_DECIMALS), formattedReserveLiquidationThreshold: normalize( reserve.reserveLiquidationThreshold, 4, @@ -252,9 +235,6 @@ function formatEnhancedReserve({ totalScaledVariableDebt: normalizeWithReserve( reserve.totalScaledVariableDebt, ), - totalPrincipalStableDebt: normalizeWithReserve( - reserve.totalPrincipalStableDebt, - ), debtCeilingUSD: isIsolated ? normalize(reserve.debtCeiling, reserve.debtCeilingDecimals) : '0', @@ -296,7 +276,6 @@ export interface FormatReserveUSDResponse extends FormatReserveResponse { availableLiquidityUSD: string; totalDebtUSD: string; totalVariableDebtUSD: string; - totalStableDebtUSD: string; borrowCapUSD: string; supplyCapUSD: string; unbackedUSD: string; @@ -358,20 +337,6 @@ export function formatReserveUSD({ priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, normalizedMarketReferencePriceInUsd, }), - totalStableDebtUSD: nativeToUSD({ - amount: computedFields.totalStableDebt, - currencyDecimals: reserve.decimals, - marketReferenceCurrencyDecimals, - priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - normalizedMarketReferencePriceInUsd, - }), - // isolationModeTotalDebtUSD: nativeToUSD({ - // amount: computedFields.totalStableDebt, - // currencyDecimals: reserve.decimals, - // marketReferenceCurrencyDecimals, - // priceInMarketReferenceCurrency: reserve.priceInMarketReferenceCurrency, - // marketReferencePriceInUsd, - // }), formattedPriceInMarketReferenceCurrency: normalize( reserve.priceInMarketReferenceCurrency, marketReferenceCurrencyDecimals, @@ -469,7 +434,6 @@ export function formatReservesAndIncentives({ reserve.totalVariableDebt, -reserve.decimals, ), - totalStableDebt: normalize(reserve.totalStableDebt, -reserve.decimals), priceInMarketReferenceCurrency: reserve.formattedPriceInMarketReferenceCurrency, decimals: reserve.decimals, diff --git a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals-v3.ts b/packages/math-utils/src/formatters/user/calculate-user-reserve-totals-v3.ts deleted file mode 100644 index 13c43966e..000000000 --- a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals-v3.ts +++ /dev/null @@ -1,114 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { valueToBigNumber, valueToZDBigNumber } from '../../bignumber'; -import { FormatReserveUSDResponse } from '../reserve/format-reserves-v3'; -import { UserReserveSummaryResponse } from './generate-user-reserve-summary-v3'; - -interface UserReserveTotalsRequest { - userReserves: UserReserveSummaryResponse[]; - userEmodeCategoryId: number; -} - -interface UserReserveTotalsResponse { - totalLiquidityMarketReferenceCurrency: BigNumber; - totalBorrowsMarketReferenceCurrency: BigNumber; - totalCollateralMarketReferenceCurrency: BigNumber; - currentLtv: BigNumber; - currentLiquidationThreshold: BigNumber; - isInIsolationMode: boolean; - isolatedReserve?: FormatReserveUSDResponse; -} - -export function calculateUserReserveTotals({ - userReserves, - userEmodeCategoryId, -}: UserReserveTotalsRequest): UserReserveTotalsResponse { - let totalLiquidityMarketReferenceCurrency = valueToZDBigNumber('0'); - let totalCollateralMarketReferenceCurrency = valueToZDBigNumber('0'); - let totalBorrowsMarketReferenceCurrency = valueToZDBigNumber('0'); - let currentLtv = valueToBigNumber('0'); - let currentLiquidationThreshold = valueToBigNumber('0'); - let isInIsolationMode = false; - let isolatedReserve: FormatReserveUSDResponse | undefined; - - userReserves.forEach(userReserveSummary => { - totalLiquidityMarketReferenceCurrency = - totalLiquidityMarketReferenceCurrency.plus( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ); - totalBorrowsMarketReferenceCurrency = - totalBorrowsMarketReferenceCurrency.plus( - userReserveSummary.variableBorrowsMarketReferenceCurrency, - ); - - if ( - userReserveSummary.userReserve.reserve.reserveLiquidationThreshold !== - '0' && - userReserveSummary.userReserve.usageAsCollateralEnabledOnUser - ) { - if (userReserveSummary.userReserve.reserve.debtCeiling !== '0') { - isolatedReserve = userReserveSummary.userReserve.reserve; - isInIsolationMode = true; - } - - totalCollateralMarketReferenceCurrency = - totalCollateralMarketReferenceCurrency.plus( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ); - if ( - userEmodeCategoryId && - userEmodeCategoryId === - userReserveSummary.userReserve.reserve.eModeCategoryId - ) { - currentLtv = currentLtv.plus( - valueToBigNumber( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ).multipliedBy(userReserveSummary.userReserve.reserve.eModeLtv), - ); - currentLiquidationThreshold = currentLiquidationThreshold.plus( - valueToBigNumber( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ).multipliedBy( - userReserveSummary.userReserve.reserve.eModeLiquidationThreshold, - ), - ); - } else { - currentLtv = currentLtv.plus( - valueToBigNumber( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ).multipliedBy( - userReserveSummary.userReserve.reserve.baseLTVasCollateral, - ), - ); - currentLiquidationThreshold = currentLiquidationThreshold.plus( - valueToBigNumber( - userReserveSummary.underlyingBalanceMarketReferenceCurrency, - ).multipliedBy( - userReserveSummary.userReserve.reserve.reserveLiquidationThreshold, - ), - ); - } - } - }); - - if (currentLtv.gt(0)) { - currentLtv = valueToZDBigNumber( - currentLtv.div(totalCollateralMarketReferenceCurrency), - ); - } - - if (currentLiquidationThreshold.gt(0)) { - currentLiquidationThreshold = valueToZDBigNumber( - currentLiquidationThreshold.div(totalCollateralMarketReferenceCurrency), - ); - } - - return { - totalLiquidityMarketReferenceCurrency, - totalBorrowsMarketReferenceCurrency, - totalCollateralMarketReferenceCurrency, - currentLtv, - currentLiquidationThreshold, - isInIsolationMode, - isolatedReserve, - }; -} diff --git a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.test.ts b/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.test.ts index b28725453..9591c0502 100644 --- a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.test.ts +++ b/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.test.ts @@ -27,7 +27,7 @@ describe('calculateUserReserveTotals', () => { const ethReserveMock = new UserReserveMock({ decimals: 18 }) .supply(200) - .stableBorrow(100); + .variableBorrow(100); const rawETHSummary: UserReserveSummaryResponse = generateUserReserveSummary({ userReserve: { ...ethReserveMock.userReserve, diff --git a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.ts b/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.ts index 0447786fd..157b7b2df 100644 --- a/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.ts +++ b/packages/math-utils/src/formatters/user/calculate-user-reserve-totals.ts @@ -35,9 +35,10 @@ export function calculateUserReserveTotals({ totalLiquidityMarketReferenceCurrency.plus( userReserveSummary.underlyingBalanceMarketReferenceCurrency, ); - totalBorrowsMarketReferenceCurrency = totalBorrowsMarketReferenceCurrency - .plus(userReserveSummary.variableBorrowsMarketReferenceCurrency) - .plus(userReserveSummary.stableBorrowsMarketReferenceCurrency); + totalBorrowsMarketReferenceCurrency = + totalBorrowsMarketReferenceCurrency.plus( + userReserveSummary.variableBorrowsMarketReferenceCurrency, + ); if ( userReserveSummary.userReserve.reserve.reserveLiquidationThreshold !== diff --git a/packages/math-utils/src/formatters/user/format-user-reserve-v3.ts b/packages/math-utils/src/formatters/user/format-user-reserve-v3.ts deleted file mode 100644 index b82d142d4..000000000 --- a/packages/math-utils/src/formatters/user/format-user-reserve-v3.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { BigNumberValue, normalize } from '../../bignumber'; -import { FormatReserveUSDResponse } from '../reserve/format-reserves-v3'; -import { ComputedUserReserve } from './format-user-summary-v3'; -import { UserReserveSummaryResponse } from './generate-user-reserve-summary-v3'; - -export interface FormatUserReserveRequest< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - reserve: UserReserveSummaryResponse; - marketReferenceCurrencyDecimals: number; -} - -export interface FormatUserReserveResponse< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - reserve: ComputedUserReserve; -} - -export function formatUserReserve< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, ->({ - reserve: _reserve, - marketReferenceCurrencyDecimals, -}: FormatUserReserveRequest): ComputedUserReserve { - const { userReserve } = _reserve; - const { reserve } = userReserve; - const reserveDecimals = reserve.decimals; - - const normalizeWithReserve = (n: BigNumberValue) => - normalize(n, reserve.decimals); - - return { - ...userReserve, - underlyingBalance: normalize(_reserve.underlyingBalance, reserveDecimals), - underlyingBalanceMarketReferenceCurrency: normalize( - _reserve.underlyingBalanceMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - underlyingBalanceUSD: _reserve.underlyingBalanceUSD.toString(), - variableBorrows: normalizeWithReserve(_reserve.variableBorrows), - variableBorrowsMarketReferenceCurrency: normalize( - _reserve.variableBorrowsMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - variableBorrowsUSD: _reserve.variableBorrowsUSD.toString(), - totalBorrows: normalizeWithReserve(_reserve.totalBorrows), - totalBorrowsMarketReferenceCurrency: normalize( - _reserve.totalBorrowsMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - totalBorrowsUSD: _reserve.totalBorrowsUSD.toString(), - }; -} diff --git a/packages/math-utils/src/formatters/user/format-user-reserve.test.ts b/packages/math-utils/src/formatters/user/format-user-reserve.test.ts index b3c6362bc..964b806be 100644 --- a/packages/math-utils/src/formatters/user/format-user-reserve.test.ts +++ b/packages/math-utils/src/formatters/user/format-user-reserve.test.ts @@ -14,8 +14,7 @@ describe('formatUserReserve', () => { const currentTimestamp = 1; const usdcUserMock = new UserReserveMock({ decimals: 6 }) .supply(500) - .variableBorrow(100) - .stableBorrow(100); + .variableBorrow(100); const rawUSDCSummary: UserReserveSummaryResponse = generateUserReserveSummary( { userReserve: { @@ -39,11 +38,11 @@ describe('formatUserReserve', () => { '5000', ); expect(formattedReserve.underlyingBalanceUSD).toEqual('50000'); - expect(formattedReserve.totalBorrows).toEqual('200'); + expect(formattedReserve.totalBorrows).toEqual('100'); expect(formattedReserve.totalBorrowsMarketReferenceCurrency).toEqual( - '2000', + '1000', ); - expect(formattedReserve.totalBorrowsUSD).toEqual('20000'); + expect(formattedReserve.totalBorrowsUSD).toEqual('10000'); expect(formattedReserve.usageAsCollateralEnabledOnUser).toEqual(true); expect(formattedReserve.variableBorrows).toEqual('100'); expect(formattedReserve.variableBorrowsMarketReferenceCurrency).toEqual( diff --git a/packages/math-utils/src/formatters/user/format-user-reserve.ts b/packages/math-utils/src/formatters/user/format-user-reserve.ts index 1256240ce..5da744af1 100644 --- a/packages/math-utils/src/formatters/user/format-user-reserve.ts +++ b/packages/math-utils/src/formatters/user/format-user-reserve.ts @@ -1,9 +1,7 @@ -import { BigNumberValue, normalize, valueToZDBigNumber } from '../../bignumber'; -import { RAY_DECIMALS, SECONDS_PER_YEAR } from '../../constants'; -import { RAY, rayPow } from '../../ray.math'; +import { BigNumberValue, normalize } from '../../bignumber'; import { FormatReserveUSDResponse } from '../reserve'; import { UserReserveSummaryResponse } from './generate-user-reserve-summary'; -import { ComputedUserReserve } from './index'; +import { ComputedUserReserve } from '.'; export interface FormatUserReserveRequest< T extends FormatReserveUSDResponse = FormatReserveUSDResponse, @@ -31,13 +29,6 @@ export function formatUserReserve< const normalizeWithReserve = (n: BigNumberValue) => normalize(n, reserve.decimals); - const exactStableBorrowRate = rayPow( - valueToZDBigNumber(userReserve.stableBorrowRate) - .dividedBy(SECONDS_PER_YEAR) - .plus(RAY), - SECONDS_PER_YEAR, - ).minus(RAY); - return { ...userReserve, underlyingBalance: normalize(_reserve.underlyingBalance, reserveDecimals), @@ -46,12 +37,6 @@ export function formatUserReserve< marketReferenceCurrencyDecimals, ), underlyingBalanceUSD: _reserve.underlyingBalanceUSD.toString(), - stableBorrows: normalizeWithReserve(_reserve.stableBorrows), - stableBorrowsMarketReferenceCurrency: normalize( - _reserve.stableBorrowsMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - stableBorrowsUSD: _reserve.stableBorrowsUSD.toString(), variableBorrows: normalizeWithReserve(_reserve.variableBorrows), variableBorrowsMarketReferenceCurrency: normalize( _reserve.variableBorrowsMarketReferenceCurrency, @@ -64,7 +49,5 @@ export function formatUserReserve< marketReferenceCurrencyDecimals, ), totalBorrowsUSD: _reserve.totalBorrowsUSD.toString(), - stableBorrowAPR: normalize(userReserve.stableBorrowRate, RAY_DECIMALS), - stableBorrowAPY: normalize(exactStableBorrowRate, RAY_DECIMALS), }; } diff --git a/packages/math-utils/src/formatters/user/format-user-summary-v3.ts b/packages/math-utils/src/formatters/user/format-user-summary-v3.ts deleted file mode 100644 index 6e36ab31a..000000000 --- a/packages/math-utils/src/formatters/user/format-user-summary-v3.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { BigNumberValue, normalize } from '../../bignumber'; -import { LTV_PRECISION, USD_DECIMALS } from '../../constants'; -import { - calculateAllUserIncentives, - UserIncentiveDict, -} from '../incentive/calculate-all-user-incentives-v3'; -import { - ReservesIncentiveDataHumanized, - UserReservesIncentivesDataHumanized, -} from '../incentive/types'; -import { FormatReserveUSDResponse } from '../reserve/format-reserves-v3'; -import { formatUserReserve } from './format-user-reserve-v3'; -import { generateRawUserSummary } from './generate-raw-user-summary-v3'; -import { - generateUserReserveSummary, - UserReserveSummaryResponse, -} from './generate-user-reserve-summary-v3'; - -export interface UserReserveData { - underlyingAsset: string; - scaledATokenBalance: string; - usageAsCollateralEnabledOnUser: boolean; - scaledVariableDebt: string; -} - -export interface CombinedReserveData< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> extends UserReserveData { - reserve: T; -} - -export interface ComputedUserReserve< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> extends CombinedReserveData { - underlyingBalance: string; - underlyingBalanceMarketReferenceCurrency: string; - underlyingBalanceUSD: string; - variableBorrows: string; - variableBorrowsMarketReferenceCurrency: string; - variableBorrowsUSD: string; - totalBorrows: string; - totalBorrowsMarketReferenceCurrency: string; - totalBorrowsUSD: string; -} - -export interface FormatUserSummaryRequest< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - userReserves: UserReserveData[]; - formattedReserves: T[]; - marketReferencePriceInUsd: BigNumberValue; - marketReferenceCurrencyDecimals: number; - currentTimestamp: number; - userEmodeCategoryId: number; -} - -export interface FormatUserSummaryResponse< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - userReservesData: Array>; - totalLiquidityMarketReferenceCurrency: string; - totalLiquidityUSD: string; - totalCollateralMarketReferenceCurrency: string; - totalCollateralUSD: string; - totalBorrowsMarketReferenceCurrency: string; - totalBorrowsUSD: string; - netWorthUSD: string; - availableBorrowsMarketReferenceCurrency: string; - availableBorrowsUSD: string; - currentLoanToValue: string; - currentLiquidationThreshold: string; - healthFactor: string; - userEmodeCategoryId: number; - isInIsolationMode: boolean; - isolatedReserve?: FormatReserveUSDResponse; -} - -export interface FormatUserSummaryAndIncentivesRequest< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> extends FormatUserSummaryRequest { - reserveIncentives: ReservesIncentiveDataHumanized[]; - userIncentives: UserReservesIncentivesDataHumanized[]; -} - -export interface FormatUserSummaryAndIncentivesResponse< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> extends FormatUserSummaryResponse { - calculatedUserIncentives: UserIncentiveDict; -} - -export function formatUserSummary< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, ->({ - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - userReserves, - formattedReserves, - userEmodeCategoryId, -}: FormatUserSummaryRequest): FormatUserSummaryResponse { - const normalizedMarketRefPriceInUsd = normalize( - marketReferencePriceInUsd, - USD_DECIMALS, - ); - - // Combine raw user and formatted reserve data - const combinedReserves: Array> = []; - - userReserves.forEach(userReserve => { - const reserve = formattedReserves.find( - r => - r.underlyingAsset.toLowerCase() === - userReserve.underlyingAsset.toLowerCase(), - ); - if (reserve) { - combinedReserves.push({ - ...userReserve, - reserve, - }); - } - }); - - const computedUserReserves: Array> = - combinedReserves.map(userReserve => - generateUserReserveSummary({ - userReserve, - marketReferencePriceInUsdNormalized: normalizedMarketRefPriceInUsd, - marketReferenceCurrencyDecimals, - currentTimestamp, - }), - ); - - const formattedUserReserves = computedUserReserves.map(computedUserReserve => - formatUserReserve({ - reserve: computedUserReserve, - marketReferenceCurrencyDecimals, - }), - ); - - const userData = generateRawUserSummary({ - userReserves: computedUserReserves, - marketReferencePriceInUsd: normalizedMarketRefPriceInUsd, - marketReferenceCurrencyDecimals, - userEmodeCategoryId, - }); - - return { - userReservesData: formattedUserReserves, - totalLiquidityMarketReferenceCurrency: normalize( - userData.totalLiquidityMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - totalLiquidityUSD: userData.totalLiquidityUSD.toString(), - totalCollateralMarketReferenceCurrency: normalize( - userData.totalCollateralMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - totalCollateralUSD: userData.totalCollateralUSD.toString(), - totalBorrowsMarketReferenceCurrency: normalize( - userData.totalBorrowsMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - totalBorrowsUSD: userData.totalBorrowsUSD.toString(), - netWorthUSD: userData.totalLiquidityUSD - .minus(userData.totalBorrowsUSD) - .toString(), - availableBorrowsMarketReferenceCurrency: normalize( - userData.availableBorrowsMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - ), - availableBorrowsUSD: userData.availableBorrowsUSD.toString(), - currentLoanToValue: normalize(userData.currentLoanToValue, LTV_PRECISION), - currentLiquidationThreshold: normalize( - userData.currentLiquidationThreshold, - LTV_PRECISION, - ), - healthFactor: userData.healthFactor.toFixed(), - userEmodeCategoryId, - isInIsolationMode: userData.isInIsolationMode, - isolatedReserve: userData.isolatedReserve, - }; -} - -export function formatUserSummaryAndIncentives< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, ->({ - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - userReserves, - formattedReserves, - userEmodeCategoryId, - reserveIncentives, - userIncentives, -}: FormatUserSummaryAndIncentivesRequest): FormatUserSummaryAndIncentivesResponse { - const formattedUserSummary = formatUserSummary({ - currentTimestamp, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - userReserves, - formattedReserves, - userEmodeCategoryId, - }); - - const calculatedUserIncentives = calculateAllUserIncentives({ - reserveIncentives, - userIncentives, - userReserves: formattedUserSummary.userReservesData, - currentTimestamp, - }); - - return { - ...formattedUserSummary, - calculatedUserIncentives, - }; -} diff --git a/packages/math-utils/src/formatters/user/generate-raw-user-summary-v3.ts b/packages/math-utils/src/formatters/user/generate-raw-user-summary-v3.ts deleted file mode 100644 index c530a2a99..000000000 --- a/packages/math-utils/src/formatters/user/generate-raw-user-summary-v3.ts +++ /dev/null @@ -1,112 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { BigNumberValue, normalizeBN } from '../../bignumber'; -import { - calculateAvailableBorrowsMarketReferenceCurrency, - calculateHealthFactorFromBalances, -} from '../../pool-math'; -import { FormatReserveUSDResponse } from '../reserve/format-reserves-v3'; -import { normalizedToUsd } from '../usd/normalized-to-usd'; -import { calculateUserReserveTotals } from './calculate-user-reserve-totals-v3'; -import { UserReserveSummaryResponse } from './generate-user-reserve-summary-v3'; - -export interface RawUserSummaryRequest { - userReserves: UserReserveSummaryResponse[]; - marketReferencePriceInUsd: BigNumberValue; - marketReferenceCurrencyDecimals: number; - userEmodeCategoryId: number; -} - -export interface RawUserSummaryResponse { - totalLiquidityUSD: BigNumber; - totalCollateralUSD: BigNumber; - totalBorrowsUSD: BigNumber; - totalLiquidityMarketReferenceCurrency: BigNumber; - totalCollateralMarketReferenceCurrency: BigNumber; - totalBorrowsMarketReferenceCurrency: BigNumber; - availableBorrowsMarketReferenceCurrency: BigNumber; - availableBorrowsUSD: BigNumber; - currentLoanToValue: BigNumber; - currentLiquidationThreshold: BigNumber; - healthFactor: BigNumber; - isInIsolationMode: boolean; - isolatedReserve?: FormatReserveUSDResponse; -} - -export function generateRawUserSummary({ - userReserves, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - userEmodeCategoryId, -}: RawUserSummaryRequest): RawUserSummaryResponse { - const { - totalLiquidityMarketReferenceCurrency, - totalBorrowsMarketReferenceCurrency, - totalCollateralMarketReferenceCurrency, - currentLtv, - currentLiquidationThreshold, - isInIsolationMode, - isolatedReserve, - } = calculateUserReserveTotals({ userReserves, userEmodeCategoryId }); - - const _availableBorrowsMarketReferenceCurrency = - calculateAvailableBorrowsMarketReferenceCurrency({ - collateralBalanceMarketReferenceCurrency: - totalCollateralMarketReferenceCurrency, - borrowBalanceMarketReferenceCurrency: totalBorrowsMarketReferenceCurrency, - currentLtv, - }); - - const availableBorrowsMarketReferenceCurrency = - isInIsolationMode && isolatedReserve - ? BigNumber.min( - BigNumber.max( - 0, - normalizeBN( - new BigNumber(isolatedReserve.debtCeiling).minus( - isolatedReserve.isolationModeTotalDebt, - ), - isolatedReserve.debtCeilingDecimals - - marketReferenceCurrencyDecimals, - ), - ), - _availableBorrowsMarketReferenceCurrency, - ) - : _availableBorrowsMarketReferenceCurrency; - - return { - isInIsolationMode, - isolatedReserve, - totalLiquidityUSD: normalizedToUsd( - totalLiquidityMarketReferenceCurrency, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - ), - totalCollateralUSD: normalizedToUsd( - totalCollateralMarketReferenceCurrency, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - ), - totalBorrowsUSD: normalizedToUsd( - totalBorrowsMarketReferenceCurrency, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - ), - totalLiquidityMarketReferenceCurrency, - totalCollateralMarketReferenceCurrency, - totalBorrowsMarketReferenceCurrency, - availableBorrowsMarketReferenceCurrency, - availableBorrowsUSD: normalizedToUsd( - availableBorrowsMarketReferenceCurrency, - marketReferencePriceInUsd, - marketReferenceCurrencyDecimals, - ), - currentLoanToValue: currentLtv, - currentLiquidationThreshold, - healthFactor: calculateHealthFactorFromBalances({ - collateralBalanceMarketReferenceCurrency: - totalCollateralMarketReferenceCurrency, - borrowBalanceMarketReferenceCurrency: totalBorrowsMarketReferenceCurrency, - currentLiquidationThreshold, - }), - }; -} diff --git a/packages/math-utils/src/formatters/user/generate-user-reserve-summary-v3.ts b/packages/math-utils/src/formatters/user/generate-user-reserve-summary-v3.ts deleted file mode 100644 index 4fea0ad3c..000000000 --- a/packages/math-utils/src/formatters/user/generate-user-reserve-summary-v3.ts +++ /dev/null @@ -1,94 +0,0 @@ -import BigNumber from 'bignumber.js'; -import { BigNumberValue } from '../../bignumber'; -import { - getLinearBalance, - getMarketReferenceCurrencyAndUsdBalance, - getCompoundedBalance, -} from '../../pool-math'; -import { FormatReserveUSDResponse } from '../reserve/format-reserves-v3'; -import { CombinedReserveData } from './format-user-summary-v3'; - -export interface UserReserveSummaryRequest< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - userReserve: CombinedReserveData; - marketReferencePriceInUsdNormalized: BigNumberValue; - marketReferenceCurrencyDecimals: number; - currentTimestamp: number; -} - -export interface UserReserveSummaryResponse< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, -> { - userReserve: CombinedReserveData; - underlyingBalance: BigNumber; - underlyingBalanceMarketReferenceCurrency: BigNumber; - underlyingBalanceUSD: BigNumber; - variableBorrows: BigNumber; - variableBorrowsMarketReferenceCurrency: BigNumber; - variableBorrowsUSD: BigNumber; - totalBorrows: BigNumber; - totalBorrowsMarketReferenceCurrency: BigNumber; - totalBorrowsUSD: BigNumber; -} - -export function generateUserReserveSummary< - T extends FormatReserveUSDResponse = FormatReserveUSDResponse, ->({ - userReserve, - marketReferencePriceInUsdNormalized, - marketReferenceCurrencyDecimals, - currentTimestamp, -}: UserReserveSummaryRequest): UserReserveSummaryResponse { - const poolReserve: FormatReserveUSDResponse = userReserve.reserve; - const { priceInMarketReferenceCurrency, decimals } = poolReserve; - const underlyingBalance = getLinearBalance({ - balance: userReserve.scaledATokenBalance, - index: poolReserve.liquidityIndex, - rate: poolReserve.liquidityRate, - lastUpdateTimestamp: poolReserve.lastUpdateTimestamp, - currentTimestamp, - }); - const { - marketReferenceCurrencyBalance: underlyingBalanceMarketReferenceCurrency, - usdBalance: underlyingBalanceUSD, - } = getMarketReferenceCurrencyAndUsdBalance({ - balance: underlyingBalance, - priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - decimals, - marketReferencePriceInUsdNormalized, - }); - - const variableBorrows = getCompoundedBalance({ - principalBalance: userReserve.scaledVariableDebt, - reserveIndex: poolReserve.variableBorrowIndex, - reserveRate: poolReserve.variableBorrowRate, - lastUpdateTimestamp: poolReserve.lastUpdateTimestamp, - currentTimestamp, - }); - - const { - marketReferenceCurrencyBalance: variableBorrowsMarketReferenceCurrency, - usdBalance: variableBorrowsUSD, - } = getMarketReferenceCurrencyAndUsdBalance({ - balance: variableBorrows, - priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - decimals, - marketReferencePriceInUsdNormalized, - }); - - return { - userReserve, - underlyingBalance, - underlyingBalanceMarketReferenceCurrency, - underlyingBalanceUSD, - variableBorrows, - variableBorrowsMarketReferenceCurrency, - variableBorrowsUSD, - totalBorrows: variableBorrows, - totalBorrowsMarketReferenceCurrency: variableBorrowsMarketReferenceCurrency, - totalBorrowsUSD: variableBorrowsUSD, - }; -} diff --git a/packages/math-utils/src/formatters/user/generate-user-reserve-summary.test.ts b/packages/math-utils/src/formatters/user/generate-user-reserve-summary.test.ts index fb802566b..5985aa95f 100644 --- a/packages/math-utils/src/formatters/user/generate-user-reserve-summary.test.ts +++ b/packages/math-utils/src/formatters/user/generate-user-reserve-summary.test.ts @@ -8,8 +8,7 @@ describe('generateUserReserveSummary', () => { // 1 reserve token = 10 marketReferenceCurrency tokens = 100 USD const usdcUserMock = new UserReserveMock({ decimals: 6 }) .supply(200) - .variableBorrow(50) - .stableBorrow(50); + .variableBorrow(50); const { decimals } = usdcUserMock.reserve; const marketReferenceCurrencyDecimals = 18; const rawSummary: UserReserveSummaryResponse = generateUserReserveSummary({ @@ -39,23 +38,14 @@ describe('generateUserReserveSummary', () => { .toFixed(), ).toEqual('500'); expect(rawSummary.variableBorrowsUSD.toFixed()).toEqual('5000'); - expect(rawSummary.stableBorrows.shiftedBy(-decimals).toFixed()).toEqual( - '50', - ); - expect( - rawSummary.stableBorrowsMarketReferenceCurrency - .shiftedBy(-marketReferenceCurrencyDecimals) - .toFixed(), - ).toEqual('500'); - expect(rawSummary.stableBorrowsUSD.toFixed()).toEqual('5000'); expect(rawSummary.totalBorrows.shiftedBy(-decimals).toFixed()).toEqual( - '100', + '50', ); expect( rawSummary.totalBorrowsMarketReferenceCurrency .shiftedBy(-marketReferenceCurrencyDecimals) .toFixed(), - ).toEqual('1000'); - expect(rawSummary.totalBorrowsUSD.toFixed()).toEqual('10000'); + ).toEqual('500'); + expect(rawSummary.totalBorrowsUSD.toFixed()).toEqual('5000'); }); }); diff --git a/packages/math-utils/src/formatters/user/generate-user-reserve-summary.ts b/packages/math-utils/src/formatters/user/generate-user-reserve-summary.ts index 6e15a9261..50ce31ac5 100644 --- a/packages/math-utils/src/formatters/user/generate-user-reserve-summary.ts +++ b/packages/math-utils/src/formatters/user/generate-user-reserve-summary.ts @@ -4,10 +4,9 @@ import { getLinearBalance, getMarketReferenceCurrencyAndUsdBalance, getCompoundedBalance, - getCompoundedStableBalance, } from '../../pool-math'; import { FormatReserveUSDResponse } from '../reserve'; -import { CombinedReserveData } from './index'; +import { CombinedReserveData } from '.'; export interface UserReserveSummaryRequest< T extends FormatReserveUSDResponse = FormatReserveUSDResponse, @@ -28,9 +27,6 @@ export interface UserReserveSummaryResponse< variableBorrows: BigNumber; variableBorrowsMarketReferenceCurrency: BigNumber; variableBorrowsUSD: BigNumber; - stableBorrows: BigNumber; - stableBorrowsMarketReferenceCurrency: BigNumber; - stableBorrowsUSD: BigNumber; totalBorrows: BigNumber; totalBorrowsMarketReferenceCurrency: BigNumber; totalBorrowsUSD: BigNumber; @@ -83,24 +79,6 @@ export function generateUserReserveSummary< marketReferencePriceInUsdNormalized, }); - const stableBorrows = getCompoundedStableBalance({ - principalBalance: userReserve.principalStableDebt, - userStableRate: userReserve.stableBorrowRate, - lastUpdateTimestamp: userReserve.stableBorrowLastUpdateTimestamp, - currentTimestamp, - }); - - const { - marketReferenceCurrencyBalance: stableBorrowsMarketReferenceCurrency, - usdBalance: stableBorrowsUSD, - } = getMarketReferenceCurrencyAndUsdBalance({ - balance: stableBorrows, - priceInMarketReferenceCurrency, - marketReferenceCurrencyDecimals, - decimals, - marketReferencePriceInUsdNormalized, - }); - return { userReserve, underlyingBalance, @@ -109,14 +87,8 @@ export function generateUserReserveSummary< variableBorrows, variableBorrowsMarketReferenceCurrency, variableBorrowsUSD, - stableBorrows, - stableBorrowsMarketReferenceCurrency, - stableBorrowsUSD, - totalBorrows: variableBorrows.plus(stableBorrows), - totalBorrowsMarketReferenceCurrency: - variableBorrowsMarketReferenceCurrency.plus( - stableBorrowsMarketReferenceCurrency, - ), - totalBorrowsUSD: variableBorrowsUSD.plus(stableBorrowsUSD), + totalBorrows: variableBorrows, + totalBorrowsMarketReferenceCurrency: variableBorrowsMarketReferenceCurrency, + totalBorrowsUSD: variableBorrowsUSD, }; } diff --git a/packages/math-utils/src/formatters/user/index.test.ts b/packages/math-utils/src/formatters/user/index.test.ts index c5bb5f191..eff8a9a3d 100644 --- a/packages/math-utils/src/formatters/user/index.test.ts +++ b/packages/math-utils/src/formatters/user/index.test.ts @@ -16,8 +16,7 @@ import { describe('formatUserSummaryETHMarket', () => { const usdcUserMock = new UserReserveMock({ decimals: 6 }) .supply(200) - .variableBorrow(50) - .stableBorrow(50); + .variableBorrow(100); const marketReferencePriceInUsd = 10 ** 9; // 10 const marketReferenceCurrencyDecimals = 18; const request: FormatUserSummaryRequest = { @@ -118,8 +117,8 @@ describe('formatUserSummaryETHMarket', () => { }); describe('formatUserSummaryAndIncentives', () => { - const ethUserMock = new UserReserveMock({ decimals: 18 }).stableBorrow(50); - const usdcUserMock = new UserReserveMock({ decimals: 6 }).stableBorrow(100); + const ethUserMock = new UserReserveMock({ decimals: 18 }).variableBorrow(50); + const usdcUserMock = new UserReserveMock({ decimals: 6 }).variableBorrow(100); const reserveIncentiveMock = new ReserveIncentiveMock(); const userIncentiveMock = new UserIncentiveMock(); const marketReferencePriceInUsd = '10'; diff --git a/packages/math-utils/src/formatters/user/index.ts b/packages/math-utils/src/formatters/user/index.ts index 6c3476131..c3de4dcb5 100644 --- a/packages/math-utils/src/formatters/user/index.ts +++ b/packages/math-utils/src/formatters/user/index.ts @@ -1,6 +1,9 @@ import { BigNumberValue, normalize } from '../../bignumber'; import { LTV_PRECISION, USD_DECIMALS } from '../../constants'; -import { calculateAllUserIncentives, UserIncentiveDict } from '../incentive'; +import { + calculateAllUserIncentives, + UserIncentiveDict, +} from '../incentive/calculate-all-user-incentives'; import { ReservesIncentiveDataHumanized, UserReservesIncentivesDataHumanized, @@ -17,10 +20,7 @@ export interface UserReserveData { underlyingAsset: string; scaledATokenBalance: string; usageAsCollateralEnabledOnUser: boolean; - stableBorrowRate: string; scaledVariableDebt: string; - principalStableDebt: string; - stableBorrowLastUpdateTimestamp: number; } export interface CombinedReserveData< @@ -38,14 +38,9 @@ export interface ComputedUserReserve< variableBorrows: string; variableBorrowsMarketReferenceCurrency: string; variableBorrowsUSD: string; - stableBorrows: string; - stableBorrowsMarketReferenceCurrency: string; - stableBorrowsUSD: string; totalBorrows: string; totalBorrowsMarketReferenceCurrency: string; totalBorrowsUSD: string; - stableBorrowAPY: string; - stableBorrowAPR: string; } export interface FormatUserSummaryRequest< diff --git a/packages/math-utils/src/mocks.ts b/packages/math-utils/src/mocks.ts index e2c650fde..5d0aef9e3 100644 --- a/packages/math-utils/src/mocks.ts +++ b/packages/math-utils/src/mocks.ts @@ -25,17 +25,13 @@ export class ReserveMock { eModeCategoryId: 1, reserveFactor: '0', baseLTVasCollateral: '5000', // 50% - averageStableRate: '0', - stableDebtLastUpdateTimestamp: 1, liquidityIndex: RAY.toString(), reserveLiquidationThreshold: '6000', // 60% reserveLiquidationBonus: '0', variableBorrowIndex: RAY.toString(), variableBorrowRate: RAY.multipliedBy(3).toString(), availableLiquidity: '0', - stableBorrowRate: RAY.multipliedBy(2).toString(), liquidityRate: RAY.multipliedBy(1).toString(), - totalPrincipalStableDebt: '0', totalScaledVariableDebt: '0', lastUpdateTimestamp: 1, borrowCap: '0', @@ -68,14 +64,6 @@ export class ReserveMock { return this; } - addStableDebt(amount: number | string) { - this.reserve.totalPrincipalStableDebt = new BigNumber(amount) - .shiftedBy(this.config.decimals) - .plus(this.reserve.totalPrincipalStableDebt) - .toString(); - return this; - } - addUnbacked(amount: number | string) { this.reserve.unbacked = new BigNumber(amount) .shiftedBy(this.config.decimals) @@ -95,10 +83,7 @@ export class UserReserveMock { underlyingAsset: '0x0000000000000000000000000000000000000000', scaledATokenBalance: '0', usageAsCollateralEnabledOnUser: true, - stableBorrowRate: RAY.multipliedBy(2).toString(), scaledVariableDebt: '0', - principalStableDebt: '0', - stableBorrowLastUpdateTimestamp: 1, }; const reserveMock = new ReserveMock({ decimals: config.decimals }); this.reserve = { @@ -118,7 +103,6 @@ export class UserReserveMock { variableBorrowRate: RAY.multipliedBy(3).toString(), formattedAvailableLiquidity: '0', liquidityRate: RAY.multipliedBy(1).toString(), - totalPrincipalStableDebt: '0', totalScaledVariableDebt: '0', lastUpdateTimestamp: 1, debtCeiling: '0', @@ -132,7 +116,6 @@ export class UserReserveMock { availableLiquidityUSD: '0', totalDebtUSD: '0', totalVariableDebtUSD: '0', - totalStableDebtUSD: '0', borrowCapUSD: '0', supplyCapUSD: '0', unbackedUSD: '0', @@ -143,11 +126,8 @@ export class UserReserveMock { supplyAPR: '0', variableBorrowAPY: '0', variableBorrowAPR: '0', - stableBorrowAPY: '0', - stableBorrowAPR: '0', borrowUsageRatio: '0', supplyUsageRatio: '0', - totalStableDebt: '0', totalVariableDebt: '0', totalDebt: '0', totalLiquidity: '0', @@ -181,18 +161,6 @@ export class UserReserveMock { .toString(); return this; } - - stableBorrow(amount: number | string) { - this.userReserve.principalStableDebt = new BigNumber(amount) - .shiftedBy(this.config.decimals) - .plus(this.userReserve.principalStableDebt) - .toString(); - this.reserve.totalPrincipalStableDebt = new BigNumber(amount) - .shiftedBy(this.config.decimals) - .plus(this.reserve.totalPrincipalStableDebt) - .toString(); - return this; - } } export class ReserveIncentiveMock { @@ -241,26 +209,6 @@ export class ReserveIncentiveMock { }, ], }, - sIncentiveData: { - tokenAddress: '0x0000000000000000000000000000000000000000', - incentiveControllerAddress: - '0x0000000000000000000000000000000000000000', - rewardsTokenInformation: [ - { - rewardTokenSymbol: 'Test', - emissionPerSecond: '0', - incentivesLastUpdateTimestamp: 1, - tokenIncentivesIndex: '0', - emissionEndTimestamp: 2, - rewardTokenAddress: '0x0000000000000000000000000000000000000000', - rewardTokenDecimals: 18, - precision: 18, - rewardPriceFeed: '0', - priceFeedDecimals: 8, - rewardOracleAddress: '0x0000000000000000000000000000000000000000', - }, - ], - }, }; } } @@ -305,23 +253,6 @@ export class UserIncentiveMock { }, ], }, - sTokenIncentivesUserData: { - tokenAddress: '0x0000000000000000000000000000000000000000', - incentiveControllerAddress: - '0x0000000000000000000000000000000000000000', - userRewardsInformation: [ - { - tokenIncentivesUserIndex: '0', - userUnclaimedRewards: '1', - rewardTokenAddress: '0x0000000000000000000000000000000000000000', - rewardTokenDecimals: 18, - rewardPriceFeed: (10 ** 19).toString(), // 10 - priceFeedDecimals: 8, - rewardOracleAddress: '0x0', - rewardTokenSymbol: 'Test', - }, - ], - }, }; } }