All files / src bindings.ts

48.91% Statements 45/92
2.43% Branches 1/41
8.33% Functions 1/12
42.68% Lines 35/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 5401x             1x 1x                       1x   1x     1x         1x 1x 1x 1x         1x 1x 1x 1x                           1x                         1x               1x 1x   1x         1x                   1x         1x                                             1x               1x             1x                                               1x                                         1x                                                                                                                                           1x                                                                           1x                                                                 1x                                                                                 1x                                                 1x                               1x                                                                                                         1x                                                 1x                                                                                                                
import {
  Keypair,
  PublicKey,
  Connection,
  SystemProgram,
  TransactionInstruction,
} from "@solana/web3.js";
import { DEX_ID, SRM_MINT } from "./ids";
import {
  cancelOrderInstruction,
  consumeEventsInstruction,
  createMarketInstruction,
  initializeAccountInstruction,
  newOrderInstruction,
  settleInstruction,
  closeAccountInstruction,
  swapInstruction,
  closeMarketInstruction,
  sweepFeesInstruction,
} from "./raw_instructions";
import { OrderType, PrimedTransaction, Side } from "./types";
import * as aaob from "@bonfida/aaob";
import BN from "bn.js";
import { SelfTradeBehavior } from "./state";
import { Market } from "./market";
import {
  TOKEN_PROGRAM_ID,
  createAssociatedTokenAccountInstruction,
  getAssociatedTokenAddress,
} from "@solana/spl-token";
import crypto from "crypto";
import { getMetadataKeyFromMint } from "./metadata";
import { Metadata } from "@metaplex-foundation/mpl-token-metadata";
import { computeFp32Price } from "./utils";
 
/**
 * Constants
 */
const MARKET_STATE_SPACE = 280;
const NODE_CAPACITY = 100;
const EVENT_CAPACITY = 100;
const U64_MAX = "18446744073709551615";
 
/**
 *
 * @param connection The Solana RPC connection
 * @param baseMint The mint of the base token
 * @param quoteMint The mint of the quote token
 * @param minBaseOrderSize The minimum base order size
 * @param feePayer The fee payer of the transaction
 * @param marketAdmin The market admin
 * @param tickSize The tick size of the market (FP32)
 * @param crankerReward The cranker rewards (raw amount SOL)
 * @returns
 */
