reformat code
This commit is contained in:
parent
95cd194db2
commit
32b0e9d01e
@ -113,7 +113,7 @@ class LoginController extends BaseController {
|
||||
const user = await Account.insertOrUpdate({ plat: channel, openId }, data)
|
||||
const { unionAccount, walletUser } = await parseBindAccount(account, channel, user)
|
||||
if (plat.afterLogin) {
|
||||
await plat.afterLogin(user);
|
||||
await plat.afterLogin(user)
|
||||
}
|
||||
const ztoken = await res.jwtSign({
|
||||
id: walletUser.id,
|
||||
|
@ -122,14 +122,14 @@ class OkxController extends BaseController {
|
||||
@router('post /wallet/okx/sendtran')
|
||||
async sendWalletTran(req, res) {
|
||||
let { data } = req.params
|
||||
let user = req.user;
|
||||
let user = req.user
|
||||
let record = await Wallet.findOne({ account: user.id })
|
||||
if (!record || !record.address) {
|
||||
throw new ZError(11, 'no wallet found')
|
||||
}
|
||||
data.chainId = data.chainId || DEFAULT_CHAINID
|
||||
data.walletId = record.id;
|
||||
console.log('send trans: ' + JSON.stringify(data));
|
||||
data.walletId = record.id
|
||||
console.log('send trans: ' + JSON.stringify(data))
|
||||
let result = await sendTran(data)
|
||||
if (result.status !== 200) {
|
||||
throw new ZError(result.status, result.statusText)
|
||||
@ -140,16 +140,19 @@ class OkxController extends BaseController {
|
||||
if (result.data?.data) {
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await TranRecord.insertOrUpdate({
|
||||
await TranRecord.insertOrUpdate(
|
||||
{
|
||||
transactionHash: data.txHash,
|
||||
}, {
|
||||
},
|
||||
{
|
||||
okxOrderId: result.data.data.orderId,
|
||||
})
|
||||
},
|
||||
)
|
||||
logger.log(`success update log: ${data.txHash}`)
|
||||
} catch (err) {
|
||||
logger.log(`error update log: ${data.txHash} with error: ${err}`)
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
return { txHash: data.txHash }
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ class RelayController extends BaseController {
|
||||
@role(ROLE_ANON)
|
||||
@router('post /wallet/relay/prepare')
|
||||
async prepareClient(req, res) {
|
||||
let {msg, address, signature} = req.params;
|
||||
let { msg, address, signature } = req.params
|
||||
if (!msg || !address || !signature) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
@ -29,11 +29,11 @@ class RelayController extends BaseController {
|
||||
@role(ROLE_SESSION)
|
||||
@router('post /wallet/relay/putdata')
|
||||
async uploadData(req, res) {
|
||||
let {data, type, session_id} = req.params;
|
||||
let { data, type, session_id } = req.params
|
||||
if (type == undefined || !data) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
type = parseInt(type);
|
||||
type = parseInt(type)
|
||||
let record = new RelayRecord({ sid: session_id, type, data })
|
||||
await record.save()
|
||||
return { id: record.id }
|
||||
@ -42,27 +42,26 @@ class RelayController extends BaseController {
|
||||
@role(ROLE_SESSION)
|
||||
@router('post /wallet/relay/updata')
|
||||
async updateData(req, res) {
|
||||
let {data, id} = req.params;
|
||||
let { data, id } = req.params
|
||||
if (!id || !data) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
let record = await RelayRecord.findById(id);
|
||||
record.status = RelayStatusEnum.RESOLVED;
|
||||
record.resp = data;
|
||||
let record = await RelayRecord.findById(id)
|
||||
record.status = RelayStatusEnum.RESOLVED
|
||||
record.resp = data
|
||||
await record.save()
|
||||
return { id: record.id }
|
||||
}
|
||||
|
||||
|
||||
@role(ROLE_SESSION)
|
||||
@router('post /wallet/relay/getlast')
|
||||
async fetchLast(req, res) {
|
||||
let { session_id, type } = req.params;
|
||||
let { session_id, type } = req.params
|
||||
if (type == undefined) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
type = parseInt(type);
|
||||
let record = await RelayRecord.findLastRecord(session_id, type);
|
||||
type = parseInt(type)
|
||||
let record = await RelayRecord.findLastRecord(session_id, type)
|
||||
if (!record) {
|
||||
throw new ZError(11, 'record not found')
|
||||
}
|
||||
@ -72,15 +71,14 @@ class RelayController extends BaseController {
|
||||
@role(ROLE_SESSION)
|
||||
@router('post /wallet/relay/getdata')
|
||||
async fetchData(req, res) {
|
||||
let { id } = req.params;
|
||||
let { id } = req.params
|
||||
if (!id) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
let record = await RelayRecord.findById(id);
|
||||
let record = await RelayRecord.findById(id)
|
||||
if (!record) {
|
||||
throw new ZError(11, 'record not found')
|
||||
}
|
||||
return { id: record.id, data: record.data, resp: record.resp, status: record.status }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -23,7 +23,7 @@ class SignController extends BaseController {
|
||||
const { signature, message } = req.params
|
||||
checkParamsNeeded(signature, message)
|
||||
if (!message.nonce) {
|
||||
throw new ZError(11, 'Invalid nonce');
|
||||
throw new ZError(11, 'Invalid nonce')
|
||||
}
|
||||
let record = await NonceRecord.findById(message.nonce)
|
||||
if (!record || record.status !== 0) {
|
||||
@ -34,9 +34,9 @@ class SignController extends BaseController {
|
||||
}
|
||||
record.status = 1
|
||||
await record.save()
|
||||
const msgSign = new SiweMessage(message);
|
||||
const msgSign = new SiweMessage(message)
|
||||
try {
|
||||
await msgSign.verify({ signature, nonce: record.id });
|
||||
await msgSign.verify({ signature, nonce: record.id })
|
||||
} catch (e) {
|
||||
throw new ZError(14, 'signature invalid')
|
||||
}
|
||||
|
@ -18,9 +18,9 @@ const bindOkx = async (record: any) => {
|
||||
console.log('bindOkx: ', record.address)
|
||||
let res = await createWallet({
|
||||
addresses: [{ chainId: DEFAULT_CHAINID, address: record.address }],
|
||||
walletId: record.id
|
||||
walletId: record.id,
|
||||
})
|
||||
console.log('bind result: '+ JSON.stringify(res.data));
|
||||
console.log('bind result: ' + JSON.stringify(res.data))
|
||||
if (!res.data.code || res.data.code == 81102) {
|
||||
record.toOkx = true
|
||||
await record.save()
|
||||
@ -43,7 +43,7 @@ class WalletController extends BaseController {
|
||||
if (!record.toOkx && record.address) {
|
||||
setImmediate(async () => {
|
||||
await bindOkx(record)
|
||||
});
|
||||
})
|
||||
}
|
||||
Object.assign(data, record.toJson())
|
||||
return data
|
||||
@ -91,7 +91,7 @@ class WalletController extends BaseController {
|
||||
if (!record.toOkx && record.address) {
|
||||
setImmediate(async () => {
|
||||
await bindOkx(record)
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
return {}
|
||||
|
@ -1,4 +1,4 @@
|
||||
export enum RelayTypeEnum {
|
||||
TO_WALLET = 0,
|
||||
FROM_WALLET = 1
|
||||
FROM_WALLET = 1,
|
||||
}
|
||||
|
@ -18,4 +18,3 @@ class NonceRecordClass extends BaseModule {
|
||||
}
|
||||
|
||||
export const NonceRecord = getModelForClass(NonceRecordClass, { existingConnection: NonceRecordClass['db'] })
|
||||
|
||||
|
@ -43,4 +43,3 @@ class RelayRecordClass extends BaseModule {
|
||||
}
|
||||
|
||||
export const RelayRecord = getModelForClass(RelayRecordClass, { existingConnection: RelayRecordClass['db'] })
|
||||
|
||||
|
@ -18,7 +18,7 @@ class RelaySessionClass extends BaseModule {
|
||||
public expired: number
|
||||
|
||||
public async refreshExpired() {
|
||||
this.expired = Date.now() + DEFAULT_EXPIRED;
|
||||
this.expired = Date.now() + DEFAULT_EXPIRED
|
||||
}
|
||||
|
||||
public static async removeExpired() {
|
||||
@ -27,4 +27,3 @@ class RelaySessionClass extends BaseModule {
|
||||
}
|
||||
|
||||
export const RelaySession = getModelForClass(RelaySessionClass, { existingConnection: RelaySessionClass['db'] })
|
||||
|
||||
|
@ -1,19 +1,19 @@
|
||||
import { checkParamsNeeded } from 'utils/net.util'
|
||||
import { IPlat } from './IPlat'
|
||||
import { ZError } from 'common/ZError';
|
||||
import { NonceRecord } from 'modules/NonceRecord';
|
||||
import { SiweMessage } from 'siwe';
|
||||
import { ZError } from 'common/ZError'
|
||||
import { NonceRecord } from 'modules/NonceRecord'
|
||||
import { SiweMessage } from 'siwe'
|
||||
import { DocumentType } from '@typegoose/typegoose'
|
||||
import { AccountClass } from 'modules/Account'
|
||||
import { Wallet } from 'modules/Wallet';
|
||||
import { Wallet } from 'modules/Wallet'
|
||||
|
||||
export class PlatExternalWallet implements IPlat {
|
||||
async verifyToken(req: any): Promise<any> {
|
||||
// here code is signature
|
||||
let { code, message } = req.params
|
||||
checkParamsNeeded(code, message);
|
||||
checkParamsNeeded(code, message)
|
||||
if (!message.nonce) {
|
||||
throw new ZError(11, 'Invalid nonce');
|
||||
throw new ZError(11, 'Invalid nonce')
|
||||
}
|
||||
|
||||
let record = await NonceRecord.findById(message.nonce)
|
||||
@ -25,9 +25,9 @@ export class PlatExternalWallet implements IPlat {
|
||||
}
|
||||
record.status = 1
|
||||
await record.save()
|
||||
const msgSign = new SiweMessage(message);
|
||||
const msgSign = new SiweMessage(message)
|
||||
try {
|
||||
await msgSign.verify({ signature: code, nonce: record.id });
|
||||
await msgSign.verify({ signature: code, nonce: record.id })
|
||||
} catch (e) {
|
||||
throw new ZError(14, 'signature invalid')
|
||||
}
|
||||
|
@ -62,10 +62,10 @@ const apiAuthPlugin: FastifyPluginAsync<ApiAuthOptions> = async function (fastif
|
||||
if (!session) {
|
||||
return reply.send({ errcode: 10, errmsg: 'need login' })
|
||||
}
|
||||
session.refreshExpired();
|
||||
await session.save();
|
||||
request.params['session_id'] = session.id;
|
||||
request.params['session_address'] = session.address;
|
||||
session.refreshExpired()
|
||||
await session.save()
|
||||
request.params['session_id'] = session.id
|
||||
request.params['session_address'] = session.address
|
||||
} catch (err) {
|
||||
return reply.send({ errcode: 401, errmsg: 'need auth' })
|
||||
}
|
||||
|
@ -1,37 +1,26 @@
|
||||
import {
|
||||
FastifyInstance,
|
||||
FastifyPluginAsync,
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
} from "fastify";
|
||||
import fastifyPlugin from "fastify-plugin";
|
||||
import { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import fastifyPlugin from 'fastify-plugin'
|
||||
|
||||
/**
|
||||
* 将post 和 get 的参数统一到 req.params
|
||||
*/
|
||||
declare module "fastify" {
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
zReqParser: (request: FastifyRequest, reply: FastifyReply) => {};
|
||||
zReqParser: (request: FastifyRequest, reply: FastifyReply) => {}
|
||||
}
|
||||
}
|
||||
const zReqParserPlugin: FastifyPluginAsync = async function (
|
||||
fastify: FastifyInstance,
|
||||
options?: any
|
||||
) {
|
||||
fastify.addHook(
|
||||
"preValidation",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
let params = request.params || {};
|
||||
const zReqParserPlugin: FastifyPluginAsync = async function (fastify: FastifyInstance, options?: any) {
|
||||
fastify.addHook('preValidation', async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
let params = request.params || {}
|
||||
if (request.query) {
|
||||
Object.assign(params, request.query);
|
||||
Object.assign(params, request.query)
|
||||
}
|
||||
if (request.body) {
|
||||
Object.assign(params, request.body);
|
||||
Object.assign(params, request.body)
|
||||
}
|
||||
request.params = params;
|
||||
request.params = params
|
||||
})
|
||||
return
|
||||
}
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
export default fastifyPlugin(zReqParserPlugin, "4.x");
|
||||
export default fastifyPlugin(zReqParserPlugin, '4.x')
|
||||
|
@ -1,73 +1,62 @@
|
||||
import {
|
||||
FastifyInstance,
|
||||
FastifyPluginAsync,
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
} from "fastify";
|
||||
import fastifyPlugin from "fastify-plugin";
|
||||
import { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import fastifyPlugin from 'fastify-plugin'
|
||||
|
||||
const getTokenFromHeader = function (request) {
|
||||
let token: string | undefined;
|
||||
let token: string | undefined
|
||||
if (request.headers && request.headers.authorization) {
|
||||
const parts = request.headers.authorization.split(" ");
|
||||
const parts = request.headers.authorization.split(' ')
|
||||
if (parts.length === 2) {
|
||||
const scheme = parts[0];
|
||||
const scheme = parts[0]
|
||||
if (/^Bearer$/i.test(scheme)) {
|
||||
token = parts[1];
|
||||
token = parts[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return token;
|
||||
};
|
||||
return token
|
||||
}
|
||||
const getTokenFromCookie = function (request) {
|
||||
let token: string | undefined;
|
||||
let token: string | undefined
|
||||
if (request.cookies) {
|
||||
if (request.cookies["token"]) {
|
||||
token = request.cookies["token"];
|
||||
if (request.cookies['token']) {
|
||||
token = request.cookies['token']
|
||||
}
|
||||
}
|
||||
return token;
|
||||
};
|
||||
return token
|
||||
}
|
||||
|
||||
const getTokenFromParams = function (request) {
|
||||
let token: string | undefined;
|
||||
token = request.params && request.params.token;
|
||||
return token;
|
||||
};
|
||||
let token: string | undefined
|
||||
token = request.params && request.params.token
|
||||
return token
|
||||
}
|
||||
|
||||
const getTokenFromQuery = function (request) {
|
||||
let token: string | undefined;
|
||||
token = request.query && request.query.token;
|
||||
return token;
|
||||
};
|
||||
let token: string | undefined
|
||||
token = request.query && request.query.token
|
||||
return token
|
||||
}
|
||||
|
||||
const getTokenFromBody = function (request) {
|
||||
let token: string | undefined;
|
||||
token = request.body && request.body.token;
|
||||
return token;
|
||||
};
|
||||
let token: string | undefined
|
||||
token = request.body && request.body.token
|
||||
return token
|
||||
}
|
||||
|
||||
const zTokenParserPlugin: FastifyPluginAsync = async function (
|
||||
fastify: FastifyInstance,
|
||||
options?: any
|
||||
) {
|
||||
fastify.addHook(
|
||||
"preValidation",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
request["token"] =
|
||||
const zTokenParserPlugin: FastifyPluginAsync = async function (fastify: FastifyInstance, options?: any) {
|
||||
fastify.addHook('preValidation', async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
request['token'] =
|
||||
getTokenFromHeader(request) ||
|
||||
getTokenFromCookie(request) ||
|
||||
getTokenFromParams(request) ||
|
||||
getTokenFromQuery(request) ||
|
||||
getTokenFromBody(request);
|
||||
getTokenFromBody(request)
|
||||
})
|
||||
return
|
||||
}
|
||||
);
|
||||
return;
|
||||
};
|
||||
/**
|
||||
* 依次从request的header, cookie, params, query和body中获取token, 加入到request.token中
|
||||
* header中的字段key为authorization, 格式为 Bearer xxxx
|
||||
* 其他位置的key都为 token
|
||||
*/
|
||||
|
||||
export default fastifyPlugin(zTokenParserPlugin, "4.x");
|
||||
export default fastifyPlugin(zTokenParserPlugin, '4.x')
|
||||
|
@ -8,7 +8,7 @@ import * as schedule from 'node-schedule'
|
||||
@singleton
|
||||
export default class NonceRecordSchedule {
|
||||
async parseAllFinishedRecord() {
|
||||
await NonceRecord.deleteMany({status: 1});
|
||||
await NonceRecord.deleteMany({ status: 1 })
|
||||
}
|
||||
async parseAllExpiredRecord() {
|
||||
let now = Date.now()
|
||||
|
@ -1,6 +1,6 @@
|
||||
import axios, { AxiosResponse } from 'axios'
|
||||
import logger from 'logger/logger'
|
||||
import { prepareOkxReqCfg } from 'utils/okx.utils';
|
||||
import { prepareOkxReqCfg } from 'utils/okx.utils'
|
||||
|
||||
export const OKX_BASE = 'https://www.okx.com/api/v5/waas'
|
||||
|
||||
@ -19,9 +19,9 @@ export interface IOkxRes {
|
||||
export function getGasPrice(chainId: string | number) {
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: `${OKX_BASE}/transaction/get-gas-price?chainId=${chainId}`
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: `${OKX_BASE}/transaction/get-gas-price?chainId=${chainId}`,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -38,9 +38,9 @@ export function getSignInfo(data: any) {
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/transaction/get-sign-info`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -57,9 +57,9 @@ export function sendTran(data: any): Promise<AxiosResponse<IOkxRes>> {
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/transaction/send-transaction`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -69,19 +69,32 @@ export function sendTran(data: any): Promise<AxiosResponse<IOkxRes>> {
|
||||
* @param data
|
||||
* @returns
|
||||
*/
|
||||
export function queryTranDetail({walletId, orderId, chainId}
|
||||
:{walletId: string, orderId: string, chainId: string}) {
|
||||
|
||||
export function queryTranDetail({
|
||||
walletId,
|
||||
orderId,
|
||||
chainId,
|
||||
}: {
|
||||
walletId: string
|
||||
orderId: string
|
||||
chainId: string
|
||||
}) {
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: `${OKX_BASE}/transaction/get-transaction-detail?walletId=${walletId}&orderId=${orderId}&chainId=${chainId}`
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: `${OKX_BASE}/transaction/get-transaction-detail?walletId=${walletId}&orderId=${orderId}&chainId=${chainId}`,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
export async function ensureTxhash({walletId, orderId, chainId}
|
||||
:{walletId: string, orderId: string, chainId: string}) {
|
||||
export async function ensureTxhash({
|
||||
walletId,
|
||||
orderId,
|
||||
chainId,
|
||||
}: {
|
||||
walletId: string
|
||||
orderId: string
|
||||
chainId: string
|
||||
}) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
let interReq = setInterval(async () => {
|
||||
try {
|
||||
@ -100,11 +113,10 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
} catch (err) {
|
||||
logger.log('ensureTxhash err', err)
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
}, 1000)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Query transaction history
|
||||
* https://www.okx.com/web3/build/docs/waas/api-transaction-get-transactions-history
|
||||
@ -118,9 +130,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/transaction/get-transactions`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
// end of tranactions
|
||||
@ -155,9 +167,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/wallet/create-wallet`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -195,9 +207,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/wallet/sync-address`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
/**
|
||||
@ -208,9 +220,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
export function getAddresses(walletId: string) {
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: `${OKX_BASE}/wallet/get-addresses?walletId=${walletId}`
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: `${OKX_BASE}/wallet/get-addresses?walletId=${walletId}`,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -224,9 +236,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
export function getAllCoins(type: string) {
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: `${OKX_BASE}/asset/get-all-coins?type=${type}`
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: `${OKX_BASE}/asset/get-all-coins?type=${type}`,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
/**
|
||||
@ -250,9 +262,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/asset/add-coin`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -273,9 +285,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/asset/del-coin`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -296,9 +308,9 @@ export function queryTranDetail({walletId, orderId, chainId}
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/asset/get-assets`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
// end of assets
|
||||
|
@ -1,9 +1,9 @@
|
||||
import axios from 'axios'
|
||||
import logger from 'logger/logger'
|
||||
import {generateKVStr} from 'utils/net.util';
|
||||
import { prepareOkxReqCfg } from 'utils/okx.utils';
|
||||
import { generateKVStr } from 'utils/net.util'
|
||||
import { prepareOkxReqCfg } from 'utils/okx.utils'
|
||||
|
||||
const OKX_BASE = 'https://www.okx.com/api/v5/mktplace';
|
||||
const OKX_BASE = 'https://www.okx.com/api/v5/mktplace'
|
||||
|
||||
/**
|
||||
* https://www.okx.com/web3/build/docs/build-dapp/marketplace-create-a-listing
|
||||
@ -15,9 +15,9 @@ export function beginSell(data: any) {
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/nft/markets/create-listing`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
export function submitOrder(data: any) {
|
||||
@ -27,9 +27,9 @@ export function submitOrder(data: any) {
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/nft/markets/submit-listing`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
/**
|
||||
@ -42,9 +42,9 @@ export function buyOrder(data: any) {
|
||||
let config = {
|
||||
method: 'post',
|
||||
url: `${OKX_BASE}/nft/markets/buy`,
|
||||
data
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
data,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
||||
@ -52,29 +52,29 @@ export function buyOrder(data: any) {
|
||||
* https://www.okx.com/web3/build/docs/build-dapp/marketplace-query-listing
|
||||
*/
|
||||
export function listings(data: any) {
|
||||
let uri = `${OKX_BASE}/nft/markets/listings`;
|
||||
let uri = `${OKX_BASE}/nft/markets/listings`
|
||||
if (data) {
|
||||
uri = generateKVStr({ data, uri })
|
||||
}
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: uri
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: uri,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
/**
|
||||
* https://www.okx.com/web3/build/docs/build-dapp/marketplace-query-offer
|
||||
*/
|
||||
export function offers(data: any) {
|
||||
let uri = `${OKX_BASE}/nft/markets/offers`;
|
||||
let uri = `${OKX_BASE}/nft/markets/offers`
|
||||
if (data) {
|
||||
uri = generateKVStr({ data, uri })
|
||||
}
|
||||
let config = {
|
||||
method: 'get',
|
||||
url: uri
|
||||
};
|
||||
config = prepareOkxReqCfg(config);
|
||||
url: uri,
|
||||
}
|
||||
config = prepareOkxReqCfg(config)
|
||||
return axios.request(config)
|
||||
}
|
||||
|
@ -1,23 +1,21 @@
|
||||
import { bytesToHex } from '@noble/hashes/utils'
|
||||
import { keccak_256 } from '@noble/hashes/sha3'
|
||||
import {recoverPersonalSignature} from '@metamask/eth-sig-util';
|
||||
import { recoverPersonalSignature } from '@metamask/eth-sig-util'
|
||||
|
||||
export function toEIP55(address: string) {
|
||||
const lowerAddress = `${address}`.toLowerCase().replace('0x', '');
|
||||
const lowerAddress = `${address}`.toLowerCase().replace('0x', '')
|
||||
var hash = bytesToHex(keccak_256(lowerAddress))
|
||||
var ret = '0x';
|
||||
var ret = '0x'
|
||||
for (var i = 0; i < lowerAddress.length; i++) {
|
||||
if (parseInt(hash[i], 16) >= 8) {
|
||||
ret += lowerAddress[i].toUpperCase();
|
||||
}
|
||||
else {
|
||||
ret += lowerAddress[i];
|
||||
ret += lowerAddress[i].toUpperCase()
|
||||
} else {
|
||||
ret += lowerAddress[i]
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
return ret
|
||||
}
|
||||
|
||||
|
||||
export function checkPersionalSign(message: string, address: string, signature: string) {
|
||||
if (!signature.startsWith('0x')) {
|
||||
signature = '0x' + signature
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { ZError } from "common/ZError"
|
||||
import { ZError } from 'common/ZError'
|
||||
|
||||
const TIMEOUT_ERROR = new Error('timeout')
|
||||
|
||||
@ -130,32 +130,32 @@ export function generateKVStr({
|
||||
sort = false,
|
||||
encode = false,
|
||||
ignoreNull = true,
|
||||
splitChar = "&",
|
||||
equalChar = "=",
|
||||
uri = "",
|
||||
splitChar = '&',
|
||||
equalChar = '=',
|
||||
uri = '',
|
||||
}: {
|
||||
data?: any;
|
||||
sort?: boolean;
|
||||
encode?: boolean;
|
||||
ignoreNull?: boolean;
|
||||
splitChar?: string;
|
||||
equalChar?: string;
|
||||
uri?: string;
|
||||
data?: any
|
||||
sort?: boolean
|
||||
encode?: boolean
|
||||
ignoreNull?: boolean
|
||||
splitChar?: string
|
||||
equalChar?: string
|
||||
uri?: string
|
||||
}) {
|
||||
const keys = Object.keys(data);
|
||||
sort && keys.sort();
|
||||
const keys = Object.keys(data)
|
||||
sort && keys.sort()
|
||||
let result = keys
|
||||
.filter((key) => !ignoreNull || data[key])
|
||||
.map((key) => {
|
||||
const value = encode ? encodeURIComponent(data[key]) : data[key];
|
||||
return `${key}${equalChar}${value}`;
|
||||
.filter(key => !ignoreNull || data[key])
|
||||
.map(key => {
|
||||
const value = encode ? encodeURIComponent(data[key]) : data[key]
|
||||
return `${key}${equalChar}${value}`
|
||||
})
|
||||
.join(splitChar);
|
||||
.join(splitChar)
|
||||
if (uri) {
|
||||
const joinChar = uri.search(/\?/) === -1 ? "?" : "&";
|
||||
result = uri + joinChar + result;
|
||||
const joinChar = uri.search(/\?/) === -1 ? '?' : '&'
|
||||
result = uri + joinChar + result
|
||||
}
|
||||
return result;
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
@ -164,25 +164,23 @@ export function generateKVStr({
|
||||
* @param splitChar 连接的字符, 默认是&
|
||||
* @param equalChar =
|
||||
*/
|
||||
export function keyValToObject(
|
||||
str: string,
|
||||
splitChar: string = "&",
|
||||
equalChar = "="
|
||||
): {} {
|
||||
let result: any = {};
|
||||
export function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {
|
||||
let result: any = {}
|
||||
if (!str) {
|
||||
return result;
|
||||
return result
|
||||
}
|
||||
let arrs = str.split(splitChar);
|
||||
let arrs = str.split(splitChar)
|
||||
for (let sub of arrs) {
|
||||
let subArr = sub.split(equalChar);
|
||||
result[subArr[0]] = subArr[1];
|
||||
let subArr = sub.split(equalChar)
|
||||
result[subArr[0]] = subArr[1]
|
||||
}
|
||||
return result;
|
||||
return result
|
||||
}
|
||||
|
||||
export const checkParamsNeeded = (...args) => {
|
||||
args.forEach((arg) => {if (!arg) {
|
||||
throw new ZError(10, 'params mismatch');
|
||||
}});
|
||||
args.forEach(arg => {
|
||||
if (!arg) {
|
||||
throw new ZError(10, 'params mismatch')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -1,23 +1,22 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
const apiKey = process.env.OKX_API_KEY;
|
||||
const projectId = process.env.OKX_PROJECT_ID;
|
||||
const pass = process.env.OKX_PASS;
|
||||
const secretKey = process.env.OKX_SECRET_KEY;
|
||||
|
||||
const apiKey = process.env.OKX_API_KEY
|
||||
const projectId = process.env.OKX_PROJECT_ID
|
||||
const pass = process.env.OKX_PASS
|
||||
const secretKey = process.env.OKX_SECRET_KEY
|
||||
|
||||
export function prepareOkxReqCfg(config: any) {
|
||||
let timestamp = new Date().toISOString();
|
||||
let url = new URL(config.url);
|
||||
let method = config.method.toUpperCase();
|
||||
let signStr = timestamp + method + url.pathname;
|
||||
let timestamp = new Date().toISOString()
|
||||
let url = new URL(config.url)
|
||||
let method = config.method.toUpperCase()
|
||||
let signStr = timestamp + method + url.pathname
|
||||
if (method === 'GET') {
|
||||
signStr += url.search
|
||||
} else if (method === 'POST') {
|
||||
let bodyStr = JSON.stringify(JSON.parse(config.data))
|
||||
signStr+=bodyStr;
|
||||
signStr += bodyStr
|
||||
}
|
||||
const mac = crypto.createHmac('sha256', secretKey);
|
||||
const mac = crypto.createHmac('sha256', secretKey)
|
||||
const sign = mac.update(signStr).digest('base64')
|
||||
config.headers = {
|
||||
'OK-ACCESS-PROJECT': projectId,
|
||||
@ -25,7 +24,7 @@ export function prepareOkxReqCfg(config: any) {
|
||||
'OK-ACCESS-SIGN': sign,
|
||||
'OK-ACCESS-TIMESTAMP': timestamp,
|
||||
'OK-ACCESS-PASSPHRASE': pass,
|
||||
'Content-Type': 'application/json'
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
return config;
|
||||
return config
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user