Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(trading-sdk): add an option to toggle logs #233

Merged
merged 4 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/trading/consts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { EcdsaSigningScheme, SigningScheme } from '../order-book'

export const log = (text: string) => console.log(`[COW TRADING SDK] ${text}`)
export function log(text: string) {
if (!log.enabled) return
console.log(`[COW TRADING SDK] ${text}`)
}

log.enabled = false

export const DEFAULT_QUOTE_VALIDITY = 60 * 10 // 10 min

Expand Down
9 changes: 7 additions & 2 deletions src/trading/postSwapOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ import { SwapAdvancedSettings, SwapParameters } from './types'
import { postCoWProtocolTrade } from './postCoWProtocolTrade'
import { getQuoteWithSigner, QuoteResultsWithSigner } from './getQuote'
import { swapParamsToLimitOrderParams } from './utils'
import { OrderBookApi } from '../order-book'

export async function postSwapOrder(params: SwapParameters, advancedSettings?: SwapAdvancedSettings) {
return postSwapOrderFromQuote(await getQuoteWithSigner(params, advancedSettings), advancedSettings)
export async function postSwapOrder(
params: SwapParameters,
advancedSettings?: SwapAdvancedSettings,
orderBookApi?: OrderBookApi
) {
return postSwapOrderFromQuote(await getQuoteWithSigner(params, advancedSettings, orderBookApi), advancedSettings)
}

export async function postSwapOrderFromQuote(
Expand Down
102 changes: 102 additions & 0 deletions src/trading/tradingSdk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
jest.mock('cross-fetch', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fetchMock = require('jest-fetch-mock')
// Require the original module to not be mocked...
const originalFetch = jest.requireActual('cross-fetch')
return {
__esModule: true,
...originalFetch,
default: fetchMock,
}
})
import { TradingSdk } from './tradingSdk'
import { SupportedChainId } from '../common'
import { TradeBaseParameters } from './types'
import { OrderBookApi, OrderKind } from '../order-book'

const defaultOrderParams: TradeBaseParameters = {
sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14',
sellTokenDecimals: 18,
buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59',
buyTokenDecimals: 18,
amount: '100000000000000000',
kind: OrderKind.SELL,
}

const quoteResponseMock = {
quote: {
sellToken: '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14',
buyToken: '0x0625aFB445C3B6B7B929342a04A22599fd5dBB59',
receiver: '0xc8c753ee51e8fc80e199ab297fb575634a1ac1d3',
sellAmount: '1005456782512030400',
buyAmount: '400000000000000000000',
validTo: 1737468944,
appData:
'{"appCode":"test","metadata":{"orderClass":{"orderClass":"market"},"quote":{"slippageBips":50}},"version":"1.3.0"}',
appDataHash: '0xe269b09f45b1d3c98d8e4e841b99a0779fbd3b77943d069b91ddc4fd9789e27e',
feeAmount: '1112955650440102',
kind: 'buy',
partiallyFillable: false,
sellTokenBalance: 'erc20',
buyTokenBalance: 'erc20',
signingScheme: 'eip712',
},
from: '0xc8c753ee51e8fc80e199ab297fb575634a1ac1d3',
expiration: '2025-01-21T14:07:44.176194885Z',
id: 575498,
verified: true,
}

describe('TradingSdk', () => {
let orderBookApi: OrderBookApi

describe('Logs', () => {
beforeEach(() => {
orderBookApi = {
context: {
chainId: SupportedChainId.GNOSIS_CHAIN,
},
getQuote: jest.fn().mockResolvedValue(quoteResponseMock),
sendOrder: jest.fn().mockResolvedValue('0x01'),
} as unknown as OrderBookApi
})

afterEach(() => {
jest.resetAllMocks()
})

it('When logs option is set to false, then should not display logs', async () => {
const logSpy = jest.spyOn(console, 'log')

const sdk = new TradingSdk(
{
chainId: SupportedChainId.GNOSIS_CHAIN,
appCode: 'test',
signer: '0xa43ccc40ff785560dab6cb0f13b399d050073e8a54114621362f69444e1421ca',
},
{ enableLogging: false, orderBookApi }
)

await sdk.getQuote(defaultOrderParams)

expect(logSpy.mock.calls.length).toBe(0)
})

it('When logs option is set to true, then should display logs', async () => {
const logSpy = jest.spyOn(console, 'log')

const sdk = new TradingSdk(
{
chainId: SupportedChainId.GNOSIS_CHAIN,
appCode: 'test',
signer: '0xa43ccc40ff785560dab6cb0f13b399d050073e8a54114621362f69444e1421ca',
},
{ enableLogging: true, orderBookApi }
)

await sdk.getQuote(defaultOrderParams)

expect(logSpy.mock.calls[0][0]).toContain('[COW TRADING SDK]')
})
})
})
24 changes: 19 additions & 5 deletions src/trading/tradingSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,26 @@ import { getQuoteWithSigner } from './getQuote'
import { postSellNativeCurrencyOrder } from './postSellNativeCurrencyOrder'
import { getSigner, swapParamsToLimitOrderParams } from './utils'
import { getPreSignTransaction } from './getPreSignTransaction'
import { log } from './consts'
import { OrderBookApi } from '../order-book'

interface TradingSdkOptions {
enableLogging: boolean
orderBookApi: OrderBookApi
}

export class TradingSdk {
constructor(public readonly traderParams: TraderParameters) {}
constructor(
public readonly traderParams: TraderParameters,
public readonly options: Partial<TradingSdkOptions> = { enableLogging: false }
) {
if (options.enableLogging) {
log.enabled = true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its a bit strange pattern to mutate a global var like this from the constructor. I don't care too much, so maybe I'm nitpicking, but technically, you create 2 instances of the SDK and the second one will override the option of the first one

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but technically, you create 2 instances of the SDK

Yeah, I was thinking about that.
It's a bit tricky. The sdk is provided in two ways:

  • TradingSdk class
  • set of functions like postLimitOrder, getQuote and others

Because of that, it's a bit difficult to wire them up together in terms of logging.
I could put logEnabled flag to each function, but I fee it a bit overengineering.
I understand that adding enabled property to the log function is a hacky way, but this is tradeoff in favor of simplicity.

}
}

async getQuote(params: TradeParameters, advancedSettings?: SwapAdvancedSettings): Promise<QuoteAndPost> {
const quoteResults = await getQuoteWithSigner(this.mergeParams(params), advancedSettings)
const quoteResults = await getQuoteWithSigner(this.mergeParams(params), advancedSettings, this.options.orderBookApi)

return {
quoteResults: quoteResults.result,
Expand All @@ -26,18 +40,18 @@ export class TradingSdk {
}

async postSwapOrder(params: TradeParameters, advancedSettings?: SwapAdvancedSettings): Promise<string> {
return postSwapOrder(this.mergeParams(params), advancedSettings)
return postSwapOrder(this.mergeParams(params), advancedSettings, this.options.orderBookApi)
}

async postLimitOrder(params: LimitTradeParameters, advancedSettings?: LimitOrderAdvancedSettings): Promise<string> {
return postLimitOrder(this.mergeParams(params), advancedSettings)
return postLimitOrder(this.mergeParams(params), advancedSettings, this.options.orderBookApi)
}

async postSellNativeCurrencyOrder(
params: TradeParameters,
advancedSettings?: SwapAdvancedSettings
): Promise<ReturnType<typeof postSellNativeCurrencyOrder>> {
const quoteResults = await getQuoteWithSigner(this.mergeParams(params), advancedSettings)
const quoteResults = await getQuoteWithSigner(this.mergeParams(params), advancedSettings, this.options.orderBookApi)

const { tradeParameters, quoteResponse } = quoteResults.result
return postSellNativeCurrencyOrder(
Expand Down
Loading