/
newOrder.ts
87 lines (81 loc) · 2.72 KB
/
newOrder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Program } from "@project-serum/anchor";
import { PublicKey, Transaction } from "@solana/web3.js";
import { marketLoader } from "./marketLoader";
import { deriveMarketAuthority } from "../serumUtils";
import { initOpenOrdersInstruction } from "./initOpenOrders";
import { OrderParamsWithFeeRate } from "../types";
import { PsyAmerican } from "../psyAmericanTypes";
const textEncoder = new TextEncoder();
/**
* Create a new order proxied through the Psy American Protocol
*
* @param program - Anchor Psy American program
* @param optionMarketKey - The OptionMarket address
* @param dexProgramId - The Serum DEX program ID
* @param serumMarketKey - The Serum market address
* @param orderArguments - The Serum OrderParams
* @param marketAuthorityBump - OPTIONAL: pass in the market authority bump seed
* @returns
*/
export const newOrderInstruction = async (
program: Program<PsyAmerican>,
optionMarketKey: PublicKey,
dexProgramId: PublicKey,
serumMarketKey: PublicKey,
orderArguments: OrderParamsWithFeeRate<PublicKey>,
marketAuthorityBump: number | undefined = undefined
): Promise<{ openOrdersKey: PublicKey; tx: Transaction }> => {
const transaction = new Transaction();
let _openOrdersKey = orderArguments.openOrdersAddressKey;
let _marketAuthorityBump = marketAuthorityBump;
if (!_marketAuthorityBump) {
const [marketAuthority, bump] = await deriveMarketAuthority(
program,
dexProgramId,
serumMarketKey
);
_marketAuthorityBump = bump;
}
const marketProxy = await marketLoader(
program,
optionMarketKey,
_marketAuthorityBump,
dexProgramId,
serumMarketKey
);
// create OpenOrders account
if (!_openOrdersKey) {
// Check that the OpenOrders account does not exist
[_openOrdersKey] = await PublicKey.findProgramAddress(
[
textEncoder.encode("open-orders"),
dexProgramId.toBuffer(),
marketProxy.market.address.toBuffer(),
program.provider.wallet.publicKey.toBuffer(),
],
program.programId
);
const accountInfo = await program.provider.connection.getAccountInfo(
_openOrdersKey,
"recent"
);
orderArguments.openOrdersAddressKey = _openOrdersKey;
if (!accountInfo) {
const { ix } = await initOpenOrdersInstruction(
program,
program.provider.wallet.publicKey,
optionMarketKey,
dexProgramId,
serumMarketKey,
_marketAuthorityBump
);
transaction.add(ix);
}
}
if (orderArguments.feeRate) {
orderArguments.price = orderArguments.price * (1 + orderArguments.feeRate);
}
const ix = marketProxy.instruction.newOrderV3(orderArguments);
transaction.add(ix);
return { openOrdersKey: _openOrdersKey, tx: transaction };
};