export const createMarket = async (
  connection: Connection,
  baseMint: PublicKey,
  quoteMint: PublicKey,
  minBaseOrderSize: BN,
  feePayer: PublicKey,
  marketAdmin: PublicKey,
  tickSize: BN,
  crankerReward: BN,
  baseCurrencyMultiplier?: BN,
  quoteCurrencyMultiplier?: BN
): Promise<PrimedTransaction[]> => {
  // Metadata account
  const metadataAccount = await getMetadataKeyFromMint(baseMint);
 
  // Market Account
  // const marketAccount = new Keypair();
  // console.log(`Market address ${marketAccount.publicKey.toBase58()}`);
  // const balance = await connection.getMinimumBalanceForRentExemption(
  //   MARKET_STATE_SPACE
  // );
  if (!baseCurrencyMultiplier) {
    baseCurrencyMultiplier = new BN(1);
  }
  Iif (!quoteCurrencyMultiplier) {
    quoteCurrencyMultiplier = new BN(1);
  }
 
  // Adjust tick size
  tickSize = tickSize.mul(baseCurrencyMultiplier).div(quoteCurrencyMultiplier);
 
  // const createMarketAccount = SystemProgram.createAccount({
  //   fromPubkey: feePayer,
  //   lamports: balance,
  //   newAccountPubkey: marketAccount.publicKey,
  //   programId: DEX_ID,
  //   space: MARKET_STATE_SPACE,
  // });
 
  const marketPubkey = new PublicKey(
    "DL6EXirHGSBSr3zq1aW9krJ5qB22dSNWivKuE4H1xcxz"
  );
 
  // Market signer
  const [marketSigner, marketSignerNonce] = await PublicKey.findProgramAddress(
    [marketPubkey.toBuffer()],
    DEX_ID
  );
 
  // // AAOB instructions
  // const [aaobSigners, aaobInstructions] = await aaob.createMarket(
  //   connection,
  //   marketSigner,
  //   new BN(33),
  //   new BN(32),
  //   EVENT_CAPACITY,
  //   NODE_CAPACITY,
  //   new BN(minBaseOrderSize),
  //   feePayer,
  //   tickSize,
  //   crankerReward,
  //   DEX_ID
  // );
  // // Remove the AOB create_market instruction as it is not needed with lib usage
  // aaobInstructions.pop();
 
  // Base vault
  const createBaseVault = await createAssociatedTokenAccountInstruction(
    feePayer,
    await getAssociatedTokenAddress(baseMint, marketSigner, true),
    marketSigner,
    baseMint
  );
 
  // Quote vault
  const createQuoteVault = await createAssociatedTokenAccountInstruction(
    feePayer,
    await getAssociatedTokenAddress(quoteMint, marketSigner, true),
    marketSigner,
    quoteMint
  );
 
  const createMarket = new createMarketInstruction({
    signerNonce: new BN(marketSignerNonce),
    minBaseOrderSize: new BN(minBaseOrderSize),
    tickSize: new BN(1),
    crankerReward: new BN(crankerReward),
    baseCurrencyMultiplier: new BN(1),
    quoteCurrencyMultiplier: new BN(Math.pow(10, 6)),
  }).getInstruction(
    DEX_ID,
    marketPubkey,
    new PublicKey("CzjQgYVQ76eGVLJtwRsGGeZJCGUKm3nJNzqLov96KpPg"), // orderbook
    // aaobSigners[3].publicKey,
    await getAssociatedTokenAddress(baseMint, marketSigner, true),
    await getAssociatedTokenAddress(quoteMint, marketSigner, true),
    marketAdmin,
    new PublicKey("DPiHpGUcvBUrk7dCmYnAw7bvD7uHBBkPFGPh9dFcGDFd"), // queue
    new PublicKey("39CcJ3wgppGAGNo5jxi3BfoWF94EGKhXmDwbyEqy4kck"), // asks
    new PublicKey("2D3YH2RLR2gxEXt23EuDr9sVk3sWQWViWpjNwsLDuAzJ"), // bids
    // aaobSigners[0].publicKey,
    // aaobSigners[1].publicKey,
    // aaobSigners[2].publicKey,
    metadataAccount
  );
 
  return [
    // [[marketAccount], [createMarketAccount]],
    // [aaobSigners, aaobInstructions],
    [[], [createBaseVault, createQuoteVault, createMarket]],
  ];
};
 
/**
 *
 * @param market Market object on which the order is placed
 * @param side The side of the order (Bid or Ask)
 * @param limitPrice The limit price (UI limit price not FP32)
 * @param size The size of the order (raw ammount i.e with decimals)
 * @param type The order type
 * @param selfTradeBehaviour The self trade behavior
 * @param ownerTokenAccount The token account from which token will be debited
 * @param owner The user placing the address
 * @param clientOrderId Optional client order ID
 * @param discountTokenAccount Optional SRM token account
 * @returns
 */
export const placeOrder = async (
  market: Market,
  side: Side,
  limitPrice: number,
  size: number,
  type: OrderType,
  selfTradeBehaviour: SelfTradeBehavior,
  ownerTokenAccount: PublicKey,
  owner: PublicKey,
  clientOrderId?: BN,
  discountTokenAccount?: PublicKey,
  maxBaseQty?: BN,
  maxQuoteQty?: BN
) => {
  const [userAccount] = await PublicKey.findProgramAddress(
    [market.address.toBuffer(), owner.toBuffer()],
    DEX_ID
  );
 
  // Uncomment for mainnet
  // if (!discountTokenAccount) {
  //   discountTokenAccount = await findAssociatedTokenAddress(owner, SRM_MINT);
  // }
 
  Iif (!clientOrderId) {
    clientOrderId = new BN(crypto.randomBytes(16));
  }
 
  const priceFp32 = computeFp32Price(market, limitPrice);
 
  const instruction = new newOrderInstruction({
    side: side as number,
    limitPrice: priceFp32,
    maxBaseQty:
      maxBaseQty || new BN(size * market.baseCurrencyMultiplier.toNumber()),
    maxQuoteQty: maxQuoteQty || new BN(U64_MAX),
    orderType: type,
    selfTradeBehavior: selfTradeBehaviour,
    matchLimit: new BN(Number.MAX_SAFE_INTEGER),
    clientOrderId,
    hasDiscountTokenAccount: discountTokenAccount === undefined ? 0 : 1, // TODO Change
  }).getInstruction(
    DEX_ID,
    TOKEN_PROGRAM_ID,
    SystemProgram.programId,
    market.address,
    market.orderbookAddress,
    market.eventQueueAddress,
    market.bidsAddress,
    market.asksAddress,
    market.baseVault,
    market.quoteVault,
    userAccount,
    ownerTokenAccount,
    owner,
    discountTokenAccount
  );
 
  return instruction;
};
 
