Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Xaber20110202 committed Jun 17, 2019
0 parents commit cf6216a
Show file tree
Hide file tree
Showing 65 changed files with 2,657 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.vscode
node_modules
yarn.lock
npm-debug.log
npm-debug.log.*
yarn-error.log
package-lock.json
lib
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 ConsenLabs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# tokenlon-mmsk

See [docs](https://docs.token.im/tokenlon-mmsk/)

copyright© imToken PTE. LTD.
4 changes: 4 additions & 0 deletions app/check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const mmConf = require('./mmConfig')
const mmsk = require('../lib')

mmsk.checkMMSK(mmConf)
18 changes: 18 additions & 0 deletions app/mmConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
EXCHANGE_URL: process.env.EXCHANGE_URL,
WEBSOCKET_URL: process.env.WEBSOCKET_URL,
PROVIDER_URL: process.env.PROVIDER_URL,

WALLET_ADDRESS: process.env.WALLET_ADDRESS,
USE_KEYSTORE: true,
WALLET_KEYSTORE: {},
// WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
MMSK_SERVER_PORT: process.env.MMSK_SERVER_PORT || 80,

USE_ZERORPC: true,
// HTTP_SERVER_ENDPOINT: process.env.HTTP_SERVER_ENDPOINT,
ZERORPC_SERVER_ENDPOINT: process.env.ZERORPC_SERVER_ENDPOINT,
SENTRY_DSN: '',

NODE_ENV: 'PRODUCTION',
}
4 changes: 4 additions & 0 deletions app/start.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const mmConf = require('./mmConfig')
const mmsk = require('../lib')

mmsk.startMMSK(mmConf)
50 changes: 50 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "tokenlon-mmsk",
"version": "0.2.4",
"description": "",
"main": "lib/index.js",
"types": "src/globals.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/consenlabs/tokenlon-mmsk.git"
},
"author": "imToken PTE. LTD.",
"license": "MIT",
"scripts": {
"watch": "tsc -w",
"clean": "rm -rf ./lib",
"build:commonjs": "tsc",
"build": "run-s clean build:commonjs",
"start": "node ./app/start.js",
"check": "node ./app/check.js"
},
"bugs": {
"url": "https://github.com/consenlabs/tokenlon-mmsk/issues"
},
"homepage": "https://github.com/consenlabs/tokenlon-mmsk#readme",
"devDependencies": {
"@types/node": "10.11.5",
"npm-run-all": "4.1.5",
"ts-node": "7.0.1",
"tslint": "5.11.0",
"typescript": "3.1.1"
},
"dependencies": {
"0x.js": "1.0.8",
"@babel/runtime": "7.3.1",
"@sentry/node": "4.5.3",
"axios": "0.18.0",
"babel-polyfill": "6.26.0",
"binance-api-node": "0.8.18",
"keythereum": "1.0.4",
"koa": "2.5.3",
"koa-bodyparser": "4.2.1",
"koa-router": "7.4.0",
"lodash": "4.17.11",
"readline-sync": "1.4.9",
"sockjs-client": "1.3.0",
"stompjs": "2.3.3",
"web3": "1.0.0-beta.37",
"zerorpc": "0.9.8"
}
}
27 changes: 27 additions & 0 deletions src/check/deal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as _ from 'lodash'
import { dealOrder } from '../request/marketMaker'
import { getSupportedTokens } from '../utils/token'

const check = async () => {
try {
const tokenA = getSupportedTokens()[0]
const mockOrder = {
makerToken: tokenA.symbol,
takerToken: tokenA.opposites[0],
makerTokenAmount: 40.19308759,
takerTokenAmount: 0.3,
timestamp: 1551855180,
quoteId: 'assdcjfsdhfdfoesfhafh',
}
const resp = await dealOrder(mockOrder)
if (resp.result !== false) {
return `deal an non-exist order ${JSON.stringify(mockOrder)} but got result not false`
}
} catch (e) {
return `deal API request error ${e.message}`
}

return ''
}

