Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use direct BN with better typing bby #231

Merged
merged 1 commit into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
TwapObservation
} from "@/types/prices";
import { TransactionProcessingUpdate } from "@/types/transactions";
import { BN } from "@coral-xyz/anchor";
import BN from "bn.js";
import {
CreateProposalInstruction,
ProposalOnChainFields,
Expand Down
18 changes: 12 additions & 6 deletions lib/client/indexer/dao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
dao_details_bool_exp
} from "./__generated__";
import { PublicKey } from "@solana/web3.js";
import BN from "bn.js";

export class FutarchyIndexerDaoClient implements FutarchyDaoClient {
private protocolMap: Map<string, FutarchyProtocol>;
Expand Down Expand Up @@ -234,12 +235,17 @@ export class FutarchyIndexerDaoClient implements FutarchyDaoClient {
: undefined,
proposalCount: d.proposals_aggregate.aggregate?.count,
passThresholdBps: d.pass_threshold_bps,
slotsPerProposal: d.slots_per_proposal,
twapInitialObservation: d.twap_initial_observation,
twapMaxObservationChangePerUpdate:
d.twap_max_observation_change_per_update,
minBaseFutarchicLiquidity: d.min_base_futarchic_liquidity,
minQuoteFutarchicLiquidity: d.min_quote_futarchic_liquidity
slotsPerProposal: new BN(d.slots_per_proposal ?? 0),
twapInitialObservation: new BN(d.twap_initial_observation ?? 0),
twapMaxObservationChangePerUpdate: new BN(
d.twap_max_observation_change_per_update ?? 0
),
minBaseFutarchicLiquidity: new BN(
d.min_base_futarchic_liquidity ?? 0
),
minQuoteFutarchicLiquidity: new BN(
d.min_quote_futarchic_liquidity ?? 0
)
},
publicKey: new PublicKey(d.dao_acct),
protocol: this.protocolMap.get(d.program_acct)
Expand Down
46 changes: 4 additions & 42 deletions lib/client/indexer/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
import { Client as GQLWebSocketClient } from "graphql-ws";
import { FutarchyMarketsRPCClient } from "../rpc/markets";
import { PriceMath } from "@metadaoproject/futarchy";
import { BN } from "@coral-xyz/anchor";
import BN from "bn.js";

export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
public openbook: FutarchyIndexerOpenbookMarketsClient;
Expand Down Expand Up @@ -135,10 +135,7 @@ export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
return market;
}

