Skip to content

Commit

Permalink
feat: refactor SDK to return tx observables
Browse files Browse the repository at this point in the history
  • Loading branch information
LukasDeco committed May 30, 2024
1 parent 7cf7aa7 commit 125fc62
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 235 deletions.
41 changes: 28 additions & 13 deletions lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ import {
SpotObservation,
TwapObservation
} from "@/types/prices";
import { SendTransactionResponse } from "@/types/transactions";
import {
SendTransactionResponse,
TransactionProcessingUpdate
} from "@/types/transactions";
import { BN } from "@coral-xyz/anchor";
import {
CreateProposalInstruction,
Expand Down Expand Up @@ -64,25 +67,32 @@ export interface FutarchyProposalsClient {
amount: number,
vaultAccountAddress: PublicKey,
vaultAccount: VaultAccountWithProtocol
): SendTransactionResponse;
withdraw(proposal: Proposal): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
withdraw(
proposal: Proposal
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
createProposal(
daoAggregate: DaoAggregate,
version: ProgramVersionLabel,
instructionParams: CreateProposalInstruction,
marketParams: MarketParams,
proposalDetails: ProposalDetails
): SendTransactionResponse;
finalizeProposal(proposal: Proposal): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
finalizeProposal(
proposal: Proposal
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
saveProposalDetails(proposalDetails: ProposalDetails): void;
updateProposalAccounts(accounts: ProposalAccounts): void;
mergeConditionalTokensForUnderlyingTokens(
programVersion: ProgramVersionLabel,
amoutn: BN,
proposal: Proposal,
underlyingToken: "base" | "quote"
): SendTransactionResponse;
watchReactions?: (proposal: string, user?: string) => Observable<ReactionResponse>
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
watchReactions?: (
proposal: string,
user?: string
) => Observable<ReactionResponse>;
}

export interface FutarchyBalancesClient {
Expand Down Expand Up @@ -148,8 +158,11 @@ export interface FutarchyOrderbookMarketsClient<
market: M,
order: Omit<O, "owner" | "transactionStatus" | "status" | "filled">,
placeOrderType: PlaceOrderType
): SendTransactionResponse;
cancelOrder(market: M, order: O): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
cancelOrder(
market: M,
order: O
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
}

export interface FutarchyAmmMarketsClient {
Expand All @@ -160,12 +173,12 @@ export interface FutarchyAmmMarketsClient {
inputAmount: number,
outputAmountMin: number,
slippage: number
): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
removeLiquidity(
ammMarket: AmmMarket,
lpTokensToBurn: number,
slippage: number
): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
validateAddLiquidity(
ammMarket: AmmMarket,
quoteAmount: number,
Expand All @@ -179,11 +192,13 @@ export interface FutarchyAmmMarketsClient {
quoteAmount: number,
maxBaseAmount: number,
slippage: number
): SendTransactionResponse;
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
}

export interface FinalizeProposal {
finalizeProposal(proposal: Proposal): SendTransactionResponse;
finalizeProposal(
proposal: Proposal
): Promise<Observable<TransactionProcessingUpdate> | undefined>;
}

export interface CreateProposal {
Expand Down
6 changes: 3 additions & 3 deletions lib/client/indexer/market-clients/ammMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class FutarchyIndexerAmmMarketsClient
quoteAmount: number,
maxBaseAmount: number,
slippage: number
): SendTransactionResponse {
) {
return this.rpcMarketsClient.addLiquidity(
ammMarket,
quoteAmount,
Expand All @@ -77,7 +77,7 @@ export class FutarchyIndexerAmmMarketsClient
ammMarket: AmmMarket,
lpTokensToBurn: number,
slippage: number
): SendTransactionResponse {
) {
return this.rpcMarketsClient.removeLiquidity(
ammMarket,
lpTokensToBurn,
Expand All @@ -101,7 +101,7 @@ export class FutarchyIndexerAmmMarketsClient
inputAmount: number,
outputAmountMin: number,
slippage: number
): SendTransactionResponse {
) {
return this.rpcMarketsClient.swap(
ammMarket,
swapType,
Expand Down
7 changes: 2 additions & 5 deletions lib/client/indexer/market-clients/openbookMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ export class FutarchyIndexerOpenbookMarketsClient
constructor(rpcMarketsClient: FutarchyOpenbookMarketsRPCClient) {
this.rpcMarketsClient = rpcMarketsClient;
}
async cancelOrder(
market: OpenbookMarket,
order: OpenbookOrder
): SendTransactionResponse {
async cancelOrder(market: OpenbookMarket, order: OpenbookOrder) {
return this.rpcMarketsClient.cancelOrder(market, order);
}

Expand Down Expand Up @@ -52,7 +49,7 @@ export class FutarchyIndexerOpenbookMarketsClient
market: OpenbookMarket,
order: Omit<OpenbookOrder, "status" | "transactionStatus" | "filled">,
placeOrderType: PlaceOrderType
): SendTransactionResponse {
) {
return this.rpcMarketsClient.placeOrder(market, order, placeOrderType);
}
}
61 changes: 34 additions & 27 deletions lib/client/indexer/proposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import {
} from "@/types";
import { FutarchyProposalsClient } from "@/client";
import { FutarchyRPCProposalsClient } from "@/client/rpc";
import { Client as IndexerGraphQLClient, generateSubscriptionOp } from "./__generated__";
import {
Client as IndexerGraphQLClient,
generateSubscriptionOp
} from "./__generated__";
import { SendTransactionResponse } from "@/types/transactions";
import {
CreateProposalInstruction,
Expand All @@ -25,7 +28,6 @@ import { Client as GQLWebSocketClient } from "graphql-ws";
import { SUPPORTED_EMOJIS } from "@/constants/reactions";
import { ReactionType } from "@/types/reactions";


export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
private protocolMap: Map<string, FutarchyProtocol>;
private rpcProposalsClient: FutarchyRPCProposalsClient;
Expand Down Expand Up @@ -198,7 +200,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
new BN(curr.filled_base_amount),
new BN(d.tokenByBaseAcct?.decimals ?? 6)
) *
curr.quote_price,
curr.quote_price,
0
) ?? 0;
const failVolume =
Expand All @@ -209,7 +211,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
new BN(curr.filled_base_amount),
new BN(d.tokenByBaseAcct?.decimals ?? 6)
) *
curr.quote_price,
curr.quote_price,
0
) ?? 0;

Expand Down Expand Up @@ -282,10 +284,10 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
endDate: p.ended_at
? new Date(p.ended_at)
: new Date(
new Date(p.created_at).setDate(
new Date(p.created_at).getDate() + 3
)
),
new Date(p.created_at).setDate(
new Date(p.created_at).getDate() + 3
)
),
// TODO figure this out by slot enqueued maybe
finalizationDate: p.completed_at,
dao: {
Expand Down Expand Up @@ -373,15 +375,15 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
amount: number,
vaultAccountAddress: PublicKey,
vaultAccount: VaultAccountWithProtocol
): SendTransactionResponse {
) {
return this.rpcProposalsClient.deposit(
amount,
vaultAccountAddress,
vaultAccount
);
}

async withdraw(proposal: Proposal): SendTransactionResponse {
async withdraw(proposal: Proposal) {
return this.rpcProposalsClient.withdraw(proposal);
}

Expand All @@ -391,7 +393,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
instructionParams: CreateProposalInstruction,
marketParams: MarketParams,
proposalDetails: ProposalDetails
): SendTransactionResponse {
) {
return this.rpcProposalsClient.createProposal(
daoAggregate,
version,
Expand All @@ -418,7 +420,7 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
amount: BN,
proposal: Proposal,
underlyingToken: "base" | "quote"
): SendTransactionResponse {
) {
return this.rpcProposalsClient.mergeConditionalTokensForUnderlyingTokens(
programVersion,
amount,
Expand All @@ -427,7 +429,12 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
);
}

watchReactions(proposal: string, user?: string) : Observable<{ [key in ReactionType]: { count: number, userReacted: boolean } }> {
watchReactions(
proposal: string,
user?: string
): Observable<{
[key in ReactionType]: { count: number; userReacted: boolean };
}> {
const { query, variables } = generateSubscriptionOp({
reactions: {
__args: {
Expand All @@ -438,37 +445,39 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
reactor_acct: true,
updated_at: true,
reaction: true,
proposal_acct: true,
proposal_acct: true
}
});

return new Observable((subscriber) => {
const subscriptionCleanup:() => void = this.graphqlWSClient.subscribe<{
const subscriptionCleanup: () => void = this.graphqlWSClient.subscribe<{
reactions: {
reactor_acct: string,
updated_at: string,
reaction: string,
proposal_acct: string,
reactor_acct: string;
updated_at: string;
reaction: string;
proposal_acct: string;
}[];
}>(
{ query, variables },
{
next: (data) => {
const reactions = data.data

const reactionCounts: { [key in ReactionType]: { count: number, userReacted: boolean } } = {};
const reactions = data.data;

const reactionCounts: {
[key in ReactionType]: { count: number; userReacted: boolean };
} = {};
// Initialize each reaction type
SUPPORTED_EMOJIS.forEach((reactionType) => {
reactionCounts[reactionType] = { count: 0, userReacted: false };
})
});

// Might need some optimization later
reactions?.reactions.forEach((reaction) => {
reactionCounts[reaction.reaction]!!.count += 1;
if (user && reaction.reactor_acct === user)
reactionCounts[reaction.reaction]!!.userReacted = true;
})
});

subscriber.next(reactionCounts);
},
error: (error) => subscriber.error(error),
Expand All @@ -479,5 +488,3 @@ export class FutarchyIndexerProposalsClient implements FutarchyProposalsClient {
});
}
}


46 changes: 18 additions & 28 deletions lib/client/rpc/market-clients/ammMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import {
LiquidityAddError,
SwapPreview
} from "@/types/amm";
import { SendTransactionResponse } from "@/types/transactions";
import {
SendTransactionResponse,
TransactionProcessingUpdate
} from "@/types/transactions";
import { BN, Program, Provider } from "@coral-xyz/anchor";
import {
AMM_PROGRAM_ID,
Expand All @@ -24,6 +27,7 @@ import {
import { Amm as AmmIDLType } from "@/idl/amm_v0.3";
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import { AccountInfo, PublicKey } from "@solana/web3.js";
import { Observable } from "rxjs";

export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
private rpcProvider: Provider;
Expand Down Expand Up @@ -166,17 +170,11 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
quoteAmount: number,
maxBaseAmount: number,
slippage: number
): SendTransactionResponse {
if (!this.transactionSender)
return {
signatures: [],
errors: [
{
message: "Transaction sender is undefined",
name: "Transaction Sender Error"
}
]
};
) {
if (!this.transactionSender) {
console.error("Transaction sender is undefined");
return;
}

const validationError = this.validateAddLiquidity(
ammMarket,
Expand All @@ -185,10 +183,8 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
slippage
);
if (validationError) {
return {
signatures: [],
errors: [{ message: validationError, name: "Failed to Add Liquidity." }]
};
console.error("failed to add liquidity", validationError);
return;
}

const quoteAmountArg = PriceMath.getChainAmount(
Expand Down Expand Up @@ -286,7 +282,7 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
ammMarket: AmmMarket,
lpTokensToBurn: number,
slippage: number
) {
): Promise<Observable<TransactionProcessingUpdate> | undefined> {
// fetch or have lp token account
const lpTokensLots = PriceMath.getChainAmount(lpTokensToBurn, 9);

Expand Down Expand Up @@ -345,17 +341,11 @@ export class FutarchyAmmMarketsRPCClient implements FutarchyAmmMarketsClient {
inputAmount: number,
outputAmountMin: number,
slippage: number
): SendTransactionResponse {
if (!this.transactionSender)
return {
signatures: [],
errors: [
{
message: "Transaction sender is undefined",
name: "Transaction Sender Error"
}
]
};
) {
if (!this.transactionSender) {
console.error("Transaction sender is undefined");
return;
}
let [inputToken, outputToken] = swapType.buy
? [ammMarket.quoteToken, ammMarket.baseToken]
: [ammMarket.baseToken, ammMarket.quoteToken];
Expand Down
Loading

0 comments on commit 125fc62

Please sign in to comment.