Skip to content

Commit

Permalink
Add hooks (#2)
Browse files Browse the repository at this point in the history
* Add useMarkets

* Rename useMarkets to usePerpsGetMarkets

* Add error handling and timing to usePerpsGetMarkets

* Add usePerpsGetMarketSummary (#2)

* Add useGetMarketSummary

* Rename market summary functions to include "Perps"

* Update return types in perps market summary functions

* Rename marketId to perpsMarketId for clarity

* Add logging and error handling improvements

* Add usePerpsMetadata (#3)

* Add usePerpsMetadata

* Rename parameter marketId to perpsMarketId.

* Add error handling with errorParser in usePerpsMetadata

* Add usePerpsAccounts (#4)

* Add usePerpsAccounts

* Add error handling with useErrorParser in usePerpsAccounts

* Add useMintUsd (#5)

* Add useMintUsd

* Remove CollateralType

* Add detailed logging and error handling

* Add useWethDeposit (#6)

* Add usePerpsDeposit

* Add WETH contract support and rename PerpsDeposit

* Add WETH contract addresses

* Add functions for handling Perps commit orders

* Refactor mutations and queries, add collateral utilities

* Integrate price feed hook and add token utilities

* Remove priceIds from usePerpsGetMarketSummary

* Replace useAllPriceFeeds with usePriceUpdateTxn

* Invalidate queries without slicing price IDs
  • Loading branch information
vderunov authored Sep 30, 2024
1 parent efe1078 commit 1de1c70
Show file tree
Hide file tree
Showing 34 changed files with 1,425 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/fetchApproveToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ethers } from 'ethers';

export async function fetchApproveToken({
provider,
walletAddress,
tokenAddress,
spenderAddress,
allowance,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
tokenAddress: string;
spenderAddress: string;
allowance: ethers.BigNumber;
}) {
const signer = provider.getSigner(walletAddress);
const Token = new ethers.Contract(tokenAddress, ['function approve(address spender, uint256 amount) returns (bool)'], signer);
const tx: ethers.ContractTransaction = await Token.approve(spenderAddress, allowance);
console.log({ tx });
const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
39 changes: 39 additions & 0 deletions src/fetchMintUsd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ethers } from 'ethers';

export async function fetchMintUsd({
provider,
walletAddress,
CoreProxyContract,
accountId,
poolId,
tokenAddress,
mintUsdAmount,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
CoreProxyContract: { address: string; abi: string[] };
accountId: ethers.BigNumber;
poolId: ethers.BigNumber;
tokenAddress: string;
mintUsdAmount: ethers.BigNumber;
}) {
const signer = provider.getSigner(walletAddress);

const CoreProxy = new ethers.Contract(CoreProxyContract.address, CoreProxyContract.abi, signer);
const mintUsdTxnArgs = [
//
accountId,
poolId,
tokenAddress,
mintUsdAmount,
];
console.log('mintUsdTxnArgs', mintUsdTxnArgs);

console.time('mintUsd');
const tx: ethers.ContractTransaction = await CoreProxy.mintUsd(...mintUsdTxnArgs);
console.timeEnd('mintUsd');
console.log({ tx });
const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
64 changes: 64 additions & 0 deletions src/fetchMintUsdWithPriceUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { ethers } from 'ethers';

export async function fetchMintUsdWithPriceUpdate({
provider,
walletAddress,
CoreProxyContract,
MulticallContract,
accountId,
poolId,
tokenAddress,
mintUsdAmount,
priceUpdateTxn,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
CoreProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
accountId: ethers.BigNumber;
poolId: ethers.BigNumber;
tokenAddress: string;
mintUsdAmount: ethers.BigNumber;
priceUpdateTxn: {
target: string;
callData: string;
value: number;
requireSuccess: boolean;
};
}) {
const CoreProxyInterface = new ethers.utils.Interface(CoreProxyContract.abi);
const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);

const mintUsdTxnArgs = [
//
accountId,
poolId,
tokenAddress,
mintUsdAmount,
];
console.log({ mintUsdTxnArgs });

const mintUsdTxn = {
target: CoreProxyContract.address,
callData: CoreProxyInterface.encodeFunctionData('mintUsd', [...mintUsdTxnArgs]),
value: 0,
requireSuccess: true,
};
console.log({ mintUsdTxn });

const signer = provider.getSigner(walletAddress);
const multicallTxn = {
from: walletAddress,
to: MulticallContract.address,
data: MulticallInterface.encodeFunctionData('aggregate3Value', [[priceUpdateTxn, mintUsdTxn]]),
value: priceUpdateTxn.value,
};
console.log({ multicallTxn });

console.time('mintUsd');
const tx: ethers.ContractTransaction = await signer.sendTransaction(multicallTxn);
console.timeEnd('mintUsd');
const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
31 changes: 31 additions & 0 deletions src/fetchPerpsCommitOrder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ethers } from 'ethers';

export async function fetchPerpsCommitOrder({
walletAddress,
provider,
PerpsMarketProxyContract,
orderCommitmentArgs,
}: {
walletAddress?: string;
provider: ethers.providers.Web3Provider;
PerpsMarketProxyContract: { address: string; abi: string[] };
orderCommitmentArgs: {
marketId: string;
accountId: ethers.BigNumber;
sizeDelta: ethers.BigNumber;
settlementStrategyId: string;
acceptablePrice: ethers.BigNumber;
referrer: string;
trackingCode: string;
};
}) {
const signer = provider.getSigner(walletAddress);
const PerpsMarketProxy = new ethers.Contract(PerpsMarketProxyContract.address, PerpsMarketProxyContract.abi, signer);

console.time('fetchPerpsCommitOrder');
const tx: ethers.ContractTransaction = await PerpsMarketProxy.commitOrder(orderCommitmentArgs);
console.timeEnd('fetchPerpsCommitOrder');
const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
58 changes: 58 additions & 0 deletions src/fetchPerpsCommitOrderWithPriceUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { ethers } from 'ethers';

export async function fetchPerpsCommitOrderWithPriceUpdate({
walletAddress,
provider,
PerpsMarketProxyContract,
MulticallContract,
orderCommitmentArgs,
priceUpdateTxn,
}: {
walletAddress?: string;
provider: ethers.providers.Web3Provider;
PerpsMarketProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
orderCommitmentArgs: {
marketId: string;
accountId: ethers.BigNumber;
sizeDelta: ethers.BigNumber;
settlementStrategyId: string;
acceptablePrice: ethers.BigNumber;
referrer: string;
trackingCode: string;
};
priceUpdateTxn: {
target: string;
callData: string;
value: number;
requireSuccess: boolean;
};
}) {
const PerpsMarketPoxyInterface = new ethers.utils.Interface(PerpsMarketProxyContract.abi);
const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);

const commitOrderTxn = {
target: PerpsMarketProxyContract.address,
callData: PerpsMarketPoxyInterface.encodeFunctionData('commitOrder', [orderCommitmentArgs]),
value: 0,
requireSuccess: true,
};
console.log({ commitOrderTxn });
const signer = provider.getSigner(walletAddress);

const multicallTxn = {
from: walletAddress,
to: MulticallContract.address,
data: MulticallInterface.encodeFunctionData('aggregate3Value', [[priceUpdateTxn, commitOrderTxn]]),
value: priceUpdateTxn.value,
};
console.log({ multicallTxn });

console.time('fetchPerpsCommitOrderWithPriceUpdate');
const tx: ethers.ContractTransaction = await signer.sendTransaction(multicallTxn);
console.timeEnd('fetchPerpsCommitOrderWithPriceUpdate');

const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
18 changes: 18 additions & 0 deletions src/fetchPerpsGetAvailableMargin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ethers } from 'ethers';

export async function fetchPerpsGetAvailableMargin({
provider,
perpsAccountId,
PerpsMarketProxyContract,
}: {
provider?: ethers.providers.BaseProvider;
perpsAccountId: ethers.BigNumber;
PerpsMarketProxyContract: { address: string; abi: string[] };
}) {
const PerpsMarketProxy = new ethers.Contract(PerpsMarketProxyContract.address, PerpsMarketProxyContract.abi, provider);
console.time('fetchPerpsGetAvailableMargin');
const availableMargin = await PerpsMarketProxy.getAvailableMargin(perpsAccountId);
console.timeEnd('fetchPerpsGetAvailableMargin');
console.log({ availableMargin });
return availableMargin;
}
23 changes: 23 additions & 0 deletions src/fetchPerpsGetMarketSummary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ethers } from 'ethers';

export async function fetchPerpsGetMarketSummary({
provider,
perpsMarketId,
PerpsMarketProxyContract,
}: {
provider: ethers.providers.BaseProvider;
perpsMarketId: ethers.BigNumber;
PerpsMarketProxyContract: { address: string; abi: string[] };
}): Promise<{
skew: ethers.BigNumber;
size: ethers.BigNumber;
maxOpenInterest: ethers.BigNumber;
currentFundingRate: ethers.BigNumber;
currentFundingVelocity: ethers.BigNumber;
indexPrice: ethers.BigNumber;
}> {
const PerpsMarketProxy = new ethers.Contract(PerpsMarketProxyContract.address, PerpsMarketProxyContract.abi, provider);
const marketSummary = await PerpsMarketProxy.getMarketSummary(perpsMarketId);
console.log({ marketSummary });
return marketSummary;
}
57 changes: 57 additions & 0 deletions src/fetchPerpsGetMarketSummaryWithPriceUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ethers } from 'ethers';

export async function fetchPerpsGetMarketSummaryWithPriceUpdate({
provider,
perpsMarketId,
PerpsMarketProxyContract,
MulticallContract,
priceUpdateTxn,
}: {
provider: ethers.providers.BaseProvider;
perpsMarketId: ethers.BigNumber;
PerpsMarketProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
priceUpdateTxn: {
target: string;
callData: string;
value: number;
requireSuccess: boolean;
};
}): Promise<{
skew: ethers.BigNumber;
size: ethers.BigNumber;
maxOpenInterest: ethers.BigNumber;
currentFundingRate: ethers.BigNumber;
currentFundingVelocity: ethers.BigNumber;
indexPrice: ethers.BigNumber;
}> {
const PerpsMarketProxyInterface = new ethers.utils.Interface(PerpsMarketProxyContract.abi);
const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);

const getMarketSummaryTxn = {
target: PerpsMarketProxyContract.address,
callData: PerpsMarketProxyInterface.encodeFunctionData('getMarketSummary', [perpsMarketId]),
value: 0,
requireSuccess: true,
};

const response = await provider.call({
to: MulticallContract.address,
data: MulticallInterface.encodeFunctionData('aggregate3Value', [[priceUpdateTxn, getMarketSummaryTxn]]),
value: priceUpdateTxn.value,
});

if (response) {
const decodedMulticall = MulticallInterface.decodeFunctionResult('aggregate3Value', response);
if (decodedMulticall?.returnData?.[1]?.returnData) {
const getMarketSummaryTxnData = decodedMulticall.returnData[1].returnData;
const marketSummary = PerpsMarketProxyInterface.decodeFunctionResult('getMarketSummary', getMarketSummaryTxnData);
console.log('>>>>> marketSummary', marketSummary);
return marketSummary[0];
}

console.error({ decodedMulticall });
throw new Error('Unexpected multicall response');
}
throw new Error('Empty multicall response');
}
18 changes: 18 additions & 0 deletions src/fetchPerpsTotalCollateralValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ethers } from 'ethers';

export async function fetchPerpsTotalCollateralValue({
provider,
PerpsMarketProxyContract,
perpsAccountId,
}: {
provider?: ethers.providers.BaseProvider;
PerpsMarketProxyContract: { address: string; abi: string[] };
perpsAccountId: ethers.BigNumber;
}) {
const PerpsMarketProxy = new ethers.Contract(PerpsMarketProxyContract.address, PerpsMarketProxyContract.abi, provider);
console.time('fetchPerpsTotalCollateralValue');
const totalCollateralValue = await PerpsMarketProxy.totalCollateralValue(perpsAccountId);
console.timeEnd('fetchPerpsTotalCollateralValue');
console.log({ totalCollateralValue });
return totalCollateralValue;
}
5 changes: 4 additions & 1 deletion src/fetchPriceUpdateTxn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ export async function fetchPriceUpdateTxn({
MulticallContract,
PythERC7412WrapperContract,
priceIds,
stalenessTolerance: stalenessToleranceFromSpotPriceData,
}: {
provider: ethers.providers.BaseProvider;
MulticallContract: { address: string; abi: string[] };
PythERC7412WrapperContract: { address: string; abi: string[] };
priceIds: string[];
stalenessTolerance?: ethers.BigNumber;
}) {
console.time('fetchPriceUpdateTxn');
const stalenessTolerance = 1800; // half of 3600 required tolerance
const defaultStalenessTolerance = 1800; // half of 3600 required tolerance
const stalenessTolerance = stalenessToleranceFromSpotPriceData || defaultStalenessTolerance;

const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);
const PythERC7412WrapperInterface = new ethers.utils.Interface(PythERC7412WrapperContract.abi);
Expand Down
25 changes: 25 additions & 0 deletions src/fetchSpotSell.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ethers } from 'ethers';

export async function fetchSpotSell({
provider,
walletAddress,
SpotMarketProxyContract,
marketId,
amount,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
SpotMarketProxyContract: { address: string; abi: string[] };
marketId: string;
amount: ethers.BigNumber;
}) {
const signer = provider.getSigner(walletAddress);
const SpotMarketProxy = new ethers.Contract(SpotMarketProxyContract.address, SpotMarketProxyContract.abi, signer);

console.time('fetchSpotSell');
const tx: ethers.ContractTransaction = await SpotMarketProxy.sell(marketId, amount, amount, ethers.constants.AddressZero);
console.timeEnd('fetchSpotSell');
const txResult = await tx.wait();
console.log({ txResult });
return txResult;
}
Loading

0 comments on commit 1de1c70

Please sign in to comment.