Code Monkey home page Code Monkey logo

serum-js's Introduction

npm (scoped) Build Status

Moved

This repository has been moved to the serum-ts monorepo.

Serum JS Client Library

JavaScript client library for interacting with the Project Serum DEX.

Installation

Using npm:

npm install @solana/web3.js @project-serum/serum

Using yarn:

yarn add @solana/web3.js @project-serum/serum

Usage

import { Account, Connection, PublicKey } from '@solana/web3.js';
import { Market } from '@project-serum/serum';

let connection = new Connection('https://testnet.solana.com');
let marketAddress = new PublicKey('...');
let market = await Market.load(connection, marketAddress);

// Fetching orderbooks
let bids = await market.loadBids(connection);
let asks = await market.loadAsks(connection);
// L2 orderbook data
for (let [price, size] of bids.getL2(20)) {
  console.log(price, size);
}
// Full orderbook data
for (let order of asks) {
  console.log(
    order.orderId,
    order.price,
    order.size,
    order.side, // 'buy' or 'sell'
  );
}

// Placing orders
let owner = new Account('...');
let payer = new PublicKey('...'); // spl-token account
await market.placeOrder(connection, {
  owner,
  payer,
  side: 'buy', // 'buy' or 'sell'
  price: 123.45,
  size: 17.0,
  orderType: 'limit', // 'limit', 'ioc', 'postOnly'
});

// Retrieving open orders by owner
let myOrders = await market.loadOrdersForOwner(connection, owner.publicKey);

// Cancelling orders
for (let order of myOrders) {
  await market.cancelOrder(connection, owner, order);
}

// Retrieving fills
for (let fill of await market.loadFills(connection)) {
  console.log(
    fill.orderId,
    fill.price,
    fill.size,
    fill.side,
  );
}

// Settle funds
for (let openOrders of await market.findOpenOrdersAccountsForOwner(
  connection,
  owner.publicKey,
)) {
  if (openOrders.baseTokenFree > 0 || openOrders.quoteTokenFree > 0) {
    // spl-token accounts to which to send the proceeds from trades
    let baseTokenAccount = new PublicKey('...');
    let quoteTokenAccount = new PublicKey('...');

    await market.settleFunds(
      connection,
      owner,
      openOrders,
      baseTokenAccount,
      quoteTokenAccount,
    );
  }
}

serum-js's People

Contributors

armaniferrante avatar fallingoak avatar garywang avatar leofisg avatar michaelhly avatar nathanielparke avatar nishadsingh1 avatar philippe-ftx avatar thaaddeus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serum-js's Issues

What should we put for the market address public key?

In the README.md it said to put in the public key of the market, I am wondering when should we put in exactly?

I have tried:

  let marketAddress = new PublicKey('9o1FisE366msTQcEvXapyMorTLmvezrxSD8DnM5e5XKw');

According to here

But this doesn't seem to work, it's reporting:

$ node index.js 
(node:15774) ExperimentalWarning: The ESM module loader is experimental.
(node:15774) UnhandledPromiseRejectionWarning: Error: Address not owned by program
    at Function.load (/Users/wge/Documents/serum_exp/node_modules/@project-serum/serum/lib/market.js:53:19)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async main (file:///Users/wge/Documents/serum_exp/index.js:9:16)
(node:15774) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15774) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Provide a centralised conversion from binary to language specific format

Currently, a huge part of the js-serum client codebase is doing binary parsing (which is returned by the Solana client), i.e. from a binary format to JS class. If someone is to build another client say, in Python, the developer needs to implement similar parsing logic to convert from a binary format into the language native format which is super error-prone and tedious.

It will be great if the conversion from binary format to a language-specific format can be done once across various language. The team can have a conversion from binary to, say protobuf or json. So it will be easier for different language client to be built.

Abstract away the Solana primitives

Currently, the serum-js library still requires the developers to know the abstraction from @solana/web3.js, specifically Account, Connection and PublicKey.

However, it will be nicer if the developer doesn't need to know about these primitives and only interact with serum-js. And I think this should be quite easy to abstract away.

Question on how to create a 'new Account()' from the id.json

Hi,

I'd like to get all my open orders from a market on Serum.

I've been able to connect and list the bids/asks, but now I want to see my open orders.

I do have an open order on the FTT/USDC market but my code returns an empty array.

I've created a wallet using sollet.io and placed several orders that have filled using the Dex UI.

So working backwards from there, I've created the ~/.config/solana/id.json file by using 'solana-keygen recover' and enter the sollet.io wallet seed phrase and password.