/**
 *
 * @param market  Market object on which the order is canceled
 * @param owner The owner of the order being cancelled
 * @param orderId The order ID
 * @param orderIndex The index of the order in the user account orders list
 * @param clientOrderId Optional client order ID
 * @returns
 */
export const cancelOrder = async (
  market: Market,
  owner: PublicKey,
  orderId: BN,
  orderIndex?: BN,
  clientOrderId?: BN
) => {
  const [userAccount] = await PublicKey.findProgramAddress(
    [market.address.toBuffer(), owner.toBuffer()],
    DEX_ID
  );
 
  const instruction = new cancelOrderInstruction({
    orderId: clientOrderId ? clientOrderId : orderId,
    orderIndex: orderIndex ? orderIndex : new BN(0),
    isClientId: clientOrderId ? 1 : 0,
  }).getInstruction(
    DEX_ID,
    market.address,
    market.orderbookAddress,
    market.eventQueueAddress,
    market.bidsAddress,
    market.asksAddress,
    userAccount,
    owner
  );
 
  return instruction;
};
 
/**
 *
 * @param market Market object on which the user account is created
 * @param owner The owner of the user account
 * @param maxOrders The max capacity of orders
 * @param feePayer The fee payer of the transaction
 * @returns
 */
export const initializeAccount = async (
  market: PublicKey,
  owner: PublicKey,
  maxOrders = 20,
  feePayer?: PublicKey
) => {
  const [userAccount] = await PublicKey.findProgramAddress(
    [market.toBuffer(), owner.toBuffer()],
    DEX_ID
  );
 
  const instruction = new initializeAccountInstruction({
    market: market.toBuffer(),
    maxOrders: new BN(maxOrders),
  }).getInstruction(
    DEX_ID,
    SystemProgram.programId,
    userAccount,
    owner,
    feePayer || owner
  );
 
  return instruction;
};
 
/**
 *
 * @param market Market object on which funds are settled
 * @param owner The user settling their funds
 * @param destinationBaseAccount The user base token account
 * @param destinationQuoteAccount The user quote token account
 * @returns
 */
export const settle = async (
  market: Market,
  owner: PublicKey,
  destinationBaseAccount: PublicKey,
  destinationQuoteAccount: PublicKey
) => {
  const [marketSigner] = await PublicKey.findProgramAddress(
    [market.address.toBuffer()],
    DEX_ID
  );
 
  const [userAccount] = await PublicKey.findProgramAddress(
    [market.address.toBuffer(), owner.toBuffer()],
    DEX_ID
  );
 
  const instruction = new settleInstruction().getInstruction(
    DEX_ID,
    TOKEN_PROGRAM_ID,
    market.address,
    market.baseVault,
    market.quoteVault,
    marketSigner,
    userAccount,
    owner,
    destinationBaseAccount,
    destinationQuoteAccount
  );
 
  return instruction;
};
 
/**
 *
 * @param market Market object on which events are consumed
 * @param rewardTarget The cranker rewards target
 * @param userAccounts The user accounts
 * @param maxIterations
 * @param noOpErr
 * @returns
 */
export const consumeEvents = async (
  market: Market,
  rewardTarget: PublicKey,
  userAccounts: PublicKey[],
  maxIterations: BN,
  noOpErr: BN
) => {
  const instruction = new consumeEventsInstruction({
    maxIterations,
    noOpErr,
  }).getInstruction(
    DEX_ID,
    market.address,
    market.orderbookAddress,
    market.eventQueueAddress,
    rewardTarget,
    userAccounts
      .map((e) => e.toBuffer())
      .sort(Buffer.compare)
      .map((e) => new PublicKey(e))
  );
 
  return instruction;
};
 
