@polymarbot/shared 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ // src/utils/trade-strategy/normalize.ts
2
+ import { Side } from "@polymarket/clob-client";
3
+ function normalizeBuyStep(step, options) {
4
+ const { start, end, price, size } = step;
5
+ const { minPrice, minSize } = options;
6
+ if (start === void 0 || start === null || start < 0) {
7
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u4E70\u5165\u6B65\u9AA4: start \u5FC5\u987B >= 0\uFF0C\u5F53\u524D\u503C: ${start}`);
8
+ return null;
9
+ }
10
+ if (end === void 0 || end === null || end <= 0) {
11
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u4E70\u5165\u6B65\u9AA4: end \u5FC5\u987B > 0\uFF0C\u5F53\u524D\u503C: ${end}`);
12
+ return null;
13
+ }
14
+ if (start >= end) {
15
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u4E70\u5165\u6B65\u9AA4: start \u5FC5\u987B\u5C0F\u4E8E end\uFF0C\u5F53\u524D start: ${start}, end: ${end}`);
16
+ return null;
17
+ }
18
+ if (price === void 0 || price === null || price < minPrice || price >= 1) {
19
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u4E70\u5165\u6B65\u9AA4: price \u5FC5\u987B >= ${minPrice} \u4E14 < 1\uFF0C\u5F53\u524D\u503C: ${price}`);
20
+ return null;
21
+ }
22
+ if (size === void 0 || size === null || size < minSize) {
23
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u4E70\u5165\u6B65\u9AA4: size \u5FC5\u987B >= ${minSize}\uFF0C\u5F53\u524D\u503C: ${size}`);
24
+ return null;
25
+ }
26
+ const normalized = {
27
+ side: Side.BUY,
28
+ price,
29
+ size,
30
+ start,
31
+ end
32
+ };
33
+ if (step.once === true) {
34
+ normalized.once = true;
35
+ }
36
+ if (step.outcome === "Up" || step.outcome === "Down") {
37
+ normalized.outcome = step.outcome;
38
+ }
39
+ const isLowPriceMode = price <= 0.5;
40
+ const isChaseMode = price > 0.5;
41
+ if (isLowPriceMode) {
42
+ if (step.maxUnderlyingDiff !== void 0) {
43
+ if (step.maxUnderlyingDiff >= 1 && step.maxUnderlyingDiff <= 1e3) {
44
+ normalized.maxUnderlyingDiff = step.maxUnderlyingDiff;
45
+ } else {
46
+ console.warn(` \u2514\u2500 \u5DF2\u79FB\u9664\u65E0\u6548\u5B57\u6BB5 maxUnderlyingDiff: \u503C\u5FC5\u987B\u5728 1-1000 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${step.maxUnderlyingDiff}`);
47
+ }
48
+ }
49
+ if (step.minUnderlyingDiff !== void 0) {
50
+ console.warn(` \u2514\u2500 \u5DF2\u79FB\u9664\u65E0\u6548\u5B57\u6BB5 minUnderlyingDiff: \u4F4E\u4F4D\u4E70\u5165\u6A21\u5F0F(price=${price})\u4E0D\u652F\u6301\u6B64\u5B57\u6BB5`);
51
+ }
52
+ }
53
+ if (isChaseMode) {
54
+ if (step.minUnderlyingDiff !== void 0) {
55
+ if (step.minUnderlyingDiff >= 1 && step.minUnderlyingDiff <= 1e3) {
56
+ normalized.minUnderlyingDiff = step.minUnderlyingDiff;
57
+ } else {
58
+ console.warn(` \u2514\u2500 \u5DF2\u79FB\u9664\u65E0\u6548\u5B57\u6BB5 minUnderlyingDiff: \u503C\u5FC5\u987B\u5728 1-1000 \u8303\u56F4\u5185\uFF0C\u5F53\u524D\u503C: ${step.minUnderlyingDiff}`);
59
+ }
60
+ }
61
+ if (step.maxUnderlyingDiff !== void 0) {
62
+ console.warn(` \u2514\u2500 \u5DF2\u79FB\u9664\u65E0\u6548\u5B57\u6BB5 maxUnderlyingDiff: \u8FFD\u6DA8\u4E70\u5165\u6A21\u5F0F(price=${price})\u4E0D\u652F\u6301\u6B64\u5B57\u6BB5`);
63
+ }
64
+ }
65
+ return normalized;
66
+ }
67
+ function normalizeSellStep(step, options) {
68
+ const { start, end, price, size } = step;
69
+ const { minPrice, minSize } = options;
70
+ if (start === void 0 || start === null || start < 0) {
71
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u5356\u51FA\u6B65\u9AA4: start \u5FC5\u987B >= 0\uFF0C\u5F53\u524D\u503C: ${start}`);
72
+ return null;
73
+ }
74
+ if (end === void 0 || end === null || end <= 0) {
75
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u5356\u51FA\u6B65\u9AA4: end \u5FC5\u987B > 0\uFF0C\u5F53\u524D\u503C: ${end}`);
76
+ return null;
77
+ }
78
+ if (start >= end) {
79
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u5356\u51FA\u6B65\u9AA4: start \u5FC5\u987B\u5C0F\u4E8E end\uFF0C\u5F53\u524D start: ${start}, end: ${end}`);
80
+ return null;
81
+ }
82
+ if (price === void 0 || price === null || price < minPrice || price >= 1) {
83
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u5356\u51FA\u6B65\u9AA4: price \u5FC5\u987B >= ${minPrice} \u4E14 < 1\uFF0C\u5F53\u524D\u503C: ${price}`);
84
+ return null;
85
+ }
86
+ if (size === void 0 || size === null || size < minSize) {
87
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u5356\u51FA\u6B65\u9AA4: size \u5FC5\u987B >= ${minSize}\uFF0C\u5F53\u524D\u503C: ${size}`);
88
+ return null;
89
+ }
90
+ const normalized = {
91
+ side: Side.SELL,
92
+ price,
93
+ size,
94
+ start,
95
+ end
96
+ };
97
+ const stepAsTradeStep = step;
98
+ const invalidFields = [];
99
+ if ("once" in stepAsTradeStep && stepAsTradeStep.once !== void 0) invalidFields.push("once");
100
+ if ("outcome" in stepAsTradeStep && stepAsTradeStep.outcome !== void 0) invalidFields.push("outcome");
101
+ if ("maxUnderlyingDiff" in stepAsTradeStep && stepAsTradeStep.maxUnderlyingDiff !== void 0) invalidFields.push("maxUnderlyingDiff");
102
+ if ("minUnderlyingDiff" in stepAsTradeStep && stepAsTradeStep.minUnderlyingDiff !== void 0) invalidFields.push("minUnderlyingDiff");
103
+ if (invalidFields.length > 0) {
104
+ console.warn(` \u2514\u2500 \u5DF2\u79FB\u9664\u5356\u51FA\u6B65\u9AA4\u4E2D\u7684\u65E0\u6548\u5B57\u6BB5: ${invalidFields.join(", ")}`);
105
+ }
106
+ return normalized;
107
+ }
108
+ function normalizeStrategy(config, options = {}) {
109
+ if (!config || !Array.isArray(config) || config.length === 0) {
110
+ console.warn("\u26A0\uFE0F \u7B56\u7565\u914D\u7F6E\u4E3A\u7A7A\u6216\u683C\u5F0F\u9519\u8BEF");
111
+ return [];
112
+ }
113
+ const normalizeOptions = {
114
+ minPrice: options.minPrice ?? 0.01,
115
+ minSize: options.minSize ?? 5
116
+ };
117
+ const normalized = [];
118
+ config.forEach((step, index) => {
119
+ console.debug(`\u9A8C\u8BC1\u6B65\u9AA4 ${index + 1}/${config.length}: ${step.side}`);
120
+ let normalizedStep = null;
121
+ if (step.side === Side.BUY) {
122
+ normalizedStep = normalizeBuyStep(step, normalizeOptions);
123
+ } else if (step.side === Side.SELL) {
124
+ normalizedStep = normalizeSellStep(step, normalizeOptions);
125
+ } else {
126
+ const unknownStep = step;
127
+ console.warn(`\u26A0\uFE0F \u5DF2\u8FC7\u6EE4\u65E0\u6548\u6B65\u9AA4: \u672A\u77E5\u7684 side \u7C7B\u578B: ${unknownStep.side}`);
128
+ }
129
+ if (normalizedStep) {
130
+ normalized.push(normalizedStep);
131
+ }
132
+ });
133
+ console.info(`\u2705 \u7B56\u7565\u4FEE\u6B63\u5B8C\u6210: \u539F\u59CB\u6B65\u9AA4 ${config.length} \u4E2A\uFF0C\u6709\u6548\u6B65\u9AA4 ${normalized.length} \u4E2A`);
134
+ return normalized;
135
+ }
136
+ function hasBuySteps(config) {
137
+ return config.some((step) => step.side === Side.BUY);
138
+ }
139
+ export {
140
+ hasBuySteps,
141
+ normalizeStrategy
142
+ };
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+
16
+ // src/utils/trade-strategy/types.ts
17
+ var types_exports = {};
18
+ module.exports = __toCommonJS(types_exports);
@@ -0,0 +1,231 @@
1
+ import { Side, ClobClient } from '@polymarket/clob-client';
2
+
3
+ /**
4
+ * 市场相关类型定义
5
+ */
6
+ declare enum SupportedSymbol {
7
+ ETH = "eth",
8
+ BTC = "btc",
9
+ SOL = "sol",
10
+ XRP = "xrp"
11
+ }
12
+ declare enum SupportedInterval {
13
+ M15 = "15m",
14
+ H1 = "1h",
15
+ H4 = "4h",
16
+ D1 = "1d"
17
+ }
18
+ interface RawMarketData {
19
+ id: string;
20
+ conditionId: string;
21
+ question: string;
22
+ slug: string;
23
+ eventStartTime: string;
24
+ endDate: string;
25
+ active: boolean;
26
+ closed: boolean;
27
+ umaResolutionStatus?: string;
28
+ customLiveness?: number;
29
+ outcomes: string;
30
+ outcomePrices?: string;
31
+ clobTokenIds?: string;
32
+ orderPriceMinTickSize: number;
33
+ orderMinSize: number;
34
+ negRisk: boolean;
35
+ volume: string;
36
+ liquidity: string;
37
+ bestBid?: number;
38
+ bestAsk?: number;
39
+ }
40
+ interface Market {
41
+ id: string;
42
+ conditionId: string;
43
+ question: string;
44
+ slug: string;
45
+ url: string;
46
+ startTimestamp: number;
47
+ endTimestamp: number;
48
+ orderMinSize: number;
49
+ orderPriceMinTickSize: number;
50
+ negRisk: boolean;
51
+ outcomes: string[];
52
+ clobTokenIds: string[];
53
+ marketName: string;
54
+ symbol: SupportedSymbol;
55
+ interval: SupportedInterval;
56
+ intervalName: string | null;
57
+ raw: RawMarketData;
58
+ }
59
+ interface MarketToken {
60
+ id: string;
61
+ name: string;
62
+ }
63
+
64
+ /**
65
+ * Polymarket 交易基础工具方法
66
+ */
67
+ /**
68
+ * 仓位信息
69
+ */
70
+ interface PositionInfo {
71
+ /** 仓位数量(格式化后的数字) */
72
+ size: number;
73
+ /** 原始余额(字符串格式) */
74
+ balance: string;
75
+ }
76
+
77
+ /**
78
+ * 加密货币价格查询模块
79
+ * 支持通过 Binance API 查询 ETH, BTC, SOL, XRP 的价格
80
+ */
81
+
82
+ /**
83
+ * 价格差信息类型
84
+ */
85
+ interface PriceDifferenceInfo {
86
+ /** 开始价格 */
87
+ start: number;
88
+ /** 结束价格 */
89
+ end: number;
90
+ /** 价格差 */
91
+ difference: number;
92
+ /** 价格差绝对值 */
93
+ differenceAbs: number;
94
+ /** 涨跌幅百分比,100 表示 100%,-100 表示 -100% */
95
+ percent: number;
96
+ /** 涨跌幅百分比绝对值 */
97
+ percentAbs: number;
98
+ /** 是否上涨 */
99
+ isUp: boolean;
100
+ /** 是否下跌 */
101
+ isDown: boolean;
102
+ /** 是否持平 */
103
+ isFlat: boolean;
104
+ }
105
+
106
+ /**
107
+ * 交易策略类型定义
108
+ */
109
+
110
+ /**
111
+ * 买入步骤配置
112
+ */
113
+ interface BuyStep {
114
+ side: Side.BUY;
115
+ price: number;
116
+ size: number;
117
+ start: number;
118
+ end: number;
119
+ once?: boolean;
120
+ outcome?: 'Up' | 'Down';
121
+ maxUnderlyingDiff?: number;
122
+ minUnderlyingDiff?: number;
123
+ }
124
+ /**
125
+ * 卖出步骤配置
126
+ */
127
+ interface SellStep {
128
+ side: Side.SELL;
129
+ price: number;
130
+ size: number;
131
+ start: number;
132
+ end: number;
133
+ }
134
+ /**
135
+ * 交易步骤类型
136
+ */
137
+ type TradeStep = BuyStep | SellStep;
138
+ /**
139
+ * 策略配置类型
140
+ * 由多个交易步骤组成的数组
141
+ */
142
+ type StrategyConfig = TradeStep[];
143
+ /**
144
+ * 策略回调函数类型
145
+ * @param prevResult - 上一个策略回调的返回值(首个回调为 undefined)
146
+ * @returns 返回值说明:
147
+ * - 返回 false:终止后续所有策略的执行
148
+ * - 返回 true、null、undefined、void:继续执行后续策略,不传递值
149
+ * - 返回其他非 boolean 值:继续执行后续策略,并将该值作为下一个策略的入参
150
+ */
151
+ type StrategyCallback = (prevResult?: any) => any | Promise<any>;
152
+ /**
153
+ * 策略配置数组
154
+ * StrategyCondition 格式:
155
+ * - "<10": 从开始到10分钟(不包含10分钟)
156
+ * - ">=10": 从10分钟开始(包含10分钟)到结束
157
+ * - ">=20,<40": 从20分钟开始(包含20分钟)到40分钟(不包含40分钟)
158
+ * - "=30" 或 "30": 等于30分钟
159
+ * - ">10,<=20": 从10分钟后(不包含10分钟)到20分钟(包含20分钟)
160
+ *
161
+ * 任务严格按照数组顺序执行
162
+ */
163
+ type StrategyCondition = string;
164
+ type StrategyExecQueue = Array<[StrategyCondition, StrategyCallback]>;
165
+ /**
166
+ * 策略执行错误回调函数类型
167
+ * @param error - 错误对象
168
+ */
169
+ type StrategyErrorCallback = (error: Error) => void | Promise<void>;
170
+ /**
171
+ * 策略函数类型
172
+ * @param onError - 策略执行失败时的错误回调(可选)
173
+ */
174
+ type StrategyFn = (onError?: StrategyErrorCallback) => Promise<void>;
175
+ /**
176
+ * Token 交易步骤订单信息
177
+ */
178
+ interface TokenTradeStepOrder {
179
+ id: string;
180
+ stepJson: string;
181
+ side: Side;
182
+ status: string;
183
+ updatedAt: number;
184
+ }
185
+ /**
186
+ * 市场交易记录类型
187
+ */
188
+ interface MarketTradeRecord {
189
+ marketId: string;
190
+ strategyJson: string;
191
+ tokens: {
192
+ [tokenId: string]: TokenTradeStepOrder[];
193
+ };
194
+ }
195
+ /**
196
+ * 市场交易上下文
197
+ * 包含执行交易策略所需的市场信息和客户端实例
198
+ */
199
+ interface MarketTradeContext {
200
+ /** CLOB 客户端实例 */
201
+ clobClient: ClobClient;
202
+ /** Funder 地址或标识 */
203
+ funder: string;
204
+ /** 市场信息(包含开始/结束时间戳等) */
205
+ market: Market;
206
+ /** Token 列表 (包含 id 和 name) */
207
+ tokens: MarketToken[];
208
+ /** 交易记录 */
209
+ tradeRecord: MarketTradeRecord;
210
+ /** 标的物价格信息(可能为 null,如果价格查询失败) */
211
+ underlyingPrice: PriceDifferenceInfo | null;
212
+ }
213
+ /**
214
+ * 市场 Token 数据
215
+ */
216
+ interface MarketTokenData extends MarketToken {
217
+ /** 是否有持仓 */
218
+ hasPosition: boolean;
219
+ /** 仓位信息,null 表示未查询 */
220
+ positionInfo: PositionInfo | null;
221
+ /** 订单记录 */
222
+ orderRecords: TokenTradeStepOrder[];
223
+ }
224
+ /**
225
+ * 市场 Token 上下文
226
+ * 记录市场中每个 Token 的持仓和订单记录数据
227
+ * 使用 tokenId 作为 key
228
+ */
229
+ type MarketTokenContext = Record<string, MarketTokenData>;
230
+
231
+ export type { BuyStep, MarketTokenContext, MarketTokenData, MarketTradeContext, MarketTradeRecord, SellStep, StrategyCallback, StrategyCondition, StrategyConfig, StrategyErrorCallback, StrategyExecQueue, StrategyFn, TokenTradeStepOrder, TradeStep };
@@ -0,0 +1,231 @@
1
+ import { Side, ClobClient } from '@polymarket/clob-client';
2
+
3
+ /**
4
+ * 市场相关类型定义
5
+ */
6
+ declare enum SupportedSymbol {
7
+ ETH = "eth",
8
+ BTC = "btc",
9
+ SOL = "sol",
10
+ XRP = "xrp"
11
+ }
12
+ declare enum SupportedInterval {
13
+ M15 = "15m",
14
+ H1 = "1h",
15
+ H4 = "4h",
16
+ D1 = "1d"
17
+ }
18
+ interface RawMarketData {
19
+ id: string;
20
+ conditionId: string;
21
+ question: string;
22
+ slug: string;
23
+ eventStartTime: string;
24
+ endDate: string;
25
+ active: boolean;
26
+ closed: boolean;
27
+ umaResolutionStatus?: string;
28
+ customLiveness?: number;
29
+ outcomes: string;
30
+ outcomePrices?: string;
31
+ clobTokenIds?: string;
32
+ orderPriceMinTickSize: number;
33
+ orderMinSize: number;
34
+ negRisk: boolean;
35
+ volume: string;
36
+ liquidity: string;
37
+ bestBid?: number;
38
+ bestAsk?: number;
39
+ }
40
+ interface Market {
41
+ id: string;
42
+ conditionId: string;
43
+ question: string;
44
+ slug: string;
45
+ url: string;
46
+ startTimestamp: number;
47
+ endTimestamp: number;
48
+ orderMinSize: number;
49
+ orderPriceMinTickSize: number;
50
+ negRisk: boolean;
51
+ outcomes: string[];
52
+ clobTokenIds: string[];
53
+ marketName: string;
54
+ symbol: SupportedSymbol;
55
+ interval: SupportedInterval;
56
+ intervalName: string | null;
57
+ raw: RawMarketData;
58
+ }
59
+ interface MarketToken {
60
+ id: string;
61
+ name: string;
62
+ }
63
+
64
+ /**
65
+ * Polymarket 交易基础工具方法
66
+ */
67
+ /**
68
+ * 仓位信息
69
+ */
70
+ interface PositionInfo {
71
+ /** 仓位数量(格式化后的数字) */
72
+ size: number;
73
+ /** 原始余额(字符串格式) */
74
+ balance: string;
75
+ }
76
+
77
+ /**
78
+ * 加密货币价格查询模块
79
+ * 支持通过 Binance API 查询 ETH, BTC, SOL, XRP 的价格
80
+ */
81
+
82
+ /**
83
+ * 价格差信息类型
84
+ */
85
+ interface PriceDifferenceInfo {
86
+ /** 开始价格 */
87
+ start: number;
88
+ /** 结束价格 */
89
+ end: number;
90
+ /** 价格差 */
91
+ difference: number;
92
+ /** 价格差绝对值 */
93
+ differenceAbs: number;
94
+ /** 涨跌幅百分比,100 表示 100%,-100 表示 -100% */
95
+ percent: number;
96
+ /** 涨跌幅百分比绝对值 */
97
+ percentAbs: number;
98
+ /** 是否上涨 */
99
+ isUp: boolean;
100
+ /** 是否下跌 */
101
+ isDown: boolean;
102
+ /** 是否持平 */
103
+ isFlat: boolean;
104
+ }
105
+
106
+ /**
107
+ * 交易策略类型定义
108
+ */
109
+
110
+ /**
111
+ * 买入步骤配置
112
+ */
113
+ interface BuyStep {
114
+ side: Side.BUY;
115
+ price: number;
116
+ size: number;
117
+ start: number;
118
+ end: number;
119
+ once?: boolean;
120
+ outcome?: 'Up' | 'Down';
121
+ maxUnderlyingDiff?: number;
122
+ minUnderlyingDiff?: number;
123
+ }
124
+ /**
125
+ * 卖出步骤配置
126
+ */
127
+ interface SellStep {
128
+ side: Side.SELL;
129
+ price: number;
130
+ size: number;
131
+ start: number;
132
+ end: number;
133
+ }
134
+ /**
135
+ * 交易步骤类型
136
+ */
137
+ type TradeStep = BuyStep | SellStep;
138
+ /**
139
+ * 策略配置类型
140
+ * 由多个交易步骤组成的数组
141
+ */
142
+ type StrategyConfig = TradeStep[];
143
+ /**
144
+ * 策略回调函数类型
145
+ * @param prevResult - 上一个策略回调的返回值(首个回调为 undefined)
146
+ * @returns 返回值说明:
147
+ * - 返回 false:终止后续所有策略的执行
148
+ * - 返回 true、null、undefined、void:继续执行后续策略,不传递值
149
+ * - 返回其他非 boolean 值:继续执行后续策略,并将该值作为下一个策略的入参
150
+ */
151
+ type StrategyCallback = (prevResult?: any) => any | Promise<any>;
152
+ /**
153
+ * 策略配置数组
154
+ * StrategyCondition 格式:
155
+ * - "<10": 从开始到10分钟(不包含10分钟)
156
+ * - ">=10": 从10分钟开始(包含10分钟)到结束
157
+ * - ">=20,<40": 从20分钟开始(包含20分钟)到40分钟(不包含40分钟)
158
+ * - "=30" 或 "30": 等于30分钟
159
+ * - ">10,<=20": 从10分钟后(不包含10分钟)到20分钟(包含20分钟)
160
+ *
161
+ * 任务严格按照数组顺序执行
162
+ */
163
+ type StrategyCondition = string;
164
+ type StrategyExecQueue = Array<[StrategyCondition, StrategyCallback]>;
165
+ /**
166
+ * 策略执行错误回调函数类型
167
+ * @param error - 错误对象
168
+ */
169
+ type StrategyErrorCallback = (error: Error) => void | Promise<void>;
170
+ /**
171
+ * 策略函数类型
172
+ * @param onError - 策略执行失败时的错误回调(可选)
173
+ */
174
+ type StrategyFn = (onError?: StrategyErrorCallback) => Promise<void>;
175
+ /**
176
+ * Token 交易步骤订单信息
177
+ */
178
+ interface TokenTradeStepOrder {
179
+ id: string;
180
+ stepJson: string;
181
+ side: Side;
182
+ status: string;
183
+ updatedAt: number;
184
+ }
185
+ /**
186
+ * 市场交易记录类型
187
+ */
188
+ interface MarketTradeRecord {
189
+ marketId: string;
190
+ strategyJson: string;
191
+ tokens: {
192
+ [tokenId: string]: TokenTradeStepOrder[];
193
+ };
194
+ }
195
+ /**
196
+ * 市场交易上下文
197
+ * 包含执行交易策略所需的市场信息和客户端实例
198
+ */
199
+ interface MarketTradeContext {
200
+ /** CLOB 客户端实例 */
201
+ clobClient: ClobClient;
202
+ /** Funder 地址或标识 */
203
+ funder: string;
204
+ /** 市场信息(包含开始/结束时间戳等) */
205
+ market: Market;
206
+ /** Token 列表 (包含 id 和 name) */
207
+ tokens: MarketToken[];
208
+ /** 交易记录 */
209
+ tradeRecord: MarketTradeRecord;
210
+ /** 标的物价格信息(可能为 null,如果价格查询失败) */
211
+ underlyingPrice: PriceDifferenceInfo | null;
212
+ }
213
+ /**
214
+ * 市场 Token 数据
215
+ */
216
+ interface MarketTokenData extends MarketToken {
217
+ /** 是否有持仓 */
218
+ hasPosition: boolean;
219
+ /** 仓位信息,null 表示未查询 */
220
+ positionInfo: PositionInfo | null;
221
+ /** 订单记录 */
222
+ orderRecords: TokenTradeStepOrder[];
223
+ }
224
+ /**
225
+ * 市场 Token 上下文
226
+ * 记录市场中每个 Token 的持仓和订单记录数据
227
+ * 使用 tokenId 作为 key
228
+ */
229
+ type MarketTokenContext = Record<string, MarketTokenData>;
230
+
231
+ export type { BuyStep, MarketTokenContext, MarketTokenData, MarketTradeContext, MarketTradeRecord, SellStep, StrategyCallback, StrategyCondition, StrategyConfig, StrategyErrorCallback, StrategyExecQueue, StrategyFn, TokenTradeStepOrder, TradeStep };
File without changes
package/wallet.cjs ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/utils/wallet.ts
21
+ var wallet_exports = {};
22
+ __export(wallet_exports, {
23
+ USDC_ABI: () => USDC_ABI,
24
+ USDC_ADDRESS: () => USDC_ADDRESS,
25
+ USDC_DECIMALS: () => USDC_DECIMALS,
26
+ formatBalance: () => formatBalance,
27
+ getPublicClient: () => getPublicClient,
28
+ getUSDCBalance: () => getUSDCBalance,
29
+ isAddressEqual: () => isAddressEqual
30
+ });
31
+ module.exports = __toCommonJS(wallet_exports);
32
+ var import_viem = require("viem");
33
+ var import_chains = require("viem/chains");
34
+ var USDC_ADDRESS = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
35
+ var USDC_DECIMALS = 6;
36
+ var USDC_ABI = (0, import_viem.parseAbi)(["function balanceOf(address) view returns (uint256)"]);
37
+ var getPublicClient = (() => {
38
+ const POLYGON_RPC = process.env.POLYGON_RPC || import_chains.polygon.rpcUrls.default.http[0];
39
+ let client = null;
40
+ return () => {
41
+ if (!client) {
42
+ client = (0, import_viem.createPublicClient)({
43
+ chain: import_chains.polygon,
44
+ transport: (0, import_viem.http)(POLYGON_RPC)
45
+ });
46
+ }
47
+ return client;
48
+ };
49
+ })();
50
+ function formatBalance(rawBalance, decimals = USDC_DECIMALS) {
51
+ return parseFloat((0, import_viem.formatUnits)(BigInt(rawBalance), decimals)).toFixed(2);
52
+ }
53
+ async function getUSDCBalance(address) {
54
+ const publicClient = getPublicClient();
55
+ return await publicClient.readContract({
56
+ address: USDC_ADDRESS,
57
+ abi: USDC_ABI,
58
+ functionName: "balanceOf",
59
+ args: [address]
60
+ });
61
+ }
62
+ function isAddressEqual(a, b) {
63
+ if (!a) return false;
64
+ if (!b) return false;
65
+ return a.toLowerCase() === b.toLowerCase();
66
+ }
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ USDC_ABI,
70
+ USDC_ADDRESS,
71
+ USDC_DECIMALS,
72
+ formatBalance,
73
+ getPublicClient,
74
+ getUSDCBalance,
75
+ isAddressEqual
76
+ });