Then use the Array from id.json as input to 'new Account()', but my actual open orders are not listed in the output (empty array of results when there is one open order on the dex)

I hope I explained that OK.

Where am I going wrong?

Here's some code I'm hacking around with:

import { Connection, Account } from "@solana/web3.js"
import { MARKETS, Market } from "@project-serum/serum"
import * as fs from "fs"

// create the ~/.config/solana/id.json by using 'solana-keygen recover' and enter the sollet.io wallet seed phrase and password
const solanaId = JSON.parse(fs.readFileSync("/home/rudi/.config/solana/id.json", { encoding: "UTF-8" }))
// console.log(solanaId)

const fttUsdc = MARKETS.filter((item: any) => item.name === "FTT/USDC")[0]
// console.log(fttUsdc)

let connection = new Connection("https://api.mainnet-beta.solana.com/")

let owner = new Account(solanaId)

async function main() {
  let market = await Market.load(connection, fttUsdc.address, undefined, fttUsdc.programId)
  // console.log(market)

  // Retrieving open orders by owner
  // console.log(owner.publicKey, owner.secretKey)
  let myOrders = await market.loadOrdersForOwner(connection, owner.publicKey)
  console.log(myOrders)
}

main()
  .then((res) => console.log(res))
  .catch((err) => console.log(err))

Here's a screen cap of the open order under my account on the dex:

Screenshot from 2020-09-21 14-24-50

Market addresses and DEX_PROGRAM_ID. for testnet/devnet

Is it possible for us to use testnet/devnet for dev purposes? In this case, are there DEX_PROGRAM_ID and markets addresses deployed there? I suppose that the market addresses are also attached to SPL mint addresses. Is it also possible to mint coins on those SPL programs?

Fill event price logic

In market.ts there is a quite a bit of logic that retrieves the price from an event

price = divideBnToNumber(

is it basically equivalent to priceLotsToNumber(event.orderId.ushrn(64)) or we should not rely on order id encoding to retrieve the order price? I'm asking as already using that logic to retreive price for request queue items and not 100% sure if that is correct or not.

...also is it necessary to check event.nativeQuantityPaid.gtn(0) at

(event) => event.eventFlags.fill && event.nativeQuantityPaid.gtn(0),

can there be a fill that has nativeQuantityPaid set to 0?
Thanks

`payer` refer to different things in `serum-js` and `crank`

In serum-js README the payer is the public key address that holds the SPL token (in the case of bid order placement it will hold quote token), however, in crank the payer means the wallet account. See here.

My understanding is based on Account (solana-web3 type) generally correspond to Keypair(solana-rust-sdk).
And PublicKey (solana-web3 type) correspond to Pubkey (solana-rust-sdk).

It will be nice if the naming can be unified to avoid some confusion.

I have an issue with fetching market data.

I run the following code:

import solanaWeb3 from '@solana/web3.js';
import serum from '@project-serum/serum';
const { Market } = serum;

let url;
url = 'https://api.mainnet-beta.solana.com';
//url = 'http://localhost:8899';
const connection = new solanaWeb3.Connection(url);


let marketAddress = new solanaWeb3.PublicKey('BJ3jrUzddfuSrZHXSCxMUUQsjKEyLmuuyZebkcaFp2fg'); //
let market = await Market.load(connection, marketAddress);

// Fetching orderbooks
let bids = await market.loadBids(connection);
let asks = await market.loadAsks(connection);

// L2 orderbook data
for (let [price, size] of bids.getL2(20)) {
  console.log(price, size);
}
// Full orderbook data
for (let order of asks) {
  console.log(
    order.orderId,
    order.price,
    order.size,
    order.side, // 'buy' or 'sell'
  );
}

Error log:

node_modules/@solana/web3.js/lib/index.cjs.js:103
      return this._bn.eq(publicKey._bn);
                                   ^

TypeError: Cannot read property '_bn' of undefined
    at PublicKey.equals (/Users/artem/Repos/node-dexes/node_modules/@solana/web3.js/lib/index.cjs.js:103:36)
    at Function.load (/Users/artem/Repos/node-dexes/node_modules/@project-serum/serum/lib/market.js:88:20)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async file:///Users/artem/Repos/node-dexes/src/serum.js:20:14

how much time it need to take for order show after the order placed?

i have tested the market.loadOrdersForOwner and i use the postonly order.it seems that the order need about more than 15s after the order place by placeorder function.is the sol a very fast way trade?do you know the excatly time that the order to be show.and what is the meaning of cacheDurationMs in the market.loadOrdersForOwner?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.