Skip to content

Commit

Permalink
add pyth feature
Browse files Browse the repository at this point in the history
  • Loading branch information
xieqian committed Feb 28, 2024
1 parent e4ee4bc commit 9ac921f
Show file tree
Hide file tree
Showing 12 changed files with 413 additions and 97 deletions.
9 changes: 6 additions & 3 deletions components/Modal/Action.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { borrow } from "../../store/actions/borrow";
import { withdraw } from "../../store/actions/withdraw";
import { adjustCollateral } from "../../store/actions/adjustCollateral";
import { useAppSelector, useAppDispatch } from "../../redux/hooks";
import { getSelectedValues, getAssetData } from "../../redux/appSelectors";
import { getSelectedValues, getAssetData, getConfig } from "../../redux/appSelectors";
import { trackActionButton, trackUseAsCollateral } from "../../utils/telemetry";
import { useDegenMode } from "../../hooks/hooks";
import { SubmitButton, AlertWarning } from "./components";
Expand All @@ -20,6 +20,7 @@ import { expandToken } from "../../store";
export default function Action({ maxBorrowAmount, healthFactor, poolAsset }) {
const [loading, setLoading] = useState(false);
const { amount, useAsCollateral, isMax } = useAppSelector(getSelectedValues);
const { enable_pyth_oracle } = useAppSelector(getConfig);
const dispatch = useAppDispatch();
const asset = useAppSelector(getAssetData);
const { action = "Deposit", tokenId, borrowApy, price, borrowed } = asset;
Expand Down Expand Up @@ -67,7 +68,7 @@ export default function Action({ maxBorrowAmount, healthFactor, poolAsset }) {
}
break;
case "Borrow": {
await borrow({ tokenId, extraDecimals, amount });
await borrow({ tokenId, extraDecimals, amount, enable_pyth_oracle });
break;
}
case "Withdraw": {
Expand All @@ -76,6 +77,7 @@ export default function Action({ maxBorrowAmount, healthFactor, poolAsset }) {
extraDecimals,
amount,
isMax,
enable_pyth_oracle,
});
break;
}
Expand All @@ -85,10 +87,10 @@ export default function Action({ maxBorrowAmount, healthFactor, poolAsset }) {
extraDecimals,
amount,
isMax,
enable_pyth_oracle,
});
break;
case "Repay": {
// TODO
let minRepay = "0";
let interestChargedIn1min = "0";
if (borrowApy && price && borrowed) {
Expand Down Expand Up @@ -117,6 +119,7 @@ export default function Action({ maxBorrowAmount, healthFactor, poolAsset }) {
amount,
extraDecimals,
isMax,
enable_pyth_oracle,
});
} else {
await repay({
Expand Down
6 changes: 5 additions & 1 deletion interfaces/burrow.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Account, Contract } from "near-api-js";
import type { WalletSelector } from "@near-wallet-selector/core";

import { IPrices } from "./oracle";
import { IPrices, IPythPrice } from "./oracle";
import { IMetadata, AssetEntry, IAssetDetailed, Balance, NetTvlFarm } from "./asset";
import { IAccount, IAccountDetailed } from "./account";

Expand All @@ -17,6 +17,8 @@ export interface IConfig {
oracle_account_id: string;
owner_id: string;
x_booster_multiplier_at_maximum_staking_duration: number;
enable_price_oracle: boolean;
enable_pyth_oracle: boolean;
}

export interface IBurrow {
Expand All @@ -29,13 +31,15 @@ export interface IBurrow {
signIn: () => void;
logicContract: Contract;
oracleContract: Contract;
pythContract: Contract;
config: IConfig;
view: (
contract: Contract,
methodName: string,
args?: any,
) => Promise<
| IPrices
| IPythPrice
| IMetadata
| AssetEntry[]
| IAssetDetailed
Expand Down
10 changes: 10 additions & 0 deletions interfaces/contract-methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ export enum ViewMethodsLogic {
get_asset_farms_paged,
storage_balance_of,
check_registration,
get_all_token_pyth_infos,
}

// Change methods can modify the state. But you don't receive the returned value when called.
export enum ChangeMethodsLogic {
// init
new,
execute,
execute_with_pyth,
// register
storage_deposit,
// config
Expand Down Expand Up @@ -58,10 +60,18 @@ export enum ViewMethodsToken {
ft_balance_of,
storage_balance_of,
check_registration,
get_st_near_price,
get_nearx_price,
ft_price,
}

export enum ChangeMethodsToken {
ft_transfer_call,
storage_deposit,
register_account,
}
export enum ViewMethodsPyth {
get_price,
}

export enum ChangeMethodsPyth {}
8 changes: 7 additions & 1 deletion interfaces/oracle.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface IPrice {
decimals: number;
multiplier: string;
usd: number;
usd?: number;
}

export interface IAssetPrice {
Expand All @@ -14,3 +14,9 @@ export interface IPrices {
recency_duration_sec: number;
timestamp: string;
}
export interface IPythPrice {
price: string;
conf: string;
expo: number;
publish_time: number;
}
57 changes: 28 additions & 29 deletions store/actions/adjustCollateral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ export async function adjustCollateral({
extraDecimals,
amount,
isMax,
enable_pyth_oracle,
}: {
tokenId: string;
extraDecimals: number;
amount: string;
isMax: boolean;
enable_pyth_oracle: boolean;
}) {
const { oracleContract, logicContract, account, call } = await getBurrow();
const { decimals } = (await getMetadata(tokenId))!;
Expand All @@ -38,22 +40,14 @@ export async function adjustCollateral({
: decimalMin(totalBalance, expandTokenDecimal(amount, decimals + extraDecimals));

if (expandedAmount.gt(collateralBalance)) {
// await call(logicContract, ChangeMethodsLogic[ChangeMethodsLogic.execute], {
// actions: [
// {
// IncreaseCollateral: {
// token_id: tokenId,
// max_amount: !isMax ? expandedAmount.sub(collateralBalance).toFixed(0) : undefined,
// },
// },
// ],
// });
await prepareAndExecuteTransactions([
{
receiverId: logicContract.contractId,
functionCalls: [
{
methodName: ChangeMethodsLogic[ChangeMethodsLogic.execute],
methodName: enable_pyth_oracle
? ChangeMethodsLogic[ChangeMethodsLogic.execute_with_pyth]
: ChangeMethodsLogic[ChangeMethodsLogic.execute],
gas: new BN("100000000000000"),
args: {
actions: [
Expand All @@ -72,30 +66,35 @@ export async function adjustCollateral({
} as Transaction,
]);
} else if (expandedAmount.lt(collateralBalance)) {
const decreaseCollateralTemplate = {
DecreaseCollateral: {
token_id: tokenId,
max_amount: expandedAmount.gt(0)
? collateralBalance.sub(expandedAmount).toFixed(0)
: undefined,
},
};
await prepareAndExecuteTransactions([
{
receiverId: oracleContract.contractId,
receiverId: enable_pyth_oracle ? logicContract.contractId : oracleContract.contractId,
functionCalls: [
{
methodName: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
gas: new BN("100000000000000"),
args: {
receiver_id: logicContract.contractId,
msg: JSON.stringify({
Execute: {
actions: [
{
DecreaseCollateral: {
token_id: tokenId,
max_amount: expandedAmount.gt(0)
? collateralBalance.sub(expandedAmount).toFixed(0)
: undefined,
},
methodName: enable_pyth_oracle
? ChangeMethodsLogic[ChangeMethodsLogic.execute_with_pyth]
: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
gas: new BN("300000000000000"),
args: enable_pyth_oracle
? {
actions: [decreaseCollateralTemplate],
}
: {
receiver_id: logicContract.contractId,
msg: JSON.stringify({
Execute: {
actions: [decreaseCollateralTemplate],
},
],
}),
},
}),
},
},
],
} as Transaction,
Expand Down
29 changes: 21 additions & 8 deletions store/actions/borrow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import BN from "bn.js";

import { getBurrow, nearTokenId } from "../../utils";
import { expandToken, expandTokenDecimal } from "../helper";
import { ChangeMethodsNearToken, ChangeMethodsOracle, ChangeMethodsToken } from "../../interfaces";
import {
ChangeMethodsNearToken,
ChangeMethodsOracle,
ChangeMethodsToken,
ChangeMethodsLogic,
} from "../../interfaces";
import { Transaction, isRegistered, isRegisteredNew } from "../wallet";
import { prepareAndExecuteTransactions, getMetadata, getTokenContract } from "../tokens";
import { NEAR_DECIMALS, NO_STORAGE_DEPOSIT_CONTRACTS, NEAR_STORAGE_DEPOSIT } from "../constants";
Expand All @@ -13,10 +18,12 @@ export async function borrow({
tokenId,
extraDecimals,
amount,
enable_pyth_oracle,
}: {
tokenId: string;
extraDecimals: number;
amount: string;
enable_pyth_oracle: boolean;
}) {
const { oracleContract, logicContract, account } = await getBurrow();
const { decimals } = (await getMetadata(tokenId))!;
Expand Down Expand Up @@ -90,15 +97,21 @@ export async function borrow({
};

transactions.push({
receiverId: oracleContract.contractId,
receiverId: enable_pyth_oracle ? logicContract.contractId : oracleContract.contractId,
functionCalls: [
{
methodName: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
gas: new BN("100000000000000"),
args: {
receiver_id: logicContract.contractId,
msg: JSON.stringify(borrowTemplate),
},
methodName: enable_pyth_oracle
? ChangeMethodsLogic[ChangeMethodsLogic.execute_with_pyth]
: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
gas: new BN("300000000000000"),
args: enable_pyth_oracle
? {
actions: borrowTemplate.Execute.actions,
}
: {
receiver_id: logicContract.contractId,
msg: JSON.stringify(borrowTemplate),
},
},
],
});
Expand Down
62 changes: 34 additions & 28 deletions store/actions/repayFromDeposits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Decimal from "decimal.js";

import { decimalMax, getBurrow } from "../../utils";
import { expandTokenDecimal } from "../helper";
import { ChangeMethodsOracle } from "../../interfaces";
import { ChangeMethodsOracle, ChangeMethodsLogic } from "../../interfaces";
import { getMetadata, prepareAndExecuteTransactions } from "../tokens";
import { Transaction } from "../wallet";
import { transformAccount } from "../../transformers/account";
Expand All @@ -13,11 +13,13 @@ export async function repayFromDeposits({
amount,
extraDecimals,
isMax,
enable_pyth_oracle,
}: {
tokenId: string;
amount: string;
extraDecimals: number;
isMax: boolean;
enable_pyth_oracle: boolean;
}) {
const { logicContract, oracleContract } = await getBurrow();
const { decimals } = (await getMetadata(tokenId))!;
Expand All @@ -34,39 +36,43 @@ export async function repayFromDeposits({
);

const transactions: Transaction[] = [];

const repayTemplate = {
Repay: {
token_id: tokenId,
amount: isMax ? undefined : expandedAmount.mul(extraDecimalMultiplier).toFixed(0),
},
};
const decreaseCollateralTemplate = {
DecreaseCollateral: {
token_id: tokenId,
amount: decreaseCollateralAmount.toFixed(0),
},
};
transactions.push({
receiverId: oracleContract.contractId,
receiverId: enable_pyth_oracle ? logicContract.contractId : oracleContract.contractId,
functionCalls: [
{
methodName: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
args: {
receiver_id: logicContract.contractId,
msg: JSON.stringify({
Execute: {
methodName: enable_pyth_oracle
? ChangeMethodsLogic[ChangeMethodsLogic.execute_with_pyth]
: ChangeMethodsOracle[ChangeMethodsOracle.oracle_call],
args: enable_pyth_oracle
? {
actions: [
...(decreaseCollateralAmount.gt(0)
? [
{
DecreaseCollateral: {
token_id: tokenId,
amount: decreaseCollateralAmount.toFixed(0),
},
},
]
: []),
{
Repay: {
token_id: tokenId,
amount: isMax
? undefined
: expandedAmount.mul(extraDecimalMultiplier).toFixed(0),
},
},
...(decreaseCollateralAmount.gt(0) ? [decreaseCollateralTemplate] : []),
repayTemplate,
],
}
: {
receiver_id: logicContract.contractId,
msg: JSON.stringify({
Execute: {
actions: [
...(decreaseCollateralAmount.gt(0) ? [decreaseCollateralTemplate] : []),
repayTemplate,
],
},
}),
},
}),
},
},
],
});
Expand Down
Loading

0 comments on commit 9ac921f

Please sign in to comment.