export const closeAccount = async (market: PublicKey, owner: PublicKey) => {
  const [userAccount] = await PublicKey.findProgramAddress(
    [market.toBuffer(), owner.toBuffer()],
    DEX_ID
  );
 
  const instruction = new closeAccountInstruction().getInstruction(
    DEX_ID,
    userAccount,
    owner,
    owner
  );
 
  return instruction;
};
 
export const swap = async (
  market: Market,
  side: Side,
  minOutputQuantity: number,
  inputQuantity: number,
  selfTradeBehaviour: SelfTradeBehavior,
  ownerBaseTokenAccount: PublicKey,
  ownerQuoteTokenAccount: PublicKey,
  owner: PublicKey,
  discountTokenAccount?: PublicKey,
  referralFeeAccount?: PublicKey
) => {
  // Market signer
  const [marketSigner] = await PublicKey.findProgramAddress(
    [market.address.toBuffer()],
    DEX_ID
  );
 
  // Uncomment for mainnet
  // if (!discountTokenAccount) {
  //   discountTokenAccount = await findAssociatedTokenAddress(owner, SRM_MINT);
  // }
 
  const instruction = new swapInstruction({
    side: side as number,
    baseQty:
      side === Side.Bid ? new BN(minOutputQuantity) : new BN(inputQuantity),
    quoteQty:
      side === Side.Bid ? new BN(inputQuantity) : new BN(minOutputQuantity),
    matchLimit: new BN(Number.MAX_SAFE_INTEGER), // TODO Change
    hasDiscountTokenAccount: Number(discountTokenAccount !== undefined),
  }).getInstruction(
    DEX_ID,
    TOKEN_PROGRAM_ID,
    SystemProgram.programId,
    market.address,
    market.orderbookAddress,
    market.eventQueueAddress,
    market.bidsAddress,
    market.asksAddress,
    market.baseVault,
    market.quoteVault,
    marketSigner,
    ownerBaseTokenAccount,
    ownerQuoteTokenAccount,
    owner,
    discountTokenAccount,
    referralFeeAccount
  );
 
  return instruction;
};
 
export const closeMarket = async (market: Market, target: PublicKey) => {
  // Market signer
  const [marketSigner] = await PublicKey.findProgramAddress(
    [market.address.toBuffer()],
    DEX_ID
  );
 
  const ix = new closeMarketInstruction().getInstruction(
    DEX_ID,
    market.address,
    market.baseVault,
    market.quoteVault,
    market.orderbookAddress,
    market.eventQueueAddress,
    market.bidsAddress,
    market.asksAddress,
    market.marketAdmin,
    target,
    marketSigner,
    TOKEN_PROGRAM_ID
  );
 
  return ix;
};
 
export const sweepFees = async (
  connection: Connection,
  market: Market,
  destination: PublicKey,
  feePayer: PublicKey
) => {
  // Market signer
  const [marketSigner] = await PublicKey.findProgramAddress(
    [market.address.toBuffer()],
    DEX_ID
  );
  // Metadata account
  const creatorTokenAccounts: PublicKey[] = [];
  const tokenIxs: TransactionInstruction[] = [];
  const metadataAccount = await getMetadataKeyFromMint(market.baseMintAddress);
  const info = await connection.getAccountInfo(metadataAccount);
 
  Iif (!!info?.data) {
    const [metadata] = Metadata.fromAccountInfo(info);
    const creators = metadata?.data?.creators;
    Iif (creators) {
      for (let c of creators) {
        const key = await getAssociatedTokenAddress(
          market.quoteMintAddress,
          c.address
        );
        const info = await connection.getAccountInfo(key);
        // Create token acc if does not exist
        Iif (!info?.data) {
          tokenIxs.push(
            createAssociatedTokenAccountInstruction(
              feePayer,
              key,
              c.address,
              market.quoteMintAddress
            )
          );
        }
        creatorTokenAccounts.push(key);
      }
    }
  }
 
  const ix = new sweepFeesInstruction().getInstruction(
    DEX_ID,
    market.address,
    marketSigner,
    market.quoteVault,
    destination,
    TOKEN_PROGRAM_ID,
    metadataAccount,
    creatorTokenAccounts
  );
 
  return [...tokenIxs, ix];
};