import { AcceptedOrderInfo , OrderEvent , OrderEventEndState , OrderInfo , RejectedCode , RejectedOrderInfo , SignedOrder , ValidationResults , WSClient , } from '@0x/mesh-rpc-client' ; import * as _ from 'lodash' ; import { ZERO } from './constants' ; import { ValidationErrorCodes } from './errors' ; import { APIOrderWithMetaData } from './types' ; const d = require ( 'debug' ) ( 'MESH' ) ; export class MeshUtils { public static async addOrdersToMeshAsync ( meshClient , orders , batchSize = 100 ) { const validationResults = { accepted : [ ] , rejected : [ ] } ; const chunks = _ . chunk ( orders , batchSize ) ; for ( const chunk of chunks ) { const results = await meshClient . addOrdersAsync ( chunk , true ) ; validationResults . accepted = [ ... validationResults . accepted , ... results . accepted ] ; validationResults . rejected = [ ... validationResults . rejected , ... results . rejected ] ; } return validationResults ; } public static orderInfosToApiOrders ( orderEvent ) { return orderEvent . map ( e => MeshUtils . orderInfoToAPIOrder ( e ) ) ; } public static orderInfoToAPIOrder ( orderEvent ) { const remainingFillableTakerAssetAmount = ( orderEvent as OrderEvent ) . fillableTakerAssetAmount ? ( orderEvent as OrderEvent ) . fillableTakerAssetAmount : ZERO ; return { order : orderEvent . signedOrder , metaData : { orderHash : orderEvent . orderHash , remainingFillableTakerAssetAmount , } , } ; } public static rejectedCodeToSRACode ( code ) { switch ( code ) { case RejectedCode . OrderCancelled : case RejectedCode . OrderExpired : case RejectedCode . OrderUnfunded : case RejectedCode . OrderHasInvalidMakerAssetAmount : case RejectedCode . OrderHasInvalidMakerAssetData : case RejectedCode . OrderHasInvalidTakerAssetAmount : case RejectedCode . OrderHasInvalidTakerAssetData : case RejectedCode . OrderFullyFilled : { return ValidationErrorCodes . InvalidOrder ; } case RejectedCode . OrderHasInvalidSignature : { return ValidationErrorCodes . InvalidSignatureOrHash ; } case RejectedCode . OrderForIncorrectChain : { return ValidationErrorCodes . InvalidAddress ; } default : return ValidationErrorCodes . InternalError ; } } public static calculateAddedRemovedUpdated ( orderEvents ) { const added = [ ] ; const removed = [ ] ; const updated = [ ] ; for ( const event of orderEvents ) { const apiOrder = MeshUtils . orderInfoToAPIOrder ( event ) ; switch ( event . endState ) { case OrderEventEndState . Added : { added . push ( apiOrder ) ; break ; } case OrderEventEndState . Cancelled : case OrderEventEndState . Expired : case OrderEventEndState . FullyFilled : case OrderEventEndState . Unfunded : { removed . push ( apiOrder ) ; break ; } case OrderEventEndState . FillabilityIncreased : case OrderEventEndState . Filled : { updated . push ( apiOrder ) ; break ; } default : d ( 'Unknown Event' , event . endState , event ) ; break ; } } return { added , removed , updated } ; } }