- Introduced logic to check if the opening swap was canceled by the broker, marking positions as canceled when necessary. - Adjusted orphaned balance thresholds for ETH and other tokens to improve balance management. - Enhanced logging to provide detailed information on swap status, including warnings for canceled swaps and their implications on position management. - Added a new method to verify swap execution status, improving the robustness of position handling in SpotBot.
144 lines
6.3 KiB
TypeScript
144 lines
6.3 KiB
TypeScript
import {test} from 'node:test'
|
|
import assert from 'node:assert'
|
|
import {getClientForAddress, getSpotPositionHistoryImpl} from '../../src/plugins/custom/gmx.js'
|
|
import {Ticker} from '../../src/generated/ManagingApiTypes.js'
|
|
import {TradeActionType} from '../../src/generated/gmxsdk/types/tradeHistory.js'
|
|
import {OrderType} from '../../src/generated/gmxsdk/types/orders.js'
|
|
|
|
test('GMX get spot position history - Market swaps', async (t) => {
|
|
await t.test('should get spot swap executions', async () => {
|
|
const sdk = await getClientForAddress('0x932167388dD9aad41149b3cA23eBD489E2E2DD78')
|
|
|
|
// Get today's date range (start and end of today)
|
|
const today = new Date()
|
|
const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0)
|
|
const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999)
|
|
const fromDateTime = startOfDay.toISOString()
|
|
const toDateTime = endOfDay.toISOString()
|
|
|
|
const result = await getSpotPositionHistoryImpl(
|
|
sdk,
|
|
0, // pageIndex
|
|
100, // pageSize
|
|
Ticker.ETH, // ticker - changed to ETH to investigate the issue
|
|
fromDateTime, // fromDateTime (today's start)
|
|
toDateTime // toDateTime (today's end)
|
|
)
|
|
|
|
console.log('\n📊 Spot Swap History Summary (ETH):')
|
|
console.log(`Total swaps: ${result.length}`)
|
|
|
|
// Log detailed information about each swap
|
|
if (result.length > 0) {
|
|
console.log('\n📋 Detailed Swap Information:')
|
|
result.forEach((swap, index) => {
|
|
console.log(`\n[${index + 1}] Swap:`, JSON.stringify(swap, null, 2))
|
|
})
|
|
} else {
|
|
console.log('⚠️ No swaps found for ETH in the specified time range')
|
|
}
|
|
|
|
console.log(`\n📊 Full Result:`, result);
|
|
|
|
assert.ok(result, 'Spot position history result should be defined')
|
|
assert.ok(Array.isArray(result), 'Spot position history should be an array')
|
|
})
|
|
|
|
await t.test('should get ALL swap events (including canceled)', async () => {
|
|
const sdk = await getClientForAddress('0x932167388dD9aad41149b3cA23eBD489E2E2DD78')
|
|
|
|
// Get today's date range (start and end of today)
|
|
const today = new Date()
|
|
const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0)
|
|
const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999)
|
|
const fromTimestamp = Math.floor(startOfDay.getTime() / 1000)
|
|
const toTimestamp = Math.floor(endOfDay.getTime() / 1000)
|
|
|
|
// Fetch markets and tokens data
|
|
const marketsInfoResult = await sdk.markets.getMarketsInfo()
|
|
const tokensDataResult = await sdk.tokens.getTokensData()
|
|
|
|
if (!marketsInfoResult?.marketsInfoData || !tokensDataResult?.tokensData) {
|
|
throw new Error("No markets or tokens info data")
|
|
}
|
|
|
|
const marketsInfoData = marketsInfoResult.marketsInfoData
|
|
const tokensData = tokensDataResult.tokensData
|
|
|
|
// Fetch ALL swap events (executed, canceled, created, etc.)
|
|
const allSwapEvents = await sdk.trades.getTradeHistory({
|
|
pageIndex: 0,
|
|
pageSize: 100,
|
|
fromTxTimestamp: fromTimestamp,
|
|
toTxTimestamp: toTimestamp,
|
|
marketsInfoData,
|
|
tokensData,
|
|
marketsDirectionsFilter: undefined,
|
|
orderEventCombinations: [
|
|
{
|
|
eventName: TradeActionType.OrderExecuted,
|
|
orderType: OrderType.MarketSwap,
|
|
},
|
|
{
|
|
eventName: TradeActionType.OrderCancelled,
|
|
orderType: OrderType.MarketSwap,
|
|
},
|
|
{
|
|
eventName: TradeActionType.OrderCreated,
|
|
orderType: OrderType.MarketSwap,
|
|
}
|
|
],
|
|
})
|
|
|
|
console.log('\n🔍 ALL Swap Events (ETH):')
|
|
console.log(`Total events: ${allSwapEvents.length}`)
|
|
|
|
// Group by event type
|
|
const executedEvents = allSwapEvents.filter(e => e.eventName === TradeActionType.OrderExecuted)
|
|
const canceledEvents = allSwapEvents.filter(e => e.eventName === TradeActionType.OrderCancelled)
|
|
const createdEvents = allSwapEvents.filter(e => e.eventName === TradeActionType.OrderCreated)
|
|
|
|
console.log(`\n📊 Event Breakdown:`)
|
|
console.log(` ✅ Executed: ${executedEvents.length}`)
|
|
console.log(` ❌ Canceled: ${canceledEvents.length}`)
|
|
console.log(` 📝 Created: ${createdEvents.length}`)
|
|
|
|
// Log details of canceled events (these are likely the culprits)
|
|
if (canceledEvents.length > 0) {
|
|
console.log('\n❌ CANCELED SWAP DETAILS (THIS IS LIKELY THE ISSUE):')
|
|
canceledEvents.forEach((event, index) => {
|
|
const swapEvent = event as any
|
|
console.log(`\n[${index + 1}] Canceled Swap:`)
|
|
console.log(` Transaction: ${swapEvent.transaction?.hash}`)
|
|
console.log(` Order Key: ${swapEvent.orderKey}`)
|
|
console.log(` From Token: ${swapEvent.initialCollateralToken?.symbol}`)
|
|
console.log(` To Token: ${swapEvent.targetCollateralToken?.symbol}`)
|
|
console.log(` Amount In: ${swapEvent.initialCollateralDeltaAmount ? Number(swapEvent.initialCollateralDeltaAmount) / 1e18 : 'N/A'}`)
|
|
console.log(` Min Amount Out: ${swapEvent.minOutputAmount ? Number(swapEvent.minOutputAmount) / 1e18 : 'N/A'}`)
|
|
console.log(` Reason: ${swapEvent.reason || 'N/A'}`)
|
|
console.log(` Timestamp: ${new Date(Number(swapEvent.timestamp) * 1000).toISOString()}`)
|
|
})
|
|
}
|
|
|
|
// Log details of executed events
|
|
if (executedEvents.length > 0) {
|
|
console.log('\n✅ EXECUTED SWAP DETAILS:')
|
|
executedEvents.forEach((event, index) => {
|
|
const swapEvent = event as any
|
|
console.log(`\n[${index + 1}] Executed Swap:`)
|
|
console.log(` Transaction: ${swapEvent.transaction?.hash}`)
|
|
console.log(` Order Key: ${swapEvent.orderKey}`)
|
|
console.log(` From Token: ${swapEvent.initialCollateralToken?.symbol}`)
|
|
console.log(` To Token: ${swapEvent.targetCollateralToken?.symbol}`)
|
|
console.log(` Amount In: ${swapEvent.initialCollateralDeltaAmount ? Number(swapEvent.initialCollateralDeltaAmount) / 1e18 : 'N/A'}`)
|
|
console.log(` Amount Out: ${swapEvent.executionAmountOut ? Number(swapEvent.executionAmountOut) / 1e18 : 'N/A'}`)
|
|
console.log(` Timestamp: ${new Date(Number(swapEvent.timestamp) * 1000).toISOString()}`)
|
|
})
|
|
}
|
|
|
|
assert.ok(allSwapEvents, 'All swap events should be defined')
|
|
assert.ok(Array.isArray(allSwapEvents), 'All swap events should be an array')
|
|
})
|
|
})
|
|
|