@triadxyz/triad-protocol 1.7.0-beta → 1.7.1-beta

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.
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ const trade_2 = require("./utils/pda/trade");
24
24
  class TriadProtocolClient {
25
25
  constructor(connection, wallet) {
26
26
  this.provider = new anchor_1.AnchorProvider(connection, wallet, {
27
- commitment: 'processed'
27
+ commitment: 'confirmed'
28
28
  });
29
29
  this.program = new anchor_1.Program(idl_triad_protocol_json_1.default, this.provider);
30
30
  this.trade = new trade_1.default(this.program, this.provider);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,418 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const __1 = __importDefault(require(".."));
17
+ const anchor_1 = require("@coral-xyz/anchor");
18
+ const anchor_2 = require("@coral-xyz/anchor");
19
+ const web3_js_1 = require("@solana/web3.js");
20
+ const trade_1 = require("../types/trade");
21
+ const spl_token_1 = require("@solana/spl-token");
22
+ const constants_1 = require("../utils/constants");
23
+ // import { InitMarket } from './init-market'
24
+ const sdk_1 = require("@shadow-drive/sdk");
25
+ const init_market_1 = require("./init-market");
26
+ const file = fs_1.default.readFileSync('/Users/dannpl/.config/solana/id.json');
27
+ const rpc_file = fs_1.default.readFileSync('/Users/dannpl/.config/solana/rpc.txt');
28
+ const keypair = web3_js_1.Keypair.fromSecretKey(new Uint8Array(JSON.parse(file.toString())));
29
+ const connection = new web3_js_1.Connection(rpc_file.toString());
30
+ const wallet = new anchor_1.Wallet(keypair);
31
+ const triadProtocol = new __1.default(connection, wallet);
32
+ const marketId = 133;
33
+ const initMarket = new init_market_1.InitMarket(triadProtocol);
34
+ const updateStakeVault = () => __awaiter(void 0, void 0, void 0, function* () {
35
+ const response = yield triadProtocol.stake.updateStakeVault({
36
+ amount: new anchor_2.BN(200 * Math.pow(10, 6)),
37
+ isLocked: false
38
+ });
39
+ console.log(response);
40
+ });
41
+ const getStakeVault = () => __awaiter(void 0, void 0, void 0, function* () {
42
+ const response = yield triadProtocol.stake.getStakeVaults();
43
+ console.log(response);
44
+ });
45
+ const getStakeByWallet = () => __awaiter(void 0, void 0, void 0, function* () {
46
+ const response = yield triadProtocol.stake.getStakeByWallet(new web3_js_1.PublicKey('Fua99qprDG3YGijFDoGfWPnUjBqufgPPQgJTZEGKHFFL'), 1);
47
+ let sum = 0;
48
+ for (const stake of response) {
49
+ sum += stake.amount / Math.pow(10, 6);
50
+ }
51
+ console.log(sum);
52
+ });
53
+ getStakeByWallet();
54
+ const getAllStakes = () => __awaiter(void 0, void 0, void 0, function* () {
55
+ const stakes = yield triadProtocol.stake.getStakes();
56
+ console.log(stakes.length);
57
+ });
58
+ const getStakes = () => __awaiter(void 0, void 0, void 0, function* () {
59
+ const stakes = yield triadProtocol.stake.getStakes();
60
+ fs_1.default.writeFileSync('stakes.json', JSON.stringify(stakes, null, 2));
61
+ const stakesJson = JSON.parse(fs_1.default.readFileSync('stakes.json', 'utf8'));
62
+ let amountLocked = 0;
63
+ let amountUnlocked = 0;
64
+ let uniqueStakersLocked = new Set();
65
+ let uniqueStakersUnlocked = new Set();
66
+ let usersUnlocked = [];
67
+ let usersLocked = [];
68
+ for (const stake of stakesJson) {
69
+ if (stake.withdrawTs === 0) {
70
+ amountLocked += stake.amount / Math.pow(10, 6);
71
+ uniqueStakersLocked.add(stake.authority);
72
+ const existingUser = usersLocked.find((user) => user.address === stake.authority);
73
+ if (!existingUser) {
74
+ usersLocked.push({
75
+ address: stake.authority,
76
+ amount: stake.amount / Math.pow(10, 6)
77
+ });
78
+ }
79
+ else {
80
+ existingUser.amount += stake.amount / Math.pow(10, 6);
81
+ }
82
+ }
83
+ else {
84
+ amountUnlocked += stake.amount / Math.pow(10, 6);
85
+ uniqueStakersUnlocked.add(stake.authority);
86
+ const existingUser = usersUnlocked.find((user) => user.address === stake.authority);
87
+ if (!existingUser) {
88
+ usersUnlocked.push({
89
+ address: stake.authority,
90
+ amount: stake.amount / Math.pow(10, 6)
91
+ });
92
+ }
93
+ else {
94
+ existingUser.amount += stake.amount / Math.pow(10, 6);
95
+ }
96
+ }
97
+ }
98
+ const orders = usersLocked.sort((a, b) => b.amount - a.amount);
99
+ const ordersUnlocked = usersUnlocked.sort((a, b) => b.amount - a.amount);
100
+ console.log('Amount locked:', amountLocked);
101
+ console.log('Amount unlocked:', amountUnlocked);
102
+ console.log('Unique stakers:', uniqueStakersLocked.size);
103
+ console.log('Unique stakers unlocked:', uniqueStakersUnlocked.size);
104
+ console.log(JSON.stringify(orders, null, 2));
105
+ console.log('--------------------------------');
106
+ console.log(JSON.stringify(ordersUnlocked, null, 2));
107
+ });
108
+ const getAllMarkets = () => __awaiter(void 0, void 0, void 0, function* () {
109
+ let markets = yield triadProtocol.trade.getAllMarkets();
110
+ markets = markets.sort((a, b) => Number(a.marketId) - Number(b.marketId));
111
+ let totalFlopToPay = 0;
112
+ let totalHypeToPay = 0;
113
+ let totalLiquidity = 0;
114
+ let profit = 0;
115
+ const items = {};
116
+ for (const market of markets) {
117
+ if (Number(market.marketId) < 39 ||
118
+ market.winningDirection !== trade_1.WinningDirection.NONE) {
119
+ continue;
120
+ }
121
+ let liquidity = (Number(market.hypeLiquidity) + Number(market.flopLiquidity)) /
122
+ Math.pow(10, 6);
123
+ liquidity = liquidity - Number(market.marketLiquidityAtStart) / Math.pow(10, 6);
124
+ console.log('Market ID:', market.question);
125
+ console.log('Liquidity:', liquidity);
126
+ console.log('Hype Shares:', Number(market.hypeShares) / Math.pow(10, 6));
127
+ console.log('Flop Shares:', Number(market.flopShares) / Math.pow(10, 6));
128
+ let innerProfit = 0;
129
+ if (Number(market.hypePrice) > Number(market.flopPrice)) {
130
+ innerProfit += liquidity - Number(market.hypeShares) / Math.pow(10, 6);
131
+ console.log('Profit:', innerProfit);
132
+ }
133
+ if (Number(market.hypePrice) < Number(market.flopPrice)) {
134
+ innerProfit += liquidity - Number(market.flopShares) / Math.pow(10, 6);
135
+ console.log('Profit:', profit);
136
+ }
137
+ totalFlopToPay += Number(market.flopShares) / Math.pow(10, 6);
138
+ totalHypeToPay += Number(market.hypeShares) / Math.pow(10, 6);
139
+ totalLiquidity += liquidity;
140
+ profit += innerProfit;
141
+ items[market.marketId] = {
142
+ question: market.question,
143
+ liquidity: liquidity,
144
+ hypeShares: Number(market.hypeShares) / Math.pow(10, 6),
145
+ flopShares: Number(market.flopShares) / Math.pow(10, 6),
146
+ profit: innerProfit
147
+ };
148
+ console.log('--------------------------------');
149
+ }
150
+ console.log('Total Liquidity:', totalLiquidity);
151
+ console.log('Total Hype to Pay:', totalHypeToPay);
152
+ console.log('Total Flop to Pay:', totalFlopToPay);
153
+ console.log('Triad Profit:', profit);
154
+ console.table(items);
155
+ });
156
+ const getMarket = () => __awaiter(void 0, void 0, void 0, function* () {
157
+ const market = yield triadProtocol.trade.getMarketById(marketId);
158
+ console.log(market);
159
+ });
160
+ const getOrders = (walletAddress) => __awaiter(void 0, void 0, void 0, function* () {
161
+ const response = (yield triadProtocol.program.account.userTrade.all()).find((userTrade) => userTrade.account.authority.toBase58() === walletAddress.toBase58());
162
+ if (!response) {
163
+ return [];
164
+ }
165
+ let orders = [];
166
+ for (const order of response.account.orders) {
167
+ console.log(order);
168
+ if (!order.status.open) {
169
+ continue;
170
+ }
171
+ orders.push({
172
+ marketId: order.marketId.toNumber(),
173
+ orderId: order.orderId.toNumber(),
174
+ totalShares: order.totalShares.toString(),
175
+ amount: order.totalAmount.toString(),
176
+ direction: order.direction,
177
+ questionId: order.questionId.toString(),
178
+ price: order.price.toString(),
179
+ status: order.status
180
+ });
181
+ }
182
+ console.log(orders);
183
+ return orders;
184
+ });
185
+ const getAllTraders = () => __awaiter(void 0, void 0, void 0, function* () {
186
+ const response = yield triadProtocol.program.account.userTrade.all();
187
+ console.log(response);
188
+ });
189
+ const getLiquidityToRecovery = () => __awaiter(void 0, void 0, void 0, function* () {
190
+ const response = yield triadProtocol.program.account.userTrade.all();
191
+ const allMarkets = yield triadProtocol.trade.getAllMarkets();
192
+ const liquidityToRecovery = {};
193
+ for (const market of allMarkets) {
194
+ let currentMarket = liquidityToRecovery[market.marketId];
195
+ if (market.marketId === '58') {
196
+ // market.winningDirection = WinningDirection.FLOP
197
+ }
198
+ if (market.winningDirection.toLowerCase() === 'none') {
199
+ continue;
200
+ }
201
+ if (!currentMarket) {
202
+ currentMarket = {
203
+ address: market.address,
204
+ name: market.question,
205
+ liquidityAvailable: 0,
206
+ openOrders: 0,
207
+ amountInPDA: 0,
208
+ sharesToPay: 0,
209
+ direction: market.winningDirection.toLowerCase()
210
+ };
211
+ liquidityToRecovery[market.marketId] = currentMarket;
212
+ }
213
+ const liquidityAtStart = parseFloat(market.marketLiquidityAtStart.toString()) / Math.pow(10, 6);
214
+ if (currentMarket.direction === 'flop') {
215
+ currentMarket.liquidityAvailable =
216
+ parseFloat(market.hypeLiquidity.toString()) / Math.pow(10, 6);
217
+ currentMarket.liquidityAvailable =
218
+ currentMarket.liquidityAvailable - liquidityAtStart / 2;
219
+ }
220
+ if (currentMarket.direction === 'hype') {
221
+ currentMarket.liquidityAvailable =
222
+ parseFloat(market.flopLiquidity.toString()) / Math.pow(10, 6);
223
+ currentMarket.liquidityAvailable =
224
+ currentMarket.liquidityAvailable - liquidityAtStart / 2;
225
+ }
226
+ const token = yield (0, spl_token_1.getAssociatedTokenAddress)(constants_1.TRD_MINT, new web3_js_1.PublicKey(market.address), true, spl_token_1.TOKEN_2022_PROGRAM_ID);
227
+ const account = yield (0, spl_token_1.getAccount)(connection, token, 'finalized', spl_token_1.TOKEN_2022_PROGRAM_ID);
228
+ currentMarket.amountInPDA = Number(account.amount) / Math.pow(10, 6);
229
+ }
230
+ for (const userTrade of response) {
231
+ for (const order of userTrade.account.orders) {
232
+ const market = liquidityToRecovery[order.marketId.toNumber()];
233
+ if (!market) {
234
+ continue;
235
+ }
236
+ if (order.status.open &&
237
+ Object.keys(order.direction)[0] === market.direction) {
238
+ market.openOrders += 1;
239
+ const payout = parseFloat(order.totalShares.toString());
240
+ market.sharesToPay += payout / Math.pow(10, 6);
241
+ }
242
+ }
243
+ }
244
+ console.log(JSON.stringify(liquidityToRecovery, null, 2));
245
+ let amountAllowToWithdraw = 0;
246
+ let amountToPay = 0;
247
+ let amountInPDA = 0;
248
+ for (const market of Object.values(liquidityToRecovery)) {
249
+ amountAllowToWithdraw += market.amountInPDA - market.sharesToPay;
250
+ amountToPay += market.sharesToPay;
251
+ amountInPDA += market.amountInPDA;
252
+ }
253
+ console.log('Amount allow to withdraw:', amountAllowToWithdraw);
254
+ console.log('Amount to pay:', amountToPay);
255
+ console.log('Amount in PDA:', amountInPDA);
256
+ });
257
+ // Order functions
258
+ const closeOrders = () => __awaiter(void 0, void 0, void 0, function* () {
259
+ for (const order of yield getOrders(wallet.publicKey)) {
260
+ try {
261
+ const response = yield triadProtocol.trade.closeOrder({
262
+ marketId: order.marketId,
263
+ orderId: order.orderId,
264
+ userNonce: 0
265
+ });
266
+ console.log(response);
267
+ }
268
+ catch (e) {
269
+ console.log(e);
270
+ }
271
+ }
272
+ });
273
+ const resolveMarket = () => __awaiter(void 0, void 0, void 0, function* () {
274
+ const marketsToResolve = [
275
+ { marketId: 163, winningDirection: { flop: {} } },
276
+ { marketId: 164, winningDirection: { flop: {} } },
277
+ { marketId: 165, winningDirection: { flop: {} } } // Atletico Madrid
278
+ ];
279
+ for (const market of marketsToResolve) {
280
+ const response = yield triadProtocol.trade.resolveMarket({
281
+ marketId: market.marketId,
282
+ winningDirection: market.winningDirection
283
+ });
284
+ console.log(response);
285
+ }
286
+ });
287
+ const collectRemainingLiquidityFromAllMarkets = () => __awaiter(void 0, void 0, void 0, function* () {
288
+ console.log('Collecting fees');
289
+ const allMarkets = yield triadProtocol.trade.getAllMarkets();
290
+ for (const market of allMarkets) {
291
+ console.log(`Collecting fees for market ${market.marketId}`);
292
+ console.log(market);
293
+ if (market.openedOrders !== '0') {
294
+ continue;
295
+ }
296
+ try {
297
+ const response = yield triadProtocol.trade.collectRemainingLiquidity(Number(market.marketId));
298
+ console.log(response);
299
+ }
300
+ catch (_) { }
301
+ }
302
+ });
303
+ const burnLP = () => __awaiter(void 0, void 0, void 0, function* () {
304
+ const SOL_LP = new web3_js_1.PublicKey('8yXmXEQh8M1vyjKKhN6L12EZiXCY3cJS4xL45wwQExep');
305
+ const getTokenAccount = yield (0, spl_token_1.getAssociatedTokenAddress)(SOL_LP, wallet.publicKey, true);
306
+ console.log(getTokenAccount);
307
+ const amount = 191.360098123 * Math.pow(10, 9);
308
+ const response = yield (0, spl_token_1.burn)(connection, keypair, getTokenAccount, SOL_LP, wallet.publicKey, amount);
309
+ console.log(response);
310
+ });
311
+ const mintToken = () => __awaiter(void 0, void 0, void 0, function* () {
312
+ const filekey = fs_1.default.readFileSync('./tCMraBSGHeMcQS76hNnBhnfbMzrtnnT3nbt3vAnSCE2.json');
313
+ const token = web3_js_1.Keypair.fromSecretKey(new Uint8Array(JSON.parse(filekey.toString())));
314
+ try {
315
+ const decimals = 6; // Common decimal places for tokens
316
+ const amount = 1000000 * Math.pow(10, decimals); // 1,000,000 tokens with decimals
317
+ // Token creation code is commented out in the original
318
+ // Keeping it commented out here as well
319
+ }
320
+ catch (e) {
321
+ console.log(e);
322
+ }
323
+ });
324
+ const updateTokenMetadata = () => __awaiter(void 0, void 0, void 0, function* () {
325
+ const mintTransaction = new web3_js_1.Transaction().add((0, spl_token_1.createUpdateFieldInstruction)({
326
+ programId: spl_token_1.TOKEN_2022_PROGRAM_ID,
327
+ metadata: new web3_js_1.PublicKey('tCMraBSGHeMcQS76hNnBhnfbMzrtnnT3nbt3vAnSCE2'),
328
+ updateAuthority: wallet.publicKey,
329
+ field: 'uri',
330
+ value: 'https://shdw-drive.genesysgo.net/DRRe9dZkP199W6GLrySn2xj2ayfr8gin8iaBt1YVMN9M/tEVENT.json'
331
+ }));
332
+ const transactionSignature = yield (0, web3_js_1.sendAndConfirmTransaction)(connection, mintTransaction, [keypair] // Signers
333
+ );
334
+ console.log(transactionSignature);
335
+ });
336
+ const withdrawPoseidon = () => __awaiter(void 0, void 0, void 0, function* () {
337
+ const response = yield triadProtocol.withdrawPoseidon({
338
+ poseidonAsset: new web3_js_1.PublicKey('DMoyQ6pAj9bGu3WoMcVeYv4rgrU96Xjzyzudfs4fkJw3'),
339
+ nft: 430
340
+ });
341
+ console.log(response);
342
+ });
343
+ const openOrderTriad = () => __awaiter(void 0, void 0, void 0, function* () {
344
+ const response3 = yield triadProtocol.trade.openOrder({
345
+ marketId: marketId,
346
+ amount: 1000,
347
+ direction: {
348
+ hype: {}
349
+ },
350
+ token: constants_1.TRD_MINT.toBase58()
351
+ });
352
+ console.log(response3);
353
+ yield getMarket();
354
+ });
355
+ const closeOrderTriad = () => __awaiter(void 0, void 0, void 0, function* () {
356
+ const response = yield triadProtocol.trade.closeOrder({
357
+ marketId: marketId,
358
+ orderId: 1,
359
+ userNonce: 8
360
+ });
361
+ console.log(response);
362
+ });
363
+ const collectRoyalties = () => __awaiter(void 0, void 0, void 0, function* () {
364
+ const response = yield triadProtocol.collectRoyalty(constants_1.POSEIDON_COLLECTION_SYMBOL, {
365
+ skipPreflight: false
366
+ });
367
+ console.log(response);
368
+ });
369
+ const collectRemainingLiquidity = () => __awaiter(void 0, void 0, void 0, function* () {
370
+ const markets = [34];
371
+ for (const market of markets) {
372
+ const response = yield triadProtocol.trade.collectRemainingLiquidity(market);
373
+ console.log(response);
374
+ }
375
+ });
376
+ const allowMarketToPayout = () => __awaiter(void 0, void 0, void 0, function* () {
377
+ const markets = [163, 164, 165];
378
+ for (const market of markets) {
379
+ try {
380
+ const response = yield triadProtocol.trade.allowMarketToPayout(Number(market));
381
+ console.log(response);
382
+ }
383
+ catch (error) {
384
+ console.log(error);
385
+ }
386
+ }
387
+ });
388
+ const getUserOrders = () => __awaiter(void 0, void 0, void 0, function* () {
389
+ const response = yield triadProtocol.trade.getUserOrders(wallet.publicKey);
390
+ const filteredResponse = response.filter((order) => order.marketId === marketId.toString());
391
+ console.log(response);
392
+ });
393
+ const updateMarket = () => __awaiter(void 0, void 0, void 0, function* () {
394
+ const response = yield triadProtocol.trade.updateMarket(128, 1751327940);
395
+ console.log(response);
396
+ });
397
+ const getStorage = () => __awaiter(void 0, void 0, void 0, function* () {
398
+ const drive = yield new sdk_1.ShdwDrive(triadProtocol.provider.connection, triadProtocol.provider.wallet).init();
399
+ console.log(yield drive.getStorageAccount(new web3_js_1.PublicKey('DRRe9dZkP199W6GLrySn2xj2ayfr8gin8iaBt1YVMN9M')));
400
+ const jsonFile = {
401
+ name: `tCMAS.json`,
402
+ file: fs_1.default.readFileSync(`./src/tCMAS.json`)
403
+ };
404
+ const file = yield drive.editFile(new web3_js_1.PublicKey('DRRe9dZkP199W6GLrySn2xj2ayfr8gin8iaBt1YVMN9M'), jsonFile);
405
+ console.log(file);
406
+ return file;
407
+ });
408
+ const deployImage = (image) => __awaiter(void 0, void 0, void 0, function* () {
409
+ const TRIAD_STORAGE_ACCOUNT = new web3_js_1.PublicKey('DRRe9dZkP199W6GLrySn2xj2ayfr8gin8iaBt1YVMN9M');
410
+ const drive = yield new sdk_1.ShdwDrive(triadProtocol.provider.connection, triadProtocol.provider.wallet).init();
411
+ const jsonFile = {
412
+ name: `${image}`,
413
+ file: fs_1.default.readFileSync(`./src/${image}`)
414
+ };
415
+ const file = yield drive.uploadFile(TRIAD_STORAGE_ACCOUNT, jsonFile);
416
+ console.log(file);
417
+ return file;
418
+ });
@@ -0,0 +1,8 @@
1
+ import TriadProtocol from '..';
2
+ export declare class InitMarket {
3
+ private triadProtocol;
4
+ private markets;
5
+ constructor(triadProtocol: TriadProtocol);
6
+ initializeMarkets: () => Promise<void>;
7
+ deployImage: (image: string) => Promise<any>;
8
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.InitMarket = void 0;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const web3_js_1 = require("@solana/web3.js");
18
+ const sdk_1 = require("@shadow-drive/sdk");
19
+ class InitMarket {
20
+ constructor(triadProtocol) {
21
+ this.markets = [];
22
+ this.initializeMarkets = () => __awaiter(this, void 0, void 0, function* () {
23
+ for (const market of this.markets) {
24
+ try {
25
+ const response = yield this.triadProtocol.trade.createMarket({
26
+ marketId: market.marketId,
27
+ question: market.question,
28
+ startTime: market.startTime,
29
+ endTime: market.endTime,
30
+ feeBps: 0,
31
+ customer: null,
32
+ liquidityAtStart: 12000
33
+ });
34
+ if (market.image) {
35
+ yield this.deployImage(market.image);
36
+ }
37
+ console.log(`Initialized market ${market.question}:`, response);
38
+ }
39
+ catch (error) {
40
+ console.error(`Error initializing market ${market.question}:`, error);
41
+ }
42
+ }
43
+ });
44
+ this.deployImage = (image) => __awaiter(this, void 0, void 0, function* () {
45
+ const TRIAD_STORAGE_ACCOUNT = new web3_js_1.PublicKey('8Tp66VQmgHXQfd8ui2VZHPLZfkKu8mMwywmRsnVfTRBm');
46
+ const drive = yield new sdk_1.ShdwDrive(this.triadProtocol.provider.connection, this.triadProtocol.provider.wallet).init();
47
+ const jsonFile = {
48
+ name: `${image}`,
49
+ file: fs_1.default.readFileSync(`./src/${image}`)
50
+ };
51
+ const file = yield drive.uploadFile(TRIAD_STORAGE_ACCOUNT, jsonFile);
52
+ console.log(file);
53
+ return file;
54
+ });
55
+ this.triadProtocol = triadProtocol;
56
+ }
57
+ }
58
+ exports.InitMarket = InitMarket;
@@ -0,0 +1,9 @@
1
+ export declare class OrderBook {
2
+ private bids;
3
+ private asks;
4
+ constructor();
5
+ addBid(price: number, quantity: number): void;
6
+ addAsk(price: number, quantity: number): void;
7
+ matchOrders(): void;
8
+ printOrderBook(): void;
9
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OrderBook = void 0;
4
+ class OrderBook {
5
+ constructor() {
6
+ this.bids = [];
7
+ this.asks = [];
8
+ this.bids = []; // Lista de compras (bids)
9
+ this.asks = []; // Lista de vendas (asks)
10
+ }
11
+ addBid(price, quantity) {
12
+ this.bids.push({ price, quantity });
13
+ this.bids.sort((a, b) => b.price - a.price);
14
+ this.matchOrders();
15
+ }
16
+ addAsk(price, quantity) {
17
+ this.asks.push({ price, quantity });
18
+ this.asks.sort((a, b) => a.price - b.price);
19
+ this.matchOrders();
20
+ }
21
+ matchOrders() {
22
+ while (this.bids.length > 0 && this.asks.length > 0) {
23
+ let highestBid = this.bids[0];
24
+ let lowestAsk = this.asks[0];
25
+ if (highestBid.price >= lowestAsk.price) {
26
+ let tradeQuantity = Math.min(highestBid.quantity, lowestAsk.quantity);
27
+ console.log(`šŸ”„ Trade Executado: ${tradeQuantity} unidades a ${lowestAsk.price}`);
28
+ highestBid.quantity -= tradeQuantity;
29
+ lowestAsk.quantity -= tradeQuantity;
30
+ if (highestBid.quantity === 0)
31
+ this.bids.shift();
32
+ if (lowestAsk.quantity === 0)
33
+ this.asks.shift();
34
+ }
35
+ else {
36
+ break;
37
+ }
38
+ }
39
+ }
40
+ printOrderBook() {
41
+ console.log('\nšŸ“Š ORDER BOOK:');
42
+ console.log('BIDS (Compradores):', this.bids);
43
+ console.log('ASKS (Vendedores):', this.asks);
44
+ }
45
+ }
46
+ exports.OrderBook = OrderBook;
@@ -0,0 +1,5 @@
1
+ import TriadProtocol from '..';
2
+ export declare class SimulateMarket {
3
+ private triadProtocol;
4
+ constructor(triadProtocol: TriadProtocol);
5
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimulateMarket = void 0;
4
+ class SimulateMarket {
5
+ constructor(triadProtocol) {
6
+ this.triadProtocol = triadProtocol;
7
+ }
8
+ }
9
+ exports.SimulateMarket = SimulateMarket;
package/dist/stake.js CHANGED
@@ -51,14 +51,8 @@ class Stake {
51
51
  */
52
52
  getUserStakes(wallet) {
53
53
  return __awaiter(this, void 0, void 0, function* () {
54
- const response = yield this.program.account.stakeV2.all([
55
- {
56
- memcmp: {
57
- offset: 8 + 1,
58
- bytes: wallet.toBase58()
59
- }
60
- }
61
- ]);
54
+ const stakes = yield this.program.account.stakeV2.all();
55
+ const response = stakes.filter((stake) => stake.account.authority.toBase58() === wallet.toBase58());
62
56
  return response.map((stake) => (0, helpers_1.formatStake)(stake.account));
63
57
  });
64
58
  }
package/dist/trade.d.ts CHANGED
@@ -130,7 +130,7 @@ export default class Trade {
130
130
  * @param options - RPC options
131
131
  *
132
132
  */
133
- createMarket({ marketId, startTime, endTime, question, feeBps, customer }: CreateMarketArgs, options?: RpcOptions): Promise<string>;
133
+ createMarket({ marketId, startTime, endTime, question, feeBps, customer, liquidityAtStart }: CreateMarketArgs, options?: RpcOptions): Promise<string>;
134
134
  /**
135
135
  * Get User Trade Nonce With Slots
136
136
  * @param userTrades - User Trades
package/dist/trade.js CHANGED
@@ -114,7 +114,7 @@ class Trade {
114
114
  * @param options - RPC options
115
115
  *
116
116
  */
117
- createMarket({ marketId, startTime, endTime, question, feeBps, customer }, options) {
117
+ createMarket({ marketId, startTime, endTime, question, feeBps, customer, liquidityAtStart }, options) {
118
118
  return __awaiter(this, void 0, void 0, function* () {
119
119
  if (question.length > 80) {
120
120
  throw new Error('Question must be less than 80 characters');
@@ -125,6 +125,7 @@ class Trade {
125
125
  question: (0, helpers_1.encodeString)(question, 80),
126
126
  marketStart: new bn_js_1.default(startTime),
127
127
  marketEnd: new bn_js_1.default(endTime),
128
+ liquidityAtStart: new bn_js_1.default(liquidityAtStart * Math.pow(10, constants_1.TRD_DECIMALS)),
128
129
  feeBps
129
130
  })
130
131
  .accounts({
@@ -1706,6 +1706,10 @@
1706
1706
  {
1707
1707
  "name": "fee_bps",
1708
1708
  "type": "u8"
1709
+ },
1710
+ {
1711
+ "name": "liquidity_at_start",
1712
+ "type": "u64"
1709
1713
  }
1710
1714
  ]
1711
1715
  }
@@ -86,6 +86,7 @@ export type CreateMarketArgs = {
86
86
  question: string;
87
87
  feeBps: number;
88
88
  customer: PublicKey;
89
+ liquidityAtStart: number;
89
90
  };
90
91
  export type CreateCustomerArgs = {
91
92
  id: number;
@@ -2205,6 +2205,10 @@ export type TriadProtocol = {
2205
2205
  {
2206
2206
  name: 'feeBps';
2207
2207
  type: 'u8';
2208
+ },
2209
+ {
2210
+ name: 'liquidityAtStart';
2211
+ type: 'u64';
2208
2212
  }
2209
2213
  ];
2210
2214
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triadxyz/triad-protocol",
3
- "version": "1.7.0-beta",
3
+ "version": "1.7.1-beta",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",