export default check
46 changes: 46 additions & 0 deletions src/check/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import 'babel-polyfill'
import { ConfigForStart } from '../types'
import { getWallet } from '../utils/wallet'
import { startUpdater } from '../utils/intervalUpdater'
import { setConfig } from '../config'
import checkPairs from './pairs'
import checkIndicativePrice from './indicativePrice'
import checkPrice from './price'
import checkDeal from './deal'

export const checkMMSK = async (config: ConfigForStart) => {
const arr = [
{
title: 'checking Pairs API',
check: checkPairs,
},
{
title: 'checking indicativePrice API',
check: checkIndicativePrice,
},
{
title: 'checking price API',
check: checkPrice,
},
{
title: 'checking deal API',
check: checkDeal,
},
]

setConfig(config)

const wallet = getWallet()
await startUpdater(wallet)

for (let i = 0; i < arr.length; i += 1) {
const item = arr[i]
console.log(item.title)
const errorMsg = await item.check()
console.log(errorMsg ? `check failed: ${errorMsg}` : 'OK')
if (i === 0 && errorMsg) break
console.log('\n')
}

process.exit(0)
}
7 changes: 7 additions & 0 deletions src/check/indicativePrice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { priceCheckHelper } from './priceCheckHelper'
import { getIndicativePrice } from '../request/marketMaker'

export default async () => {
const isIndicative = true
return priceCheckHelper(getIndicativePrice, isIndicative)
}
28 changes: 28 additions & 0 deletions src/check/pairs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as _ from 'lodash'
import { getPairs } from '../request/marketMaker'
import { getSupportedTokens } from '../utils/token'

const check = async () => {
let pairsFromMM = []

try {
pairsFromMM = await getPairs()
if (!pairsFromMM) return 'pairs API no reponse'
if (!pairsFromMM.length) return 'pairs API token array is empty'
if (!pairsFromMM.every(pairStr => pairStr.indexOf('/') !== -1)) return 'pairs API pair str must be TokenA/TokenB'
} catch (e) {
return `pairs API request error ${e.message}`
}

try {
const supportedTokenList = getSupportedTokens()
if (supportedTokenList.length === 0) return 'intergrated supported token list is empty'
if (supportedTokenList.length === 1) return `intergrated supported token list only has one token trade ${supportedTokenList[0].symbol}-${supportedTokenList[0].opposites[0]}`
} catch (e) {
return `imToken getTokenList error ${e.message}`
}

return ''
}

export default check
7 changes: 7 additions & 0 deletions src/check/price.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { priceCheckHelper } from './priceCheckHelper'
import { getPrice } from '../request/marketMaker'

export default async () => {
const isIndicative = false
return priceCheckHelper(getPrice, isIndicative)
}
89 changes: 89 additions & 0 deletions src/check/priceCheckHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import * as _ from 'lodash'
import { getSupportedTokens } from '../utils/token'

const checkMinAndMaxAmount = (resp, { base, quote, side }) => {
const { minAmount, maxAmount } = resp
if (minAmount === void 0 || maxAmount === void 0) return `${base}-${quote} ${side} trade must have minAmount and maxAmount field`
if (minAmount > maxAmount) return `${base}-${quote} ${side} trade's minAmount largerer than maxAmount`
}

const checkBaseQuoteTrade = async (apiFunc, { base, quote }, isIndicative, tokenSupported) => {
const uniqId = 'uniq'
const amountArr = isIndicative ? [undefined, 0, 0.1] : [0.1, 100]

for (let side of ['BUY', 'SELL']) {
for (let item of [{ base, quote }, { base: quote, quote: base }]) {
for (let amount of amountArr) {
const base = item.base
const quote = item.quote
const params = { base, quote, side }
if (amount !== undefined) {
Object.assign(params, { amount })
}
if (!isIndicative) {
Object.assign(params, { uniqId })
}
try {
console.log('params:', JSON.stringify(params))
const resp = await apiFunc(params)
resp.exchangeable = resp.exchangeable || resp.exchangable
console.log('response:', JSON.stringify(resp))

if (!resp.result || !resp.exchangeable) {
// 数量不存在的报价,必须支持
if (tokenSupported && amount === undefined) return `can not support ${base}-${quote} ${side} trade`

// 必须包含 message
if (!resp.message) return `${base}-${quote} ${side} message is needed if result or exchangeable is false`

} else {

if (tokenSupported) {
// 价格不存在问题
if (!resp.price) return `${base}-${quote} ${side} price ${resp.price} incorrect`

// price 接口 必须包含 quoteId 字段
if (!isIndicative && (!resp.quoteId || !_.isString(resp.quoteId))) return `${base}-${quote} ${side} response need an non-empty string quoteId`

// TODO: 价格合理性检查
}
}

// 支持的 token 必须包含最大最小值
if (tokenSupported) {
const minMaxAmountValidateMsg = checkMinAndMaxAmount(resp, { base, quote, side })
if (minMaxAmountValidateMsg) return minMaxAmountValidateMsg
}

} catch (e) {
return `API request ${base}-${quote} ${side} error ${e.message}`
}
}
}
}
}

