Skip to content

Commit

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

* Add more hooks

* Rename marketId to synthMarketId and perpsMarketId

* Refactor: Simplify parameters in useDelegateCollateral
  • Loading branch information
vderunov authored Oct 1, 2024
1 parent b7f1e70 commit 64efd48
Show file tree
Hide file tree
Showing 26 changed files with 961 additions and 13 deletions.
40 changes: 40 additions & 0 deletions src/delegateCollateral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { ethers } from 'ethers';

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

const delegateCollateralTxnArgs = [
//
accountId,
poolId,
tokenAddress,
delegateAmount,
ethers.utils.parseEther('1'), // Leverage
];
console.log('delegateCollateralTxnArgs', delegateCollateralTxnArgs);

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

export async function delegateCollateralWithPriceUpdate({
provider,
walletAddress,
CoreProxyContract,
MulticallContract,
accountId,
poolId,
tokenAddress,
delegateAmount,
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;
delegateAmount: 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 delegateCollateralTxnArgs = [
//
accountId,
poolId,
tokenAddress,
delegateAmount,
ethers.utils.parseEther('1'), // Leverage
];
console.log('delegateCollateralTxnArgs', delegateCollateralTxnArgs);

const delegateCollateralTxn = {
target: CoreProxyContract.address,
callData: CoreProxyInterface.encodeFunctionData('delegateCollateral', [
//
...delegateCollateralTxnArgs,
]),
value: 0,
requireSuccess: true,
};
console.log({ delegateCollateralTxn });

const signer = provider.getSigner(walletAddress);

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

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

export async function fetchAccountAvailableCollateral({
provider,
CoreProxyContract,
accountId,
tokenAddress,
}: {
provider: ethers.providers.BaseProvider;
CoreProxyContract: { address: string; abi: string[] };
accountId: ethers.BigNumber;
tokenAddress: string;
}) {
const CoreProxy = new ethers.Contract(CoreProxyContract.address, CoreProxyContract.abi, provider);
console.time('fetchAccountAvailableCollateral');
const accountAvailableCollateral = await CoreProxy.getAccountAvailableCollateral(accountId, tokenAddress);
console.timeEnd('fetchAccountAvailableCollateral');
return accountAvailableCollateral;
}
2 changes: 1 addition & 1 deletion src/fetchPerpsCommitOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function fetchPerpsCommitOrder({
provider: ethers.providers.Web3Provider;
PerpsMarketProxyContract: { address: string; abi: string[] };
orderCommitmentArgs: {
marketId: string;
perpsMarketId: string;
accountId: ethers.BigNumber;
sizeDelta: ethers.BigNumber;
settlementStrategyId: string;
Expand Down
2 changes: 1 addition & 1 deletion src/fetchPerpsCommitOrderWithPriceUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export async function fetchPerpsCommitOrderWithPriceUpdate({
PerpsMarketProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
orderCommitmentArgs: {
marketId: string;
perpsMarketId: string;
accountId: ethers.BigNumber;
sizeDelta: ethers.BigNumber;
settlementStrategyId: string;
Expand Down
23 changes: 23 additions & 0 deletions src/fetchPerpsSettleOrder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ethers } from 'ethers';

export async function fetchPerpsSettleOrder({
provider,
walletAddress,
PerpsMarketProxyContract,
perpsAccountId,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
PerpsMarketProxyContract: { address: string; abi: string[] };
perpsAccountId: ethers.BigNumber;
}) {
const signer = provider.getSigner(walletAddress);
const PerpsMarketProxy = new ethers.Contract(PerpsMarketProxyContract.address, PerpsMarketProxyContract.abi, signer);

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

export async function fetchPerpsSettleOrderWithPriceUpdate({
provider,
walletAddress,
PerpsMarketProxyContract,
MulticallContract,
perpsAccountId,
priceUpdateTxn,
}: {
provider: ethers.providers.Web3Provider;
walletAddress?: string;
PerpsMarketProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
perpsAccountId: ethers.BigNumber;
priceUpdateTxn: {
target: string;
callData: string;
value: ethers.BigNumber;
requireSuccess: boolean;
};
}) {
const PerpsMarketPoxyInterface = new ethers.utils.Interface(PerpsMarketProxyContract.abi);
const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);

const settleOrderTxn = {
target: PerpsMarketProxyContract.address,
callData: PerpsMarketPoxyInterface.encodeFunctionData('settleOrder', [perpsAccountId]),
value: 0,
requireSuccess: true,
};
console.log({ settleOrderTxn });

const signer = provider.getSigner(walletAddress);

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

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

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

export async function fetchPositionCollateral({
provider,
CoreProxyContract,
accountId,
poolId,
tokenAddress,
}: {
provider: ethers.providers.BaseProvider;
CoreProxyContract: { address: string; abi: string[] };
accountId: ethers.BigNumber;
poolId: ethers.BigNumber;
tokenAddress: string;
}) {
const CoreProxy = new ethers.Contract(CoreProxyContract.address, CoreProxyContract.abi, provider);
const positionCollateral = await CoreProxy.getPositionCollateral(accountId, poolId, tokenAddress);
console.log({ positionCollateral });
return positionCollateral;
}
6 changes: 3 additions & 3 deletions src/fetchSpotSell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ export async function fetchSpotSell({
provider,
walletAddress,
SpotMarketProxyContract,
marketId,
synthMarketId,
amount,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
SpotMarketProxyContract: { address: string; abi: string[] };
marketId: string;
synthMarketId: 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);
const tx: ethers.ContractTransaction = await SpotMarketProxy.sell(synthMarketId, amount, amount, ethers.constants.AddressZero);
console.timeEnd('fetchSpotSell');
const txResult = await tx.wait();
console.log({ txResult });
Expand Down
6 changes: 3 additions & 3 deletions src/fetchSpotSellWithPriceUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ export async function fetchSpotSellWithPriceUpdate({
walletAddress,
SpotMarketProxyContract,
MulticallContract,
marketId,
synthMarketId,
amount,
priceUpdateTxn,
}: {
provider: ethers.providers.Web3Provider;
walletAddress: string;
SpotMarketProxyContract: { address: string; abi: string[] };
MulticallContract: { address: string; abi: string[] };
marketId: string;
synthMarketId: string;
amount: ethers.BigNumber;
priceUpdateTxn: {
target: string;
Expand All @@ -25,7 +25,7 @@ export async function fetchSpotSellWithPriceUpdate({
const SpotMarketProxyInterface = new ethers.utils.Interface(SpotMarketProxyContract.abi);
const MulticallInterface = new ethers.utils.Interface(MulticallContract.abi);

const sellArgs = [marketId, amount, amount, ethers.constants.AddressZero];
const sellArgs = [synthMarketId, amount, amount, ethers.constants.AddressZero];

console.log({ sellArgs });

Expand Down
33 changes: 33 additions & 0 deletions src/fetchStrictPriceUpdateTxn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { ethers } from 'ethers';
import { getPythVaa } from './getPythVaa';

export async function fetchStrictPriceUpdateTxn({
commitmentTime,
commitmentPriceDelay,
PythERC7412WrapperContract,
feedId,
}: {
commitmentTime: ethers.BigNumber;
commitmentPriceDelay: ethers.BigNumber;
PythERC7412WrapperContract: { address: string; abi: string[] };
feedId: string;
}) {
console.time('fetchStrictPriceUpdateTxn');
const PythERC7412WrapperInterface = new ethers.utils.Interface(PythERC7412WrapperContract.abi);
const timestamp = commitmentTime.add(commitmentPriceDelay);
const offchainData = await getPythVaa({ pythPriceFeedId: feedId, timestamp: timestamp.toNumber() });
const updateType = 2;
const offchainDataEncoded = ethers.utils.defaultAbiCoder.encode(
['uint8', 'uint64', 'bytes32[]', 'bytes[]'],
[updateType, timestamp, [feedId], [offchainData]]
);
console.timeEnd('fetchStrictPriceUpdateTxn');
const priceUpdateTxn = {
target: PythERC7412WrapperContract.address,
callData: PythERC7412WrapperInterface.encodeFunctionData('fulfillOracleQuery', [offchainDataEncoded]),
value: ethers.BigNumber.from(1),
requireSuccess: true,
};
console.log({ priceUpdateTxn });
return priceUpdateTxn;
}
15 changes: 15 additions & 0 deletions src/getPythVaa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { EvmPriceServiceConnection } from '@pythnetwork/pyth-evm-js';

const PYTH_MAINNET_ENDPOINT = process.env.PYTH_MAINNET_ENDPOINT || 'https://hermes.pyth.network';

const priceService = new EvmPriceServiceConnection(PYTH_MAINNET_ENDPOINT);

function base64ToHex(str: string) {
const raw = Buffer.from(str, 'base64');
return `0x${raw.toString('hex')}`;
}

export async function getPythVaa({ pythPriceFeedId, timestamp }: { pythPriceFeedId: string; timestamp: number }) {
const [priceUpdateData] = await priceService.getVaa(pythPriceFeedId, timestamp);
return base64ToHex(priceUpdateData);
}
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,15 @@ export * from './fetchApproveToken';
export * from './useSpotGetSettlementStrategy';
export * from './useSpotSell';
export * from './useSpotGetPriceData';
export * from './usePerpsGetCollateralAmount';
export * from './usePerpsGetOrder';
export * from './usePositionCollateral';
export * from './useDelegateCollateral';
export * from './useSelectedPoolId';
export * from './fetchAccountAvailableCollateral';
export * from './useAccounts';
export * from './useSelectedAccountId';
export * from './usePerpsCreateAccount';
export * from './usePerpsGetOpenPosition';
export * from './usePerpsGetSettlementStrategy';
export * from './usePerpsSettleOrder';
34 changes: 34 additions & 0 deletions src/useAccounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useQuery } from '@tanstack/react-query';
import { ethers } from 'ethers';
import { useErrorParser } from './useErrorParser';
import { useImportContract } from './useImports';
import { useSynthetix } from './useSynthetix';

export function useAccounts({ provider, walletAddress }: { walletAddress?: string; provider?: ethers.providers.BaseProvider }) {
const { chainId } = useSynthetix();
const errorParser = useErrorParser();
const { data: AccountProxyContract } = useImportContract('AccountProxy');

return useQuery<ethers.BigNumber[]>({
enabled: Boolean(chainId && AccountProxyContract?.address && walletAddress && provider),
queryKey: [chainId, 'Accounts', { AccountProxy: AccountProxyContract?.address }, { ownerAddress: walletAddress }],
queryFn: async () => {
if (!(chainId && AccountProxyContract?.address && walletAddress && provider)) throw 'OMFG';
const AccountProxy = new ethers.Contract(AccountProxyContract.address, AccountProxyContract.abi, provider);
const numberOfAccountTokens = await AccountProxy.balanceOf(walletAddress);
if (numberOfAccountTokens.eq(0)) {
// No accounts created yet
return [];
}
const accountIndexes = Array.from(Array(numberOfAccountTokens.toNumber()).keys());
const accounts = await Promise.all(accountIndexes.map((i) => AccountProxy.tokenOfOwnerByIndex(walletAddress, i)));
return accounts;
},
select: (accounts) => accounts.map((accountId) => ethers.BigNumber.from(accountId)),
throwOnError: (error) => {
// TODO: show toast
errorParser(error);
return false;
},
});
}
Loading

0 comments on commit 64efd48

Please sign in to comment.