forked from TONresistor/teleton-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrade.js
More file actions
388 lines (338 loc) · 13.2 KB
/
trade.js
File metadata and controls
388 lines (338 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* GiftIndex order book trading functions
*
* Builds and sends transactions for placing ask/bid orders and cancelling
* orders on the GHOLD/USDT and FLOOR/USDT order book contracts.
*
* NOTE on op code naming: the on-chain contract uses inverted names --
* what the contract calls "ask" is actually the buy-with-USDT flow, and
* what it calls "bid" is the sell-index-tokens flow. Our function names
* are user-friendly: placeAskOrder = sell tokens, placeBidOrder = buy tokens.
*
* Price scaling: 10^4 (price=10000 means $1.0000 USDT).
*
* Dependencies (provided by teleton runtime):
* @ton/core, @ton/ton, @ton/crypto, @orbs-network/ton-access
*/
import { readFileSync, realpathSync } from "fs";
import { createRequire } from "module";
import { homedir } from "os";
import { join } from "path";
// ---------------------------------------------------------------------------
// TON dependencies (CJS packages -- use createRequire for ESM compat)
// ---------------------------------------------------------------------------
const require = createRequire(realpathSync(process.argv[1]));
const _pluginRequire = createRequire(import.meta.url);
const { beginCell, Address, SendMode } = require("@ton/core");
const { WalletContractV5R1, TonClient, toNano, internal } = require("@ton/ton");
const { mnemonicToPrivateKey } = require("@ton/crypto");
// ---------------------------------------------------------------------------
// SDK logger
// ---------------------------------------------------------------------------
let _log = { info() {}, warn() {}, error() {} };
/** Initialize trade module with SDK logger. */
export function initTrade(sdk) {
_log = sdk.log;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** GHOLD jetton master (Gift Holders Index) -- 9 decimals */
const GHOLD_MASTER = "0:c833790c1bee2d8021f3a71afb1c7a173b6f7ab9ce4add2022eaa7bf342209dc";
/** FLOOR jetton master (Gifts Floor Index) -- 9 decimals */
const FLOOR_MASTER = "0:e5180905b4cfd0848dc8dcec8c8801b8a71fb9854342b7c604c7a35c7edb6b97";
/** USDT jetton master -- 6 decimals */
const USDT_MASTER = "0:b113a994b5024a16719f69139328eb759596c38a25f59028b146fecdc3621dfe";
/** Resolve the index token master from order book name */
function getIndexMaster(orderBook) {
if (orderBook.includes("EQCLF") || orderBook.toUpperCase().includes("FLOOR")) return FLOOR_MASTER;
return GHOLD_MASTER;
}
/** Standard jetton transfer op */
const JETTON_TRANSFER_OP = 0x0f8a7ea5;
/**
* Sell index tokens forward_payload op.
* (Contract calls this "bid", but from user perspective this is an ask/sell.)
*/
const ASK_OP = 0x00bf4385;
/**
* Buy index tokens with USDT forward_payload op.
* (Contract calls this "ask", but from user perspective this is a bid/buy.)
*/
const BID_OP = 0x00845746;
/** Cancel order op */
const CANCEL_OP = 0x3567;
const WALLET_FILE = join(homedir(), ".teleton", "wallet.json");
// ---------------------------------------------------------------------------
// Wallet + client setup (same pattern as gaspump/deploy.js)
// ---------------------------------------------------------------------------
async function getWalletAndClient() {
let walletData;
try {
walletData = JSON.parse(readFileSync(WALLET_FILE, "utf-8"));
} catch {
throw new Error("Agent wallet not found at " + WALLET_FILE);
}
if (!walletData.mnemonic || !Array.isArray(walletData.mnemonic)) {
throw new Error("Invalid wallet file: missing mnemonic");
}
const keyPair = await mnemonicToPrivateKey(walletData.mnemonic);
const wallet = WalletContractV5R1.create({
workchain: 0,
publicKey: keyPair.publicKey,
});
let endpoint;
try {
const { getHttpEndpoint } = _pluginRequire("@orbs-network/ton-access");
endpoint = await getHttpEndpoint({ network: "mainnet" });
} catch {
endpoint = "https://toncenter.com/api/v2/jsonRPC";
}
const client = new TonClient({ endpoint });
const contract = client.open(wallet);
return { wallet, keyPair, client, contract };
}
/**
* Resolve the jetton wallet address for a given owner on a jetton master.
*
* @param {object} client TonClient instance
* @param {string} jettonMaster Jetton master contract address (raw or friendly)
* @param {string} ownerAddress Owner wallet address
* @returns {Promise<Address>}
*/
async function resolveJettonWallet(client, jettonMaster, ownerAddress) {
const result = await client.runMethod(
Address.parse(jettonMaster),
"get_wallet_address",
[{ type: "slice", cell: beginCell().storeAddress(Address.parse(ownerAddress)).endCell() }],
);
return result.stack.readAddress();
}
// ---------------------------------------------------------------------------
// Pure cell builders
// ---------------------------------------------------------------------------
/**
* Build the forward_payload cell for ask/bid orders.
*
* @param {number} op Order op code (ASK_OP or BID_OP)
* @param {number} price Price scaled by 10^4 (e.g. 10000 = $1.0000)
* @returns {Cell}
*/
export function buildForwardPayload(op, price) {
return beginCell()
.storeUint(op, 32)
.storeUint(1, 16)
.storeUint(price, 32)
.endCell();
}
/**
* Build a TEP-74 jetton_transfer message body.
*
* Uses addr_none for response_destination (matching the on-chain frontend
* pattern -- excess TON is not returned to sender).
*
* @param {bigint} queryId Query ID for the transfer
* @param {bigint} amount Jetton amount in base units
* @param {Address} destination Where the jettons go (order book address)
* @param {Cell} forwardPayload The forward_payload cell (ask/bid payload)
* @returns {Cell}
*/
export function buildJettonTransferBody(queryId, amount, destination, forwardPayload) {
return beginCell()
.storeUint(JETTON_TRANSFER_OP, 32)
.storeUint(queryId, 64)
.storeCoins(amount)
.storeAddress(destination)
.storeUint(0, 2) // response_destination = addr_none
.storeUint(0, 1) // no custom_payload
.storeCoins(toNano("0.1")) // forward_ton_amount
.storeBit(true) // forward_payload present as ref
.storeRef(forwardPayload)
.endCell();
}
/**
* Build the cancel order message body.
*
* Cancel ref cell format: uint16(priority) + uint4(orderType) + address
* orderType: 1 = cancel bid (sell orders), 2 = cancel ask (buy orders)
*
* @param {bigint} queryId Query ID (timestamp-based)
* @param {number} priority Priority of the order to cancel (default 1)
* @param {number} orderType 1 = cancel sell order, 2 = cancel buy order
* @param {string} traderAddress Trader's wallet address (raw or friendly)
* @returns {Cell}
*/
export function buildCancelBody(queryId, priority, orderType, traderAddress) {
const refCell = beginCell()
.storeUint(priority, 16)
.storeUint(orderType, 4)
.storeAddress(Address.parse(traderAddress))
.endCell();
return beginCell()
.storeUint(CANCEL_OP, 32)
.storeUint(queryId, 64)
.storeRef(refCell)
.endCell();
}
// ---------------------------------------------------------------------------
// Transaction senders
// ---------------------------------------------------------------------------
/**
* Place an ASK order -- sell index tokens (GHOLD or FLOOR) on the order book.
*
* Sends a jetton_transfer of index tokens to the order book contract with a
* forward_payload encoding the ask price. The on-chain contract confusingly
* calls this a "bid" op (0x00BF4385).
*
* @param {string} orderBook Order book contract address
* @param {bigint|string} amount Token amount in base units (9 decimals)
* @param {number} price Ask price scaled by 10^4
* @returns {Promise<{seqno: number, walletAddress: string, jettonWalletAddress: string}>}
*/
export async function placeAskOrder(orderBook, amount, price) {
const { wallet, keyPair, client, contract } = await getWalletAndClient();
const ownerAddress = wallet.address.toString();
// Resolve the user's index token jetton wallet (GHOLD or FLOOR depending on OB)
const indexMaster = getIndexMaster(orderBook);
const jettonWallet = await resolveJettonWallet(client, indexMaster, ownerAddress);
const forwardPayload = buildForwardPayload(ASK_OP, price);
const body = buildJettonTransferBody(
0n,
BigInt(amount),
Address.parse(orderBook),
forwardPayload,
);
const seqno = await contract.getSeqno();
_log.info(`ASK order: seqno=${seqno}, ob=${orderBook}, price=${price}`);
await contract.sendTransfer({
seqno,
secretKey: keyPair.secretKey,
sendMode: SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS,
messages: [
internal({
to: jettonWallet,
value: toNano("0.15"),
body,
bounce: true,
}),
],
});
return {
seqno,
walletAddress: ownerAddress,
jettonWalletAddress: jettonWallet.toString(),
};
}
/**
* Place a BID order -- buy index tokens by sending USDT to the order book.
*
* Sends a jetton_transfer of USDT to the order book contract with a
* forward_payload encoding the bid price. The on-chain contract confusingly
* calls this an "ask" op (0x00845746).
*
* @param {string} orderBook Order book contract address
* @param {bigint|string} amount USDT amount in base units (6 decimals)
* @param {number} price Bid price scaled by 10^4
* @returns {Promise<{seqno: number, walletAddress: string, jettonWalletAddress: string}>}
*/
export async function placeBidOrder(orderBook, amount, price) {
const { wallet, keyPair, client, contract } = await getWalletAndClient();
const ownerAddress = wallet.address.toString();
// Resolve the user's USDT jetton wallet
const usdtJettonWallet = await resolveJettonWallet(client, USDT_MASTER, ownerAddress);
const forwardPayload = buildForwardPayload(BID_OP, price);
const body = buildJettonTransferBody(
0n,
BigInt(amount),
Address.parse(orderBook),
forwardPayload,
);
const seqno = await contract.getSeqno();
_log.info(`BID order: seqno=${seqno}, ob=${orderBook}, price=${price}`);
await contract.sendTransfer({
seqno,
secretKey: keyPair.secretKey,
sendMode: SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS,
messages: [
internal({
to: usdtJettonWallet,
value: toNano("0.15"),
body,
bounce: true,
}),
],
});
return {
seqno,
walletAddress: ownerAddress,
jettonWalletAddress: usdtJettonWallet.toString(),
};
}
/**
* Cancel an order on the order book.
*
* Sends a direct message to the order book contract with the cancel op,
* query ID, and order details (priority, type, trader address) in a ref cell.
*
* @param {string} orderBook Order book contract address
* @param {bigint} queryId Timestamp / query ID of the order to cancel
* @param {number} priority Priority of the order (uint16)
* @param {number} orderType 1 = cancel bid (sell orders), 2 = cancel ask (buy orders)
* @returns {Promise<{seqno: number, walletAddress: string}>}
*/
export async function cancelOrder(orderBook, queryId, priority, orderType) {
const { wallet, keyPair, contract } = await getWalletAndClient();
const ownerAddress = wallet.address.toString();
const body = buildCancelBody(BigInt(queryId), priority, orderType, ownerAddress);
const seqno = await contract.getSeqno();
_log.info(`CANCEL order: seqno=${seqno}, ob=${orderBook}, type=${orderType}`);
await contract.sendTransfer({
seqno,
secretKey: keyPair.secretKey,
sendMode: SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS,
messages: [
internal({
to: Address.parse(orderBook),
value: toNano("0.1"),
body,
bounce: true,
}),
],
});
return {
seqno,
walletAddress: ownerAddress,
};
}
// ---------------------------------------------------------------------------
// Post-trade verification
// ---------------------------------------------------------------------------
/**
* Rule 7: Poll the wallet seqno until it advances past expectedSeqno,
* confirming the transaction was accepted on-chain.
*
* @param {number} expectedSeqno - the seqno used when sending the tx
* @param {number} [maxWaitMs=25000] - maximum wait time in milliseconds
* @param {number} [intervalMs=3000] - polling interval
* @returns {{ confirmed: boolean, newSeqno?: number, elapsed: number }}
*/
export async function verifySeqnoAdvanced(expectedSeqno, maxWaitMs = 25000, intervalMs = 3000) {
const { contract } = await getWalletAndClient();
const start = Date.now();
while (Date.now() - start < maxWaitMs) {
await new Promise((r) => setTimeout(r, intervalMs));
try {
const current = await contract.getSeqno();
if (current > expectedSeqno) {
return { confirmed: true, newSeqno: current, elapsed: Date.now() - start };
}
} catch {
// Network blip — keep polling
}
}
return { confirmed: false, elapsed: Date.now() - start };
}
// ---------------------------------------------------------------------------
// Exported constants for use by index.js
// ---------------------------------------------------------------------------
export { GHOLD_MASTER, FLOOR_MASTER, USDT_MASTER, ASK_OP, BID_OP, CANCEL_OP };