index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // Boilerplate utils to bootstrap an orderbook for testing on a localnet.
  2. // not super relevant to the point of the example, though may be useful to
  3. // include into your own workspace for testing.
  4. //
  5. // TODO: Modernize all these apis. This is all quite clunky.
  6. const Token = require("@solana/spl-token").Token;
  7. const TOKEN_PROGRAM_ID = require("@solana/spl-token").TOKEN_PROGRAM_ID;
  8. const TokenInstructions = require("@project-serum/serum").TokenInstructions;
  9. const { Market, OpenOrders } = require("@project-serum/serum");
  10. const DexInstructions = require("@project-serum/serum").DexInstructions;
  11. const web3 = require("@project-serum/anchor").web3;
  12. const Connection = web3.Connection;
  13. const anchor = require("@project-serum/anchor");
  14. const BN = anchor.BN;
  15. const serumCmn = require("@project-serum/common");
  16. const Account = web3.Account;
  17. const Transaction = web3.Transaction;
  18. const PublicKey = web3.PublicKey;
  19. const SystemProgram = web3.SystemProgram;
  20. const DEX_PID = new PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin");
  21. const MARKET_MAKER = new Account();
  22. async function initMarket({ provider }) {
  23. // Setup mints with initial tokens owned by the provider.
  24. const decimals = 6;
  25. const [MINT_A, GOD_A] = await serumCmn.createMintAndVault(
  26. provider,
  27. new BN("1000000000000000000"),
  28. undefined,
  29. decimals
  30. );
  31. const [USDC, GOD_USDC] = await serumCmn.createMintAndVault(
  32. provider,
  33. new BN("1000000000000000000"),
  34. undefined,
  35. decimals
  36. );
  37. // Create a funded account to act as market maker.
  38. const amount = new BN("10000000000000").muln(10 ** decimals);
  39. const marketMaker = await fundAccount({
  40. provider,
  41. mints: [
  42. { god: GOD_A, mint: MINT_A, amount, decimals },
  43. { god: GOD_USDC, mint: USDC, amount, decimals },
  44. ],
  45. });
  46. // Setup A/USDC with resting orders.
  47. const asks = [
  48. [6.041, 7.8],
  49. [6.051, 72.3],
  50. [6.055, 5.4],
  51. [6.067, 15.7],
  52. [6.077, 390.0],
  53. [6.09, 24.0],
  54. [6.11, 36.3],
  55. [6.133, 300.0],
  56. [6.167, 687.8],
  57. ];
  58. const bids = [
  59. [6.004, 8.5],
  60. [5.995, 12.9],
  61. [5.987, 6.2],
  62. [5.978, 15.3],
  63. [5.965, 82.8],
  64. [5.961, 25.4],
  65. ];
  66. [MARKET_A_USDC, vaultSigner] = await setupMarket({
  67. baseMint: MINT_A,
  68. quoteMint: USDC,
  69. marketMaker: {
  70. account: marketMaker.account,
  71. baseToken: marketMaker.tokens[MINT_A.toString()],
  72. quoteToken: marketMaker.tokens[USDC.toString()],
  73. },
  74. bids,
  75. asks,
  76. provider,
  77. });
  78. const marketMakerOpenOrders = (
  79. await OpenOrders.findForMarketAndOwner(
  80. provider.connection,
  81. MARKET_A_USDC.address,
  82. marketMaker.account.publicKey,
  83. DEX_PID
  84. )
  85. )[0].address;
  86. return {
  87. marketA: MARKET_A_USDC,
  88. vaultSigner,
  89. marketMaker,
  90. marketMakerOpenOrders,
  91. mintA: MINT_A,
  92. usdc: USDC,
  93. godA: GOD_A,
  94. godUsdc: GOD_USDC,
  95. };
  96. }
  97. async function fundAccount({ provider, mints }) {
  98. const marketMaker = {
  99. tokens: {},
  100. account: MARKET_MAKER,
  101. };
  102. // Transfer lamports to market maker.
  103. await provider.send(
  104. (() => {
  105. const tx = new Transaction();
  106. tx.add(
  107. SystemProgram.transfer({
  108. fromPubkey: provider.wallet.publicKey,
  109. toPubkey: MARKET_MAKER.publicKey,
  110. lamports: 100000000000,
  111. })
  112. );
  113. return tx;
  114. })()
  115. );
  116. // Transfer SPL tokens to the market maker.
  117. for (let k = 0; k < mints.length; k += 1) {
  118. const { mint, god, amount, decimals } = mints[k];
  119. let MINT_A = mint;
  120. let GOD_A = god;
  121. // Setup token accounts owned by the market maker.
  122. const mintAClient = new Token(
  123. provider.connection,
  124. MINT_A,
  125. TOKEN_PROGRAM_ID,
  126. provider.wallet.payer // node only
  127. );
  128. const marketMakerTokenA = await mintAClient.createAccount(
  129. MARKET_MAKER.publicKey
  130. );
  131. await provider.send(
  132. (() => {
  133. const tx = new Transaction();
  134. tx.add(
  135. Token.createTransferCheckedInstruction(
  136. TOKEN_PROGRAM_ID,
  137. GOD_A,
  138. MINT_A,
  139. marketMakerTokenA,
  140. provider.wallet.publicKey,
  141. [],
  142. amount,
  143. decimals
  144. )
  145. );
  146. return tx;
  147. })()
  148. );
  149. marketMaker.tokens[mint.toString()] = marketMakerTokenA;
  150. }
  151. return marketMaker;
  152. }
  153. async function setupMarket({
  154. provider,
  155. marketMaker,
  156. baseMint,
  157. quoteMint,
  158. bids,
  159. asks,
  160. }) {
  161. const [marketAPublicKey, vaultOwner] = await listMarket({
  162. connection: provider.connection,
  163. wallet: provider.wallet,
  164. baseMint: baseMint,
  165. quoteMint: quoteMint,
  166. baseLotSize: 100000,
  167. quoteLotSize: 100,
  168. dexProgramId: DEX_PID,
  169. feeRateBps: 0,
  170. });
  171. const MARKET_A_USDC = await Market.load(
  172. provider.connection,
  173. marketAPublicKey,
  174. { commitment: "recent" },
  175. DEX_PID
  176. );
  177. for (let k = 0; k < asks.length; k += 1) {
  178. let ask = asks[k];
  179. const {
  180. transaction,
  181. signers,
  182. } = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
  183. owner: marketMaker.account,
  184. payer: marketMaker.baseToken,
  185. side: "sell",
  186. price: ask[0],
  187. size: ask[1],
  188. orderType: "postOnly",
  189. clientId: undefined,
  190. openOrdersAddressKey: undefined,
  191. openOrdersAccount: undefined,
  192. feeDiscountPubkey: null,
  193. selfTradeBehavior: "abortTransaction",
  194. });
  195. await provider.send(transaction, signers.concat(marketMaker.account));
  196. }
  197. for (let k = 0; k < bids.length; k += 1) {
  198. let bid = bids[k];
  199. const {
  200. transaction,
  201. signers,
  202. } = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
  203. owner: marketMaker.account,
  204. payer: marketMaker.quoteToken,
  205. side: "buy",
  206. price: bid[0],
  207. size: bid[1],
  208. orderType: "postOnly",
  209. clientId: undefined,
  210. openOrdersAddressKey: undefined,
  211. openOrdersAccount: undefined,
  212. feeDiscountPubkey: null,
  213. selfTradeBehavior: "abortTransaction",
  214. });
  215. await provider.send(transaction, signers.concat(marketMaker.account));
  216. }
  217. return [MARKET_A_USDC, vaultOwner];
  218. }
  219. async function listMarket({
  220. connection,
  221. wallet,
  222. baseMint,
  223. quoteMint,
  224. baseLotSize,
  225. quoteLotSize,
  226. dexProgramId,
  227. feeRateBps,
  228. }) {
  229. const market = new Account();
  230. const requestQueue = new Account();
  231. const eventQueue = new Account();
  232. const bids = new Account();
  233. const asks = new Account();
  234. const baseVault = new Account();
  235. const quoteVault = new Account();
  236. const quoteDustThreshold = new BN(100);
  237. const [vaultOwner, vaultSignerNonce] = await getVaultOwnerAndNonce(
  238. market.publicKey,
  239. dexProgramId
  240. );
  241. const tx1 = new Transaction();
  242. tx1.add(
  243. SystemProgram.createAccount({
  244. fromPubkey: wallet.publicKey,
  245. newAccountPubkey: baseVault.publicKey,
  246. lamports: await connection.getMinimumBalanceForRentExemption(165),
  247. space: 165,
  248. programId: TOKEN_PROGRAM_ID,
  249. }),
  250. SystemProgram.createAccount({
  251. fromPubkey: wallet.publicKey,
  252. newAccountPubkey: quoteVault.publicKey,
  253. lamports: await connection.getMinimumBalanceForRentExemption(165),
  254. space: 165,
  255. programId: TOKEN_PROGRAM_ID,
  256. }),
  257. TokenInstructions.initializeAccount({
  258. account: baseVault.publicKey,
  259. mint: baseMint,
  260. owner: vaultOwner,
  261. }),
  262. TokenInstructions.initializeAccount({
  263. account: quoteVault.publicKey,
  264. mint: quoteMint,
  265. owner: vaultOwner,
  266. })
  267. );
  268. const tx2 = new Transaction();
  269. tx2.add(
  270. SystemProgram.createAccount({
  271. fromPubkey: wallet.publicKey,
  272. newAccountPubkey: market.publicKey,
  273. lamports: await connection.getMinimumBalanceForRentExemption(
  274. Market.getLayout(dexProgramId).span
  275. ),
  276. space: Market.getLayout(dexProgramId).span,
  277. programId: dexProgramId,
  278. }),
  279. SystemProgram.createAccount({
  280. fromPubkey: wallet.publicKey,
  281. newAccountPubkey: requestQueue.publicKey,
  282. lamports: await connection.getMinimumBalanceForRentExemption(5120 + 12),
  283. space: 5120 + 12,
  284. programId: dexProgramId,
  285. }),
  286. SystemProgram.createAccount({
  287. fromPubkey: wallet.publicKey,
  288. newAccountPubkey: eventQueue.publicKey,
  289. lamports: await connection.getMinimumBalanceForRentExemption(262144 + 12),
  290. space: 262144 + 12,
  291. programId: dexProgramId,
  292. }),
  293. SystemProgram.createAccount({
  294. fromPubkey: wallet.publicKey,
  295. newAccountPubkey: bids.publicKey,
  296. lamports: await connection.getMinimumBalanceForRentExemption(65536 + 12),
  297. space: 65536 + 12,
  298. programId: dexProgramId,
  299. }),
  300. SystemProgram.createAccount({
  301. fromPubkey: wallet.publicKey,
  302. newAccountPubkey: asks.publicKey,
  303. lamports: await connection.getMinimumBalanceForRentExemption(65536 + 12),
  304. space: 65536 + 12,
  305. programId: dexProgramId,
  306. }),
  307. DexInstructions.initializeMarket({
  308. market: market.publicKey,
  309. requestQueue: requestQueue.publicKey,
  310. eventQueue: eventQueue.publicKey,
  311. bids: bids.publicKey,
  312. asks: asks.publicKey,
  313. baseVault: baseVault.publicKey,
  314. quoteVault: quoteVault.publicKey,
  315. baseMint,
  316. quoteMint,
  317. baseLotSize: new BN(baseLotSize),
  318. quoteLotSize: new BN(quoteLotSize),
  319. feeRateBps,
  320. vaultSignerNonce,
  321. quoteDustThreshold,
  322. programId: dexProgramId,
  323. })
  324. );
  325. const signedTransactions = await signTransactions({
  326. transactionsAndSigners: [
  327. { transaction: tx1, signers: [baseVault, quoteVault] },
  328. {
  329. transaction: tx2,
  330. signers: [market, requestQueue, eventQueue, bids, asks],
  331. },
  332. ],
  333. wallet,
  334. connection,
  335. });
  336. for (let signedTransaction of signedTransactions) {
  337. await sendAndConfirmRawTransaction(
  338. connection,
  339. signedTransaction.serialize()
  340. );
  341. }
  342. const acc = await connection.getAccountInfo(market.publicKey);
  343. return [market.publicKey, vaultOwner];
  344. }
  345. async function signTransactions({
  346. transactionsAndSigners,
  347. wallet,
  348. connection,
  349. }) {
  350. const blockhash = (await connection.getRecentBlockhash("max")).blockhash;
  351. transactionsAndSigners.forEach(({ transaction, signers = [] }) => {
  352. transaction.recentBlockhash = blockhash;
  353. transaction.setSigners(
  354. wallet.publicKey,
  355. ...signers.map((s) => s.publicKey)
  356. );
  357. if (signers?.length > 0) {
  358. transaction.partialSign(...signers);
  359. }
  360. });
  361. return await wallet.signAllTransactions(
  362. transactionsAndSigners.map(({ transaction }) => transaction)
  363. );
  364. }
  365. async function sendAndConfirmRawTransaction(
  366. connection,
  367. raw,
  368. commitment = "recent"
  369. ) {
  370. let tx = await connection.sendRawTransaction(raw, {
  371. skipPreflight: true,
  372. });
  373. return await connection.confirmTransaction(tx, commitment);
  374. }
  375. async function getVaultOwnerAndNonce(marketPublicKey, dexProgramId = DEX_PID) {
  376. const nonce = new BN(0);
  377. while (nonce.toNumber() < 255) {
  378. try {
  379. const vaultOwner = await PublicKey.createProgramAddress(
  380. [marketPublicKey.toBuffer(), nonce.toArrayLike(Buffer, "le", 8)],
  381. dexProgramId
  382. );
  383. return [vaultOwner, nonce];
  384. } catch (e) {
  385. nonce.iaddn(1);
  386. }
  387. }
  388. throw new Error("Unable to find nonce");
  389. }
  390. function sleep(ms) {
  391. return new Promise((resolve) => setTimeout(resolve, ms));
  392. }
  393. module.exports = {
  394. fundAccount,
  395. initMarket,
  396. setupMarket,
  397. DEX_PID,
  398. getVaultOwnerAndNonce,
  399. sleep,
  400. };