watchCurrentTwapPrice(
marketKey: PublicKey,
includeOracleData?: boolean
): Observable<TwapObservation[]> {
watchCurrentTwapPrice(marketKey: PublicKey): Observable<TwapObservation[]> {
const queryForGenerate = {
twap_chart_data: {
__args: {
Expand Down Expand Up @@ -166,26 +163,6 @@ export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
twaps: undefined as any
};

if (includeOracleData) {
queryForGenerate.twaps = {
__args: {
where: {
market_acct: { _eq: marketKey.toString() }
},
order_by: [
{
created_at: "desc" as order_by
}
],
limit: 1
},
last_observation: true,
last_price: true,
observation_agg: true,
updated_slot: true
};
}

const { query, variables } = generateSubscriptionOp(queryForGenerate);

return new Observable((subscriber) => {
Expand All @@ -204,20 +181,12 @@ export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
};
};
}[];
twaps: {
last_observation: number;
last_price: number;
observation_agg: number;
updated_slot: number;
}[];
}>(
{ query, variables },
{
next: ({ data }) => {
const twaps = data?.twaps;
const twapObservations =
data?.twap_chart_data?.map<TwapObservation>((d, i) => {
const latestTwaps = twaps?.[i];
return {
priceUi: PriceMath.getHumanPrice(
new BN(d.token_amount),
Expand All @@ -226,14 +195,7 @@ export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
),
priceRaw: d.token_amount,
createdAt: new Date(d.interv),
oracleData: latestTwaps
? {
lastObservation: latestTwaps.last_observation,
lastPrice: latestTwaps.last_price,
observationAgg: latestTwaps.observation_agg,
updatedSlot: latestTwaps.updated_slot
}
: null
oracleData: null
};
});
subscriber.next(twapObservations);
Expand Down Expand Up @@ -377,7 +339,7 @@ export class FutarchyIndexerMarketsClient implements FutarchyMarketsClient {
const twapObservations =
data.data?.twap_chart_data_stream?.map<TwapObservation>((d) => ({
priceUi: PriceMath.getHumanPrice(
new BN(d.token_amount),
new BN(d.token_amount ?? 0),
d.market?.tokenByBaseMintAcct.decimals!!,
d.market?.tokenByQuoteMintAcct.decimals!!
),
Expand Down
6 changes: 3 additions & 3 deletions lib/client/indexer/proposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
ProposalDetails,
ProposalInputs
} from "@/types/createProp";
import { BN } from "@coral-xyz/anchor";
import BN from "bn.js";
import { PriceMath } from "@metadaoproject/futarchy";
import { Observable } from "rxjs";
import { Client as GQLWebSocketClient } from "graphql-ws";
Expand Down Expand Up @@ -452,7 +452,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
prev +
PriceMath.getHumanAmount(
new BN(curr.filled_base_amount),
new BN(proposal.dao.tokenByBaseAcct?.decimals ?? 6)
proposal.dao.tokenByBaseAcct?.decimals ?? 6
) *
curr.quote_price,
0
Expand All @@ -463,7 +463,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
prev +
PriceMath.getHumanAmount(
new BN(curr.filled_base_amount),
new BN(proposal.dao.tokenByBaseAcct?.decimals ?? 6)
proposal.dao.tokenByBaseAcct?.decimals ?? 6
) *
curr.quote_price,
0
Expand Down
14 changes: 7 additions & 7 deletions lib/client/rpc/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import {
getAssociatedTokenAddressSync
} from "@solana/spl-token";
import {
Dao,
DaoAggregate,
FutarchyProtocol,
TokenProps,
TokenWithBalance,
TokenWithBalancePDAAndProposal,
Expand All @@ -14,8 +12,9 @@ import {
import { FutarchyBalancesClient } from "@/client";
import { PublicKey } from "@solana/web3.js";
import { Proposal } from "@/types/proposals";
import { BN, Provider } from "@coral-xyz/anchor";
import { Provider } from "@coral-xyz/anchor";
import { Observable, retry } from "rxjs";
import BN from "bn.js";

const PASS_USDC_URL =
"https://imagedelivery.net/HYEnlujCFMCgj6yA728xIw/f38677ab-8ec6-4706-6606-7d4e0a3cfc00/public";
Expand Down Expand Up @@ -155,11 +154,12 @@ export class FutarchyRPCBalancesClient implements FutarchyBalancesClient {
tokenWithPDA.pda,
(accountInfo) => {
const accountData = AccountLayout.decode(accountInfo.data);
const dividedTokenAmount =
new BN(accountData.amount) /
new BN(10).pow(new BN(tokenWithPDA.token.decimals));
const dividedTokenAmount = new BN(Number(accountData.amount)).div(
new BN(10).pow(new BN(tokenWithPDA.token.decimals))
);
// this is bugged if value is decimal/between 0 and 1
const tokenVal: TokenWithBalance = {
balance: dividedTokenAmount,
balance: dividedTokenAmount.toNumber(),
token: tokenWithPDA.token
};
subscriber.next(tokenVal);
Expand Down
5 changes: 3 additions & 2 deletions lib/client/rpc/dao.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BN, Program, Provider } from "@coral-xyz/anchor";
import { Program, Provider } from "@coral-xyz/anchor";
import {
AutocratProgram,
FutarchyProtocol,
Expand All @@ -13,6 +13,7 @@ import { PublicKey } from "@solana/web3.js";
import { createSlug } from "@/utils";
import { Autocrat, IDL as AUTOCRAT_V0_3_IDL } from "@/idl/autocrat_v0.3";
import { AUTOCRAT_PROGRAM_ID } from "@metadaoproject/futarchy";
import BN from "bn.js";

export class FutarchyRPCDaoClient implements FutarchyDaoClient {
private futarchyProtocols: FutarchyProtocol[];
Expand Down Expand Up @@ -118,7 +119,7 @@ export class FutarchyRPCDaoClient implements FutarchyDaoClient {
const slotsPerProposal: BN =
protocol.deploymentVersion === "V0"
? new BN(2160000)
: daoAccount.slotsPerProposal;
: daoAccount.slotsPerProposal ?? new BN(2160000);
const quoteMint = daoAccount.usdcMint;
if (baseMint) {
const baseToken = await enrichTokenMetadata(baseMint, this.rpcProvider);
Expand Down
33 changes: 17 additions & 16 deletions lib/client/rpc/market-clients/ammMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
SwapPreview
} from "@/types/amm";
import { TransactionProcessingUpdate } from "@/types/transactions";
import { BN, Program, Provider } from "@coral-xyz/anchor";
import anchor from "@coral-xyz/anchor";
import BN from "bn.js";
import {
AMM_PROGRAM_ID,
AmmAccount,
Expand All @@ -27,14 +28,14 @@ import { AccountInfo, PublicKey } from "@solana/web3.js";
import { Observable } from "rxjs";

export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
private rpcProvider: Provider;
private amm: Program<AmmIDLType>;
private rpcProvider: anchor.Provider;
private amm: anchor.Program<AmmIDLType>;
private ammClient: AmmClient;
private transactionSender: TransactionSender | undefined;

constructor(
rpcProvider: Provider,
amm: Program<AmmIDLType>,
rpcProvider: anchor.Provider,
amm: anchor.Program<AmmIDLType>,
ammClient: AmmClient,
transactionSender: TransactionSender | undefined
) {
Expand Down Expand Up @@ -113,7 +114,7 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
);

const maxBaseAmountWithSlippage = calculateMaxWithSlippage(
maxBaseAmountArg,
maxBaseAmountArg.toNumber(),
slippage
);
const baseReserve = ammMarket.baseAmount;
Expand Down Expand Up @@ -194,7 +195,7 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
);

const maxBaseAmountWithSlippage = calculateMaxWithSlippage(
maxBaseAmountArg,
maxBaseAmountArg.toNumber(),
slippage
);

Expand Down Expand Up @@ -421,7 +422,7 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
slippageBps: BN
): SwapPreview {
const swapType = isBuyBase ? { buy: {} } : { sell: {} };
let startPrice = amm.quoteAmount / amm.baseAmount;
let startPrice = amm.quoteAmount.toNumber() / amm.baseAmount.toNumber();

const { expectedOut, newBaseReserves, newQuoteReserves } =
this.ammClient.simulateSwap(
Expand All @@ -432,16 +433,16 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
slippageBps
);

const finalPrice = newQuoteReserves / newBaseReserves;
const finalPrice = newQuoteReserves.toNumber() / newBaseReserves.toNumber();

// NOTE: Default is selling into USDC
let avgSwapPrice = expectedOut / inputAmount;
let humanInput = inputAmount / 10 ** amm.baseMintDecimals;
let humanOutput = expectedOut / 10 ** amm.quoteMintDecimals;
let avgSwapPrice = expectedOut.toNumber() / inputAmount.toNumber();
let humanInput = inputAmount.toNumber() / 10 ** amm.baseMintDecimals;
let humanOutput = expectedOut.toNumber() / 10 ** amm.quoteMintDecimals;
if (swapType.buy) {
avgSwapPrice = inputAmount / expectedOut;
humanInput = inputAmount / 10 ** amm.quoteMintDecimals;
humanOutput = expectedOut / 10 ** amm.baseMintDecimals;
avgSwapPrice = inputAmount.toNumber() / expectedOut.toNumber();
humanInput = inputAmount.toNumber() / 10 ** amm.quoteMintDecimals;
humanOutput = expectedOut.toNumber() / 10 ** amm.baseMintDecimals;
}

const priceImpact = Math.abs(finalPrice - startPrice) / startPrice;
Expand All @@ -454,7 +455,7 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
outputUnits: humanOutput,
startPrice,
finalPrice,
avgSwapPrice: inputAmount / expectedOut,
avgSwapPrice: inputAmount.toNumber() / expectedOut.toNumber(),
priceImpact
};
}
Expand Down
21 changes: 12 additions & 9 deletions lib/client/rpc/market-clients/openbookMarkets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BN, Program, Provider } from "@coral-xyz/anchor";
import anchor from "@coral-xyz/anchor";
import BN from "bn.js";
import {
Market as OBMarket,
Order as OBOrder,
Expand Down Expand Up @@ -42,14 +43,14 @@ import { SendTransactionResponse } from "@/types/transactions";
export class FutarchyOpenbookMarketsRPCClient
implements FutarchyOrderbookMarketsClient<OpenbookMarket, OpenbookOrder>
{
private openbook: Program<OpenbookV2>;
private openbook: anchor.Program<OpenbookV2>;
private openbookClient: OpenBookV2Client;
private rpcProvider: Provider;
private rpcProvider: anchor.Provider;
private transactionSender: TransactionSender | undefined;

constructor(
rpcProvider: Provider,
openbook: Program<OpenbookV2>,
rpcProvider: anchor.Provider,
openbook: anchor.Program<OpenbookV2>,
openbookClient: OpenBookV2Client,
transactionSender: TransactionSender | undefined
) {
Expand Down Expand Up @@ -177,7 +178,7 @@ export class FutarchyOpenbookMarketsRPCClient
size: bookSideOrder.size,
filled:
bookSideOrder.size -
getPartiallyFilledAmountFromBookSideOrder(bookSideOrder),
getPartiallyFilledAmountFromBookSideOrder(bookSideOrder).toNumber(),
owner: bookSideOrder.leafNode.owner,
clientOrderId: bookSideOrder.leafNode.clientOrderId,
market: bookSideOrder.market.pubkey,
Expand Down Expand Up @@ -236,7 +237,9 @@ export class FutarchyOpenbookMarketsRPCClient
const [openOrdersIx, openOrdersAccountAddress] =
await this.openbookClient.createOpenOrdersIx(
market.publicKey,
`${shortKey(this.transactionSender.owner)}-${shortKey(accountIndex)}`,
`${shortKey(this.transactionSender.owner)}-${shortKey(
accountIndex.toString()
)}`,
this.transactionSender.owner,
// TODO do we have delegate?
null,
Expand All @@ -246,7 +249,7 @@ export class FutarchyOpenbookMarketsRPCClient

const placeLimitOrderArgs = this.createPlaceOrderArgs({
orderType: placeOrderType,
accountIndex,
accountIndex: accountIndex.toNumber(),
market: market.marketInstance,
isAsk: order.side === "ask",
amount: order.size,
Expand Down Expand Up @@ -343,7 +346,7 @@ export class FutarchyOpenbookMarketsRPCClient
const _priceLots = market.priceUiToLots(priceCalc);
const maxBaseLots = market.baseUiToLots(amount);
let maxQuoteLotsIncludingFees = market.quoteUiToLots(
priceLots.mul(maxBaseLots)
priceLots.mul(maxBaseLots).toNumber()
);

if (_priceLots === priceLots) {
Expand Down
Loading
Loading