export const priceCheckHelper = async (apiFunc, isIndicative) => {
const supportedTokens = getSupportedTokens()

// ETH token
const ethToken = supportedTokens.find(t => t.symbol === 'ETH')
let base = ethToken.symbol
let quote = ethToken.opposites[0]

const supportedTokenTradeValidateMsg = await checkBaseQuoteTrade(apiFunc, { base, quote }, isIndicative, true)
if (supportedTokenTradeValidateMsg) return supportedTokenTradeValidateMsg

quote = 'ABCDEFG'
const unsupportedTokenTradeValidateMsg = await checkBaseQuoteTrade(apiFunc, { base, quote }, isIndicative, false)
if (unsupportedTokenTradeValidateMsg) return unsupportedTokenTradeValidateMsg

const otherToken = supportedTokens.find(t => t.symbol !== 'ETH' && t.opposites.length > 1)

if (otherToken) {
base = otherToken.symbol
quote = otherToken.opposites.find(symbol => symbol !== 'ETH')
const twoErc20TokenTradeValidateMsg = await checkBaseQuoteTrade(apiFunc, { base, quote }, isIndicative, true)
if (twoErc20TokenTradeValidateMsg) return twoErc20TokenTradeValidateMsg
}
}
39 changes: 39 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as readlineSync from 'readline-sync'
import * as keythereum from 'keythereum'
import { ConfigForStart } from '../types'

const config = {
EXCHANGE_URL: null,
WEBSOCKET_URL: null,
PROVIDER_URL: null,

WALLET_ADDRESS: null,
WALLET_PRIVATE_KEY: null,
USE_KEYSTORE: true,
WALLET_KEYSTORE: null,
MMSK_SERVER_PORT: null,

USE_ZERORPC: null,
HTTP_SERVER_ENDPOINT: null,
ZERORPC_SERVER_ENDPOINT: null,

NODE_ENV: 'DEVELOPMENT',
SENTRY_DSN: null,
} as ConfigForStart

const setConfig = (conf: ConfigForStart) => {
if (conf.USE_KEYSTORE) {
const KEYSTORE_PASSWORD = readlineSync.question('Please input your keystore\'s password: ', {
hideEchoBack: true,
})
const privateKeyBuf = keythereum.recover(KEYSTORE_PASSWORD, conf.WALLET_KEYSTORE)
const privateKey = privateKeyBuf.toString('hex')
conf.WALLET_PRIVATE_KEY = privateKey
}
return Object.assign(config, conf)
}

export {
config,
setConfig,
}
11 changes: 11 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const ETH_ADDRESS = `0x${'0'.repeat(40)}`

export const FEE_RECIPIENT_ADDRESS = '0xb9e29984fe50602e7a619662ebed4f90d93824c7'

export const REQUEST_TIMEOUT = 10000

export const INTERVAL_UPDAER_TIME = 5 * 60 * 1000

export const MAX_WEBSOCKET_RECONNECT_TRIED_TIMES = 100

export const WEBSOCKET_TRY_CONNECT_INTERVAL = 1000
4 changes: 4 additions & 0 deletions src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module '*.json' {
const value: any
export default value
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { checkMMSK } from './check'
export { startMMSK } from './start'
Loading

0 comments on commit cf6216a

Please sign in to comment.