@tradelayerprotocol/tradelayer 1.9.1

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.
Files changed (249) hide show
  1. package/.claude/settings.local.json +13 -0
  2. package/.claude/skills/tl-algo/SKILL.md +255 -0
  3. package/.gitattributes +2 -0
  4. package/.github/workflows/publish.yaml +26 -0
  5. package/4mm.js +163 -0
  6. package/LICENSE +21 -0
  7. package/NPMSwapRefactor.zip +0 -0
  8. package/README.md +217 -0
  9. package/address.sh +26 -0
  10. package/algoAPI.js +581 -0
  11. package/analyzepsbt.js +92 -0
  12. package/apiEx.js +99 -0
  13. package/bb_hyperscalper.js +290 -0
  14. package/bbo_demo.js +111 -0
  15. package/buyer.js +622 -0
  16. package/client.js +50 -0
  17. package/createTxTest.js +26 -0
  18. package/createWallet.js +75 -0
  19. package/daytrader.js +531 -0
  20. package/decodeTest.js +69 -0
  21. package/fundingManager.js +144 -0
  22. package/index.js +4 -0
  23. package/listener.js +27 -0
  24. package/litecoreTxBuilder.js +1128 -0
  25. package/mmEx.js +356 -0
  26. package/networks.js +51 -0
  27. package/orderbook.js +200 -0
  28. package/package.json +34 -0
  29. package/perTradeQueue.js +36 -0
  30. package/projectsTLNPMTLNPM/package-lock.json +162 -0
  31. package/projectsTLNPMTLNPM/package.json +5 -0
  32. package/quick.js +32 -0
  33. package/quickFut.js +37 -0
  34. package/quickSell.js +37 -0
  35. package/relayerClient.js +117 -0
  36. package/run4mm.js +80 -0
  37. package/run_bbo_tracker.js +241 -0
  38. package/seller.js +443 -0
  39. package/session.js +45 -0
  40. package/setup-lin-ltc.sh +139 -0
  41. package/setup-lin.sh +203 -0
  42. package/setup-win-ltc.bat +108 -0
  43. package/setup-win.bat +167 -0
  44. package/spam_screamer_futures.js +222 -0
  45. package/tradelayer.js/.gitattributes +2 -0
  46. package/tradelayer.js/README.md +2 -0
  47. package/tradelayer.js/oldTests/activationTest.js +6 -0
  48. package/tradelayer.js/oldTests/base58.test.js +23 -0
  49. package/tradelayer.js/oldTests/base64Decode.test.js +16 -0
  50. package/tradelayer.js/oldTests/blocksRefactor.js +140 -0
  51. package/tradelayer.js/oldTests/checkVestBalance.js +25 -0
  52. package/tradelayer.js/oldTests/consensusHashProto.js +151 -0
  53. package/tradelayer.js/oldTests/contractOrderbook.js +243 -0
  54. package/tradelayer.js/oldTests/createPayload.js +0 -0
  55. package/tradelayer.js/oldTests/createTestnetAddr.js +43 -0
  56. package/tradelayer.js/oldTests/decode.js +205 -0
  57. package/tradelayer.js/oldTests/decodeTest.js +50 -0
  58. package/tradelayer.js/oldTests/displayTallyMap.js +19 -0
  59. package/tradelayer.js/oldTests/encodeDecode.js +340 -0
  60. package/tradelayer.js/oldTests/expressTest.js +29 -0
  61. package/tradelayer.js/oldTests/extractBlocksVanilla.js +214 -0
  62. package/tradelayer.js/oldTests/extractBlocksVanillaa.js +179 -0
  63. package/tradelayer.js/oldTests/extractPubkeyTest.js +60 -0
  64. package/tradelayer.js/oldTests/fillInputCacheProto.js +111 -0
  65. package/tradelayer.js/oldTests/getRawTxTest.js +22 -0
  66. package/tradelayer.js/oldTests/indexTest.js +26 -0
  67. package/tradelayer.js/oldTests/initTokensTest.js +32 -0
  68. package/tradelayer.js/oldTests/interfaceChild.js +129 -0
  69. package/tradelayer.js/oldTests/listenerChild.js +112 -0
  70. package/tradelayer.js/oldTests/opdecode.js +26 -0
  71. package/tradelayer.js/oldTests/options.js +79 -0
  72. package/tradelayer.js/oldTests/optxtest.js +116 -0
  73. package/tradelayer.js/oldTests/optxtest1.js +64 -0
  74. package/tradelayer.js/oldTests/oracle.test.js +32 -0
  75. package/tradelayer.js/oldTests/orderbook.test.js +36 -0
  76. package/tradelayer.js/oldTests/parsing.js +93 -0
  77. package/tradelayer.js/oldTests/payload.js +13 -0
  78. package/tradelayer.js/oldTests/persistenceUnitTest.js +23 -0
  79. package/tradelayer.js/oldTests/property.test.js +53 -0
  80. package/tradelayer.js/oldTests/propertyLevel.js +75 -0
  81. package/tradelayer.js/oldTests/propertyTest.js +32 -0
  82. package/tradelayer.js/oldTests/queryAddressTest.js +17 -0
  83. package/tradelayer.js/oldTests/salter.js +14 -0
  84. package/tradelayer.js/oldTests/tally.js +81 -0
  85. package/tradelayer.js/oldTests/tally.test.js +48 -0
  86. package/tradelayer.js/oldTests/tally2.js +124 -0
  87. package/tradelayer.js/oldTests/tally3.js +142 -0
  88. package/tradelayer.js/oldTests/tallyDiag.js +38 -0
  89. package/tradelayer.js/oldTests/testGetRaw.js +40 -0
  90. package/tradelayer.js/oldTests/testHexConvert.js +47 -0
  91. package/tradelayer.js/oldTests/testNewEncoding.js +96 -0
  92. package/tradelayer.js/oldTests/testNewEncoding2.js +113 -0
  93. package/tradelayer.js/oldTests/testNewEncoding3 +112 -0
  94. package/tradelayer.js/oldTests/testNewEncoding3.js +168 -0
  95. package/tradelayer.js/oldTests/testOPReturn.js +102 -0
  96. package/tradelayer.js/oldTests/testPayload.js +23 -0
  97. package/tradelayer.js/oldTests/testRaw.js +50 -0
  98. package/tradelayer.js/oldTests/testSendTooMuch.js +20 -0
  99. package/tradelayer.js/oldTests/testTxBuild +28 -0
  100. package/tradelayer.js/oldTests/testTxBuild.js +42 -0
  101. package/tradelayer.js/oldTests/tokenOrderbook.js +243 -0
  102. package/tradelayer.js/oldTests/txUtilsA.js +515 -0
  103. package/tradelayer.js/oldTests/validityUnitTest.js +53 -0
  104. package/tradelayer.js/oldTests/vaults.js +72 -0
  105. package/tradelayer.js/oldTests/volumeIndex.js +117 -0
  106. package/tradelayer.js/oldTests/volumeIndex2.js +88 -0
  107. package/tradelayer.js/output_base64.txt +1 -0
  108. package/tradelayer.js/package-lock.json +9967 -0
  109. package/tradelayer.js/package.json +61 -0
  110. package/tradelayer.js/server/index.js +88 -0
  111. package/tradelayer.js/server/litecoind.exe +0 -0
  112. package/tradelayer.js/src/activation.js +303 -0
  113. package/tradelayer.js/src/adjuster.js +77 -0
  114. package/tradelayer.js/src/amm.js +400 -0
  115. package/tradelayer.js/src/base256.js +55 -0
  116. package/tradelayer.js/src/base94.js +79 -0
  117. package/tradelayer.js/src/channels.js +1163 -0
  118. package/tradelayer.js/src/clearing.js +3109 -0
  119. package/tradelayer.js/src/clearlist.js +364 -0
  120. package/tradelayer.js/src/client.js +295 -0
  121. package/tradelayer.js/src/consensus.js +613 -0
  122. package/tradelayer.js/src/contractRegistry.js +964 -0
  123. package/tradelayer.js/src/db.js +89 -0
  124. package/tradelayer.js/src/init.js +24 -0
  125. package/tradelayer.js/src/insurance.js +347 -0
  126. package/tradelayer.js/src/interface.js +218 -0
  127. package/tradelayer.js/src/interfaceExpress.js +178 -0
  128. package/tradelayer.js/src/iou.js +509 -0
  129. package/tradelayer.js/src/listener.js +226 -0
  130. package/tradelayer.js/src/logic.js +1702 -0
  131. package/tradelayer.js/src/main.js +927 -0
  132. package/tradelayer.js/src/marginMap.js +2165 -0
  133. package/tradelayer.js/src/options.js +126 -0
  134. package/tradelayer.js/src/oracle.js +394 -0
  135. package/tradelayer.js/src/orderbook.js +4123 -0
  136. package/tradelayer.js/src/persistence.js +554 -0
  137. package/tradelayer.js/src/property.js +411 -0
  138. package/tradelayer.js/src/reOrg.js +41 -0
  139. package/tradelayer.js/src/scaling.js +145 -0
  140. package/tradelayer.js/src/tally.js +1275 -0
  141. package/tradelayer.js/src/tradeHistoryManager.js +552 -0
  142. package/tradelayer.js/src/txDecoder.js +584 -0
  143. package/tradelayer.js/src/txEncoder.js +610 -0
  144. package/tradelayer.js/src/txIndex.js +502 -0
  145. package/tradelayer.js/src/txUtils.js +1392 -0
  146. package/tradelayer.js/src/types.js +429 -0
  147. package/tradelayer.js/src/validity.js +3077 -0
  148. package/tradelayer.js/src/vaults.js +430 -0
  149. package/tradelayer.js/src/vesting.js +491 -0
  150. package/tradelayer.js/src/volumeIndex.js +618 -0
  151. package/tradelayer.js/src/walletInterface.js +220 -0
  152. package/tradelayer.js/src/walletListener.js +665 -0
  153. package/tradelayer.js/tests/256decode.js +82 -0
  154. package/tradelayer.js/tests/UTXOracle.js +205 -0
  155. package/tradelayer.js/tests/base94test.js +23 -0
  156. package/tradelayer.js/tests/cancelTxTest.js +62 -0
  157. package/tradelayer.js/tests/contractInterfaceTest.js +48 -0
  158. package/tradelayer.js/tests/decimalTest.js +65 -0
  159. package/tradelayer.js/tests/decoderTest.js +100 -0
  160. package/tradelayer.js/tests/deltaCount.js +47 -0
  161. package/tradelayer.js/tests/deltaCount2.js +60 -0
  162. package/tradelayer.js/tests/interfaceTest.js +37 -0
  163. package/tradelayer.js/tests/mainTest.js +53 -0
  164. package/tradelayer.js/tests/makeActivationTest.js +24 -0
  165. package/tradelayer.js/tests/maxHeightTest.js +49 -0
  166. package/tradelayer.js/tests/reverseHash.js +72 -0
  167. package/tradelayer.js/tests/sensitiveConsoleOutput.txt +267 -0
  168. package/tradelayer.js/tests/tallyTest.js +40 -0
  169. package/tradelayer.js/tests/testBuybacks.js +46 -0
  170. package/tradelayer.js/tests/testCodeHash.js +49 -0
  171. package/tradelayer.js/tests/testConsensusHash.js +91 -0
  172. package/tradelayer.js/tests/testDecode.js +30 -0
  173. package/tradelayer.js/tests/testEncodingLengths.js +129 -0
  174. package/tradelayer.js/tests/testGetTx +32 -0
  175. package/tradelayer.js/tests/testGetTx.js +32 -0
  176. package/tradelayer.js/tests/testHexHash.js +32 -0
  177. package/tradelayer.js/tests/testIndexHash.js +35 -0
  178. package/tradelayer.js/tests/testInitContracts.js +38 -0
  179. package/tradelayer.js/tests/testMaxConsensus.js +12 -0
  180. package/tradelayer.js/tests/testMaxSynth.js +44 -0
  181. package/tradelayer.js/tests/testMint.js +21 -0
  182. package/tradelayer.js/tests/testNetwork.js +33 -0
  183. package/tradelayer.js/tests/testOrderbookLoad.js +62 -0
  184. package/tradelayer.js/tests/testRebates.js +32 -0
  185. package/tradelayer.js/tests/testRedeem.js +22 -0
  186. package/tradelayer.js/tests/testTokenTrade.js +39 -0
  187. package/tradelayer.js/tests/testTxBuild.js +42 -0
  188. package/tradelayer.js/tests/testUTXOTrade.js +27 -0
  189. package/tradelayer.js/tests/tokenTradeHistory.js +27 -0
  190. package/tradelayer.js/tests/tradeFutures.js +40 -0
  191. package/tradelayer.js/tests/tradeHistoryExample.js +35 -0
  192. package/tradelayer.js/tests/tradeHistoryLoad.js +15 -0
  193. package/tradelayer.js/tests/txScanTest.js +134 -0
  194. package/tradelayer.js/tests/validateTest.js +136 -0
  195. package/tradelayer.js/tests/vestingTest.js +37 -0
  196. package/tradelayer.js/utils/activateMainnet.js +59 -0
  197. package/tradelayer.js/utils/activateMainnetDoge.js +63 -0
  198. package/tradelayer.js/utils/autocompactdb.js +23 -0
  199. package/tradelayer.js/utils/base64toHex.js +32 -0
  200. package/tradelayer.js/utils/broadcastDoge.js +38 -0
  201. package/tradelayer.js/utils/calcRedeem.js +19 -0
  202. package/tradelayer.js/utils/checkNetwork.js +27 -0
  203. package/tradelayer.js/utils/createAddress.js +48 -0
  204. package/tradelayer.js/utils/createAttestation.js +133 -0
  205. package/tradelayer.js/utils/createContract.js +118 -0
  206. package/tradelayer.js/utils/createOracle.js +94 -0
  207. package/tradelayer.js/utils/createwallet.js +20 -0
  208. package/tradelayer.js/utils/crossFuturesTrades.js +57 -0
  209. package/tradelayer.js/utils/crossTokenTrades.js +62 -0
  210. package/tradelayer.js/utils/dumpPriv.js +29 -0
  211. package/tradelayer.js/utils/generateChannel.js +34 -0
  212. package/tradelayer.js/utils/getInfo.js +21 -0
  213. package/tradelayer.js/utils/hardWipe.js +20 -0
  214. package/tradelayer.js/utils/hexTo64.js +16 -0
  215. package/tradelayer.js/utils/importAddress.js +28 -0
  216. package/tradelayer.js/utils/importpriv.js +20 -0
  217. package/tradelayer.js/utils/issueOracleContract.js +67 -0
  218. package/tradelayer.js/utils/issueTokens.js +41 -0
  219. package/tradelayer.js/utils/listunspent.js +66 -0
  220. package/tradelayer.js/utils/litecoinClient.js +30 -0
  221. package/tradelayer.js/utils/loadwallet.js +20 -0
  222. package/tradelayer.js/utils/publishOracle.js +113 -0
  223. package/tradelayer.js/utils/sendActivation.js +21 -0
  224. package/tradelayer.js/utils/sendChannelContractTrade.js +34 -0
  225. package/tradelayer.js/utils/sendChannelTokenTrade.js +34 -0
  226. package/tradelayer.js/utils/sendCommit.js +24 -0
  227. package/tradelayer.js/utils/sendDoge.js +62 -0
  228. package/tradelayer.js/utils/sendDogeMain.js +67 -0
  229. package/tradelayer.js/utils/sendDogeTx.js +46 -0
  230. package/tradelayer.js/utils/sendLTC.js +63 -0
  231. package/tradelayer.js/utils/sendMainnet.js +62 -0
  232. package/tradelayer.js/utils/sendTransfer.js +19 -0
  233. package/tradelayer.js/utils/sendVestTest.js +88 -0
  234. package/tradelayer.js/utils/sendWithdrawal.js +26 -0
  235. package/tradelayer.js/utils/simpleStart.js +8 -0
  236. package/tradelayer.js/utils/startStop.js +27 -0
  237. package/tradelayer.js/utils/structuredTrades.js +136 -0
  238. package/tradelayer.js/utils/verifySignature.js +90 -0
  239. package/tradelayer.js/utils/verifyWitnessAndScriptPubkey.js +41 -0
  240. package/tradelayer.js/utils/walletCache.js +172 -0
  241. package/tradelayer.js/utils/walletContractInterface.js +48 -0
  242. package/tradelayer.js/utils/walletFetchTxs.js +66 -0
  243. package/tradelayer.js/utils/walletUtils.js +97 -0
  244. package/tradelayer.js/utils/wipeDB.js +55 -0
  245. package/tradelayer.js/utils/wipeDBNotTx.js +50 -0
  246. package/txEncoder.js +529 -0
  247. package/utility.js +28 -0
  248. package/verifymessage.js +38 -0
  249. package/ws-transport.js +311 -0
@@ -0,0 +1,665 @@
1
+ const ClientWrapper = require('./client.js');
2
+ const express = require('express');
3
+ const axios = require('axios');
4
+ const TallyMap = require('./tally.js');
5
+ const TxIndex = require('./txIndex.js');
6
+ const PropertyManager = require('./property.js');
7
+ const Main = require('./main.js');
8
+ const Activations = require('./activation.js');
9
+ const Orderbook = require('./orderbook.js');
10
+ const ContractRegistry = require('./contractRegistry.js');
11
+ const OracleList = require('./oracle.js');
12
+ const MarginMap = require('./marginMap.js');
13
+ const TxUtils = require('./txUtils.js')
14
+ const Consensus = require('./consensus.js')
15
+ const Channels = require('./channels.js')
16
+ const Types = require('./types.js')
17
+ const ClearList = require('./clearlist.js')
18
+ const Clearing = require('./clearing.js')
19
+ const TradeHistory = require('./tradeHistoryManager.js')
20
+ const VolumeIndex = require('./volumeIndex.js')
21
+ const db = require('./db.js')
22
+
23
+ let isInitialized = false; // A flag to track the initialization status
24
+ const app = express();
25
+ const port = 3000; // Choose a port that suits your setup
26
+
27
+ app.use(express.json()); // Middleware to parse JSON bodies
28
+
29
+ // Function to check if the ClientWrapper is ready (with retries)
30
+ async function waitForClientWrapper(maxRetries = 10, interval = 500) {
31
+ let retries = 0;
32
+ while (retries < maxRetries) {
33
+ try {
34
+ const client = await ClientWrapper.getInstance(); // Check if client is ready
35
+ if (client.chain) {
36
+ console.log('Client is ready.');
37
+ return client;
38
+ }
39
+ } catch (error) {
40
+ console.log('ClientWrapper initialization not ready, retrying...');
41
+ }
42
+ retries++;
43
+ await new Promise(resolve => setTimeout(resolve, interval)); // Wait for interval before retrying
44
+ }
45
+ throw new Error('ClientWrapper failed to initialize after max retries.');
46
+ }
47
+
48
+ let lastInitCall = Date.now();
49
+
50
+ // Initialize Main once ClientWrapper is ready
51
+ app.post('/tl_initmain', async (req, res) => {
52
+ const tradeHistory = await TradeHistory.getTokenTradeHistoryForAddress(0, 1,'tltc1q89kkgaslk0lt8l90jkl3cgwg7dkkszn73u4d2t');
53
+ console.log('trade history '+JSON.stringify(tradeHistory))
54
+ try {
55
+
56
+ if(req.wallet){
57
+ const now = Date.now();
58
+ if (now - lastInitCall < 30000) { // Only allow one call per second, adjust timing as needed
59
+ return res.status(429).send('Too many requests'); // Or simply ignore this call
60
+ }
61
+ lastInitCall = now;
62
+ }
63
+
64
+ if (!isInitialized) {
65
+ console.log('Waiting for ClientWrapper initialization...');
66
+ const client = await waitForClientWrapper(); // Ensure ClientWrapper is initialized
67
+
68
+ console.log('Client and Database initialized successfully.');
69
+
70
+ // Initialize Main only after ClientWrapper is ready
71
+ const mainProcessor = await Main.getInstance(client); // Pass client to Main
72
+ mainProcessor.initialize();
73
+
74
+ isInitialized = true; // Mark as initialized
75
+ res.status(200).send('Main process initialized successfully');
76
+ } else {
77
+ res.status(200).send('Main process already initialized');
78
+ }
79
+ } catch (error) {
80
+ console.error('Error during initialization:', error);
81
+ res.status(500).send('Error: ' + error.message);
82
+ }
83
+ });
84
+ // Validate address
85
+ app.post('/tl_validateaddress', async (req, res) => {
86
+ try {
87
+ const { address } = req.body;
88
+ const validationResponse = await TxUtils.validateAddress(address)
89
+ res.json(validationResponse);
90
+ } catch (error) {
91
+ console.error('Error validating address:', error);
92
+ res.status(500).send('Error: ' + error.message);
93
+ }
94
+ });
95
+
96
+
97
+ app.post('/tl_getTransaction', async (req, res) => {
98
+ try {
99
+ const { txid } = req.body;
100
+ const txInfo = await Consensus.getTxParams(txid)
101
+ res.json(txInfo);
102
+ } catch (error) {
103
+ console.error('Error validating address:', error);
104
+ res.status(500).send('Error: ' + error.message);
105
+ }
106
+ });
107
+
108
+ app.post('/tl_getChannelColumn', async (req,res) =>{
109
+ try {
110
+ const { channelAddress, newCommitAddress, cpAddress } = req.body;
111
+ const column = await Channels.predictColumnForAddress(channelAddress, newCommitAddress, cpAddress)
112
+ res.json(column);
113
+ } catch (error) {
114
+ console.error('Error validating address:', error);
115
+ res.status(500).send('Error: ' + error.message);
116
+ }
117
+ })
118
+
119
+ app.post('/tl_getAttestations', async (req, res) => {
120
+ try {
121
+ const { address, id } = req.body;
122
+
123
+ // Fetch and sort attestations
124
+ const attestationHistory = await ClearList.getAttestationHistory(address, id);
125
+
126
+ res.json(attestationHistory); // Send the sorted array back
127
+ } catch (error) {
128
+ console.error('Error validating address:', error);
129
+ res.status(500).send('Error: ' + error.message);
130
+ }
131
+ });
132
+
133
+
134
+ /*app.post('/tl_decodeTx', async (req, res) => {
135
+ try {
136
+ const { txid } = req.body;
137
+ const txData = await TxIndex.getTx(txid)
138
+ const txId = txData.value[0].txId;
139
+
140
+ res.json(txInfo);
141
+ } catch (error) {
142
+ console.error('Error validating address:', error);
143
+ res.status(500).send('Error: ' + error.message);
144
+ }
145
+ });*/
146
+
147
+ app.post('./tl_loadWallet', async (req, res) => {
148
+ try {
149
+ const {} = req.body;
150
+ const wallet = TxUtils.load()
151
+ res.json('loading wallet');
152
+ } catch (error) {
153
+ console.error('Error validating address:', error);
154
+ res.status(500).send('Error: ' + error.message);
155
+ }
156
+ });
157
+
158
+ app.post('/tl_gettransactionsforaddress', async (req, res) => {
159
+ try {
160
+ const { address } = req.body;
161
+ const txInfo = await Consensus.getTxParamsForAddress(address)
162
+ res.json(txInfo);
163
+ } catch (error) {
164
+ console.error('Error validating address:', error);
165
+ res.status(500).send('Error: ' + error.message);
166
+ }
167
+ });
168
+
169
+
170
+ app.post('/tl_gettransactionforblock', async (req, res) => {
171
+ try {
172
+ const { blockHeight } = req.body;
173
+ const txInfo = await Consensus.getTxParamsForBlock(blockHeight)
174
+ res.json(txInfo);
175
+ } catch (error) {
176
+ console.error('Error validating address:', error);
177
+ res.status(500).send('Error: ' + error.message);
178
+ }
179
+ });
180
+
181
+ app.post('/tl_getMaxProcessedHeight', async (req, res) => {
182
+ try {
183
+ const {} = req.body;
184
+ const txInfo = await Consensus.getMaxProcessedBlock()
185
+ res.json(txInfo);
186
+ } catch (error) {
187
+ console.error('Error validating address:', error);
188
+ res.status(500).send('Error: ' + error.message);
189
+ }
190
+ });
191
+
192
+ app.post('/tl_getMaxParsedHeight', async (req, res) => {
193
+ try {
194
+ const {} = req.body;
195
+ const height = await TxIndex.findMaxIndexedBlock()
196
+ res.json(height);
197
+ } catch (error) {
198
+ console.error('Error validating address:', error);
199
+ res.status(500).send('Error: ' + error.message);
200
+ }
201
+ });
202
+
203
+ app.post('/tl_getTrackHeight'), async (req,res) =>{
204
+ try {
205
+ const {} = req.body;
206
+ const height = await Consensus.getTrackHeight()
207
+ res.json(height);
208
+ } catch (error) {
209
+ console.error('Error validating address:', error);
210
+ res.status(500).send('Error: ' + error.message);
211
+ }
212
+ }
213
+
214
+ app.post('/tl_checkSync'), async (req,res) =>{
215
+ try {
216
+ const {} = req.body;
217
+ const res = await Main.checkSync()
218
+ res.json(res);
219
+ } catch (error) {
220
+ console.error('Error validating address:', error);
221
+ res.status(500).send('Error: ' + error.message);
222
+ }
223
+ }
224
+
225
+ app.post('/tl_pause', async (req, res) => {
226
+ try {
227
+ const {} = req.body;
228
+ const pause = Main.setPause()
229
+ res.json(pause);
230
+ } catch (error) {
231
+ console.error('Error validating address:', error);
232
+ res.status(500).send('Error: ' + error.message);
233
+ }
234
+ });
235
+
236
+ // Get all balances for an address
237
+ app.post('/tl_getAllBalancesForAddress', async (req, res) => {
238
+ console.log('Trying to load balances for: ' + req.body.params);
239
+
240
+ try {
241
+ const balances = await TallyMap.getAddressBalances(req.body.params);
242
+ res.status(200).json(balances);
243
+ } catch (error) {
244
+ console.error(error);
245
+ res.status(500).send('Error: ' + error.message);
246
+ }
247
+ });
248
+
249
+ app.post('/tl_getChannel', async (req, res) => {
250
+ console.log('Trying to load channel for: ' + req.body.params);
251
+
252
+ try {
253
+ // Fetch the channel information
254
+ const channel = await Channels.getChannel(req.body.params);
255
+
256
+ // Handle the case where the channel is undefined or null (no channel exists)
257
+ if (!channel) {
258
+ return res.status(200).json({ message: 'No channel found for the given address', channel: null });
259
+ }
260
+
261
+ // If the channel exists, return it as a successful response
262
+ return res.status(200).json(channel);
263
+ } catch (error) {
264
+ // Handle other unexpected errors and return a 500 status for genuine server-side issues
265
+ console.error('Error loading channel:', error);
266
+ return res.status(500).send('Error: ' + error.message);
267
+ }
268
+ });
269
+
270
+ // Add OP_Return to tx blob
271
+ app.post('/tl_createrawtx_opreturn', async (req, res) => {
272
+ try {
273
+ const [txHex, payload] = req.body.params;
274
+ const payloadedTx = await TxUtils.addOPReturn(txHex, payload);
275
+ const result = { data: payloadedTx.toString('hex') };
276
+ res.status(200).send(result);
277
+ } catch (error) {
278
+ console.error(error);
279
+ res.status(500).send('Error: ' + error.message);
280
+ }
281
+ });
282
+
283
+ app.post('/tl_getProperty', async (req, res) => {
284
+ try {
285
+ const pid = req.body.params;
286
+ console.log('tl_getproperty: ' + pid);
287
+ const data = await PropertyManager.getPropertyData(pid);
288
+ res.json(data);
289
+ } catch (error) {
290
+ console.error('Error fetching property data:', error);
291
+ res.status(500).send('Error: ' + error.message);
292
+ }
293
+ });
294
+
295
+ // List properties
296
+ app.post('/tl_listProperties', async (req, res) => {
297
+ try {
298
+ console.log('Express calling property list');
299
+ const propertiesArray = await PropertyManager.getPropertyIndex();
300
+ res.json(propertiesArray);
301
+ } catch (error) {
302
+ console.error('Error fetching property list:', error);
303
+ res.status(500).send('Error: ' + error.message);
304
+ }
305
+ });
306
+
307
+ app.post('/tl_listClearlists', async (req, res) => {
308
+ try {
309
+ console.log('Express calling clearlists');
310
+ const clearLists = await Clearlist.loadClearlists();
311
+ res.json(propertiesArray);
312
+ } catch (error) {
313
+ console.error('Error fetching property list:', error);
314
+ res.status(500).send('Error: ' + error.message);
315
+ }
316
+ });
317
+
318
+ app.post('/tl_showClearlist', async (req, res) => {
319
+ try {
320
+ console.log('Express calling clearlist');
321
+
322
+ // Corrected the destructuring syntax
323
+ const { id } = req.body;
324
+
325
+ const clearLists = await Clearlist.getList(id);
326
+ res.json(clearLists);
327
+ } catch (error) {
328
+ console.error('Error fetching property list:', error);
329
+ res.status(500).send('Error: ' + error.message);
330
+ }
331
+ });
332
+
333
+
334
+ app.post('/tl_listFeeCache', async(req,res)=>{
335
+ try{
336
+ console.log('Pulling fees for all properties');
337
+ const feeCache = await PropertyManager.loadFeeCacheFromDB();
338
+ res.json(feeCache);
339
+ } catch (error) {
340
+ console.error('Error fetching fee cache', error);
341
+ res.status(500).send('Error: ' + error.message);
342
+ }
343
+ })
344
+
345
+ app.post('/tl_propertyFeeCache', async(req,res)=>{
346
+ try{
347
+ console.log('Pulling fees for all properties');
348
+ const feeCache = await PropertyManager.loadFeeCacheForProperty(req.id);
349
+ res.json(feeCache);
350
+ } catch (error) {
351
+ console.error('Error fetching fee cache', error);
352
+ res.status(500).send('Error: ' + error.message);
353
+ }
354
+ })
355
+
356
+ // Get activations
357
+ app.post('/tl_getActivations', async (req, res) => {
358
+ try {
359
+ console.log('Express calling activations');
360
+ const activations = await Activations.getInstance().loadActivationsList();
361
+ res.json(activations);
362
+ } catch (error) {
363
+ console.error('Error fetching activations:', error);
364
+ res.status(500).send('Error: ' + error.message);
365
+ }
366
+ });
367
+
368
+ // Get order book
369
+ app.post('/tl_getOrderbook', async (req, res) => {
370
+ try {
371
+ const { propertyId1, propertyId2 } = req.body;
372
+ const orderBookKey = `${propertyId1}-${propertyId2}`;
373
+ const orderbook = new Orderbook(orderBookKey);
374
+ const orderBookData = await orderbook.loadOrderBook(orderBookKey);
375
+ res.json(orderBookData);
376
+ } catch (error) {
377
+ console.error('Error fetching order book:', error);
378
+ res.status(500).send('Error: ' + error.message);
379
+ }
380
+ });
381
+
382
+ // Get contract order book
383
+ app.post('/tl_getContractOrderbook', async (req, res) => {
384
+ try {
385
+ const { contractId } = req.body;
386
+ const orderBookKey = `contract-${contractId}`;
387
+ const orderbook = new Orderbook(orderBookKey);
388
+ await orderbook.loadOrCreateOrderBook();
389
+ const orderBookData = orderbook.getOrderBookData();
390
+ res.json(orderBookData);
391
+ } catch (error) {
392
+ console.error('Error fetching contract order book:', error);
393
+ res.status(500).send('Error: ' + error.message);
394
+ }
395
+ });
396
+
397
+ // List contract series
398
+ app.post('/tl_listContractSeries', async (req, res) => {
399
+ try {
400
+ console.log('Fetching contract series list');
401
+ const { contractId } = req.body;
402
+ const contractSeriesArray = await ContractRegistry.getContractInfo(contractId);
403
+ console.log('Contract series array ' + JSON.stringify(contractSeriesArray));
404
+ res.json(contractSeriesArray);
405
+ } catch (error) {
406
+ console.error('Error fetching contract series:', error);
407
+ res.status(500).send('Error: ' + error.message);
408
+ }
409
+ });
410
+
411
+ // List oracles
412
+ app.post('/tl_listOracles', async (req, res) => {
413
+ try {
414
+ console.log('Fetching oracle list');
415
+ const oracleArray = await OracleList.getAllOracles();
416
+ res.json(oracleArray);
417
+ } catch (error) {
418
+ console.error('Error fetching oracle list:', error);
419
+ res.status(500).send('Error: ' + error.message);
420
+ }
421
+ });
422
+
423
+ // Get contract position for address and contract ID
424
+ app.get('/tl_contractPosition', async (req, res) => {
425
+ try {
426
+ const { address, contractId } = req.query;
427
+ if (!address || !contractId) {
428
+ return res.status(400).json({ error: "Missing address or contractId" });
429
+ }
430
+ const contractIdNum = Number(contractId);
431
+ if (isNaN(contractIdNum)) {
432
+ return res.status(400).json({ error: "contractId must be a number" });
433
+ }
434
+ const map = await MarginMap.getInstance(contractIdNum)
435
+ const position = await map.getPositionForAddress(address,contractIdNum);
436
+ res.json(position);
437
+ } catch (error) {
438
+ res.status(500).send('Error: ' + error.message);
439
+ }
440
+ });
441
+
442
+ // Get sum of open channel balances for commit address and prop ID
443
+ app.get('/tl_channelBalanceForCommiter', async (req, res) => {
444
+ try {
445
+ const { address, propertyId } = req.query;
446
+ if (!address || !propertyId) {
447
+ return res.status(400).json({ error: "Missing address or contractId" });
448
+ }
449
+ const propIdNum = Number(propertyId);
450
+ if (isNaN(propIdNum)) {
451
+ return res.status(400).json({ error: "contractId must be a number" });
452
+ }
453
+ const rows = await Channels.getChannelBalancesForAddress(address, propertyId)
454
+ const total = rows.reduce((s, r) => s + r.amount, 0);
455
+ res.json({ total, rows });
456
+ } catch (error) {
457
+ res.status(500).send('Error: ' + error.message);
458
+ }
459
+ });
460
+
461
+ function parsePropertyKey(raw) {
462
+ // "s123-2001" => redeem; "123" => mint
463
+ if (typeof raw === 'string' && /^s\d+-\d+$/i.test(raw)) {
464
+ const [, p, c] = raw.match(/^s(\d+)-(\d+)$/i);
465
+ return { mode: 'redeem', basePid: Number(p), contractId: Number(c), synthKey: raw };
466
+ }
467
+ const n = Number(raw);
468
+ if (!Number.isFinite(n)) throw new Error('Invalid propertyId');
469
+ return { mode: 'mint', basePid: n };
470
+ }
471
+
472
+
473
+ function parseValue(doc) {
474
+ // Your samples look like: { _id, block, value: "<JSON string>" }
475
+ const raw = doc?.value ?? doc?.data ?? doc?.map ?? null;
476
+ if (raw == null) return null;
477
+
478
+ if (typeof raw === 'string') {
479
+ try { return JSON.parse(raw); } catch { /* fall-through */ }
480
+ }
481
+ return raw;
482
+ }
483
+
484
+ app.get('/tl_getMaxSynth', async (req, res) => {
485
+ try {
486
+ const { address, propId } = req.query;
487
+ if (!address || !propId) {
488
+ return res.status(400).json({ error: 'address and propertyId are required' });
489
+ }
490
+
491
+ const { mode, basePid, contractId: redeemCid, synthKey } = parsePropertyKey(propId);
492
+
493
+ // list candidate contracts for this base property (inverse + native)
494
+ let candidates = await ContractRegistry.lookupInverseNativeByNotionalPid(basePid);
495
+ if (mode === 'redeem') {
496
+ candidates = candidates.filter(c => Number(c.contractId) === Number(redeemCid));
497
+ }
498
+
499
+ const tokenPriceLTC = await VolumeIndex.getTokenPriceInLTC(basePid).catch(() => null);
500
+
501
+ const eligible = [];
502
+ for (const c of candidates) {
503
+ const map = await MarginMap.getInstance(c.seriesId)
504
+
505
+ // read position for this address in this contract’s series
506
+ const pos = await map.readPosition(c.seriesId, address); // 👈 new helper
507
+
508
+ const contracts = Number(pos?.contracts || 0);
509
+ const shortContracts = contracts < 0 ? -contracts : 0;
510
+
511
+ let mark = Number(pos?.lastMark);
512
+ if (!mark || mark <= 0) {
513
+ mark = tokenPriceLTC || 0;
514
+ }
515
+
516
+ let notionalPerContract = 0;
517
+ if (shortContracts > 0 && mark > 0) {
518
+ const nv = await ContractRegistry.getNotionalValue(c.contractId, mark);
519
+ notionalPerContract = Number(nv?.notionalValue || 0);
520
+ }
521
+
522
+ const maxByPositionUnits = shortContracts * notionalPerContract;
523
+
524
+ eligible.push({
525
+ contractId: c.contractId,
526
+ seriesId: c.seriesId,
527
+ symbol: c.symbol,
528
+ notionalPropertyId: c.notionalPropertyId,
529
+ mark,
530
+ tokenPriceLTC: tokenPriceLTC ?? null,
531
+ shortContracts,
532
+ perContractUnits: notionalPerContract,
533
+ maxMintUnits: maxByPositionUnits,
534
+ });
535
+ }
536
+
537
+ res.json({
538
+ mode,
539
+ basePropertyId: basePid,
540
+ ...(synthKey ? { synthKey } : {}),
541
+ tokenPriceLTC: tokenPriceLTC ?? null,
542
+ eligible
543
+ });
544
+ } catch (err) {
545
+ console.error('tl_getMaxSynth error', err);
546
+ res.status(500).json({ error: String(err && err.message || err) });
547
+ }
548
+ });
549
+
550
+
551
+ // Get trade history
552
+ app.get('/tl_tradeHistory', async (req, res) => {
553
+ try {
554
+ const { propertyId1, propertyId2 } = req.query;
555
+ const tradeHistory = await TradeHistory.getTradeHistoryByPropertyIdPair(propertyId1, propertyId2);
556
+ console.log('Returning trade history ' + JSON.stringify(tradeHistory));
557
+ res.json(tradeHistory);
558
+ } catch (error) {
559
+ res.status(500).send('Error: ' + error.message);
560
+ }
561
+ });
562
+
563
+ app.get('/tl_tokenTradeHistoryForAddress', async (req, res) => {
564
+ try {
565
+ const { propertyId1, propertyId2, address } = req.query;
566
+ const tradeHistory = await TradeHistory.getTokenTradeHistoryForAddress(propertyId1, propertyId2,address);
567
+ console.log('Returning trade history ' + JSON.stringify(tradeHistory));
568
+ res.json(tradeHistory);
569
+ } catch (error) {
570
+ res.status(500).send('Error: ' + error.message);
571
+ }
572
+ });
573
+
574
+ // Get initial margin for wallet UI and associated parameters (like commiting to channel for a contract trade)
575
+ app.get('/tl_getInitMargin', async (req, res) => {
576
+ try {
577
+ const { contractId, price } = req.query;
578
+ const initialMargin = await ContractRegistry.getInitialMargin(contractId, price);
579
+ console.log('Init. Margin for contract at price ' + JSON.stringify(initialMargin));
580
+ res.json(initialMargin);
581
+ } catch (error) {
582
+ res.status(500).send('Error: ' + error.message);
583
+ }
584
+ });
585
+
586
+ app.get('/tl_getContractInfo', async (req, res) => {
587
+ try {
588
+ const { contractId } = req.query;
589
+ const info = await ContractRegistry.getContractInfo(contractId);
590
+ if (!info) {
591
+ return res.status(404).json({ error: 'Contract not found' });
592
+ }
593
+ res.json(info);
594
+ } catch (error) {
595
+ res.status(500).send('Error: ' + error.message);
596
+ }
597
+ });
598
+
599
+
600
+ // Get contract trade history
601
+ app.get('/tl_contractTradeHistory', async (req, res) => {
602
+ try {
603
+ const { contractId } = req.query;
604
+ const contractTradeHistory = await Orderbook.getContractTradeHistoryByContractId(contractId);
605
+ res.json(contractTradeHistory);
606
+ } catch (error) {
607
+ res.status(500).send('Error: ' + error.message);
608
+ }
609
+ });
610
+
611
+ app.get('/tl_contractTradeHistoryForAddress', async (req, res) => {
612
+ try {
613
+ const { contractId, address } = req.query;
614
+ const contractTradeHistory = await TradeHistory.getContractTradeHistoryForAddress(contractId,address);
615
+ res.json(contractTradeHistory);
616
+ } catch (error) {
617
+ res.status(500).send('Error: ' + error.message);
618
+ }
619
+ });
620
+
621
+ app.get('/tl_totalTradeHistoryForAddress', async (req, res) => {
622
+ try {
623
+ const { address } = req.query;
624
+ const totalTradeHistory = await TradeHistory.getTradeHistoryForAddress(address);
625
+ res.json(totalTradeHistory);
626
+ } catch (error) {
627
+ res.status(500).send('Error: ' + error.message);
628
+ }
629
+ });
630
+
631
+ // Get funding history
632
+ app.get('/tl_fundingHistory', async (req, res) => {
633
+ try {
634
+ const { contractId } = req.query;
635
+ if (!contractId) return res.status(400).send("Missing contractId");
636
+
637
+ const startBlock = req.query.startBlock || await Main.getGenesisBlock();
638
+ const endBlock = req.query.endBlock || await Main.getLastBlock();
639
+
640
+ const fundingHistory = await Clearing.loadFundingEvents(contractId, startBlock, endBlock);
641
+ res.json(fundingHistory);
642
+ } catch (error) {
643
+ res.status(500).send('Error: ' + error.message);
644
+ }
645
+ });
646
+
647
+ // Get oracle history
648
+ app.get('/tl_oracleHistory', async (req, res) => {
649
+ try {
650
+ const { contractId } = req.query;
651
+ const oracleHistory = await Oracles.getHistory(contractId);
652
+ res.json(oracleHistory);
653
+ } catch (error) {
654
+ res.status(500).send('Error: ' + error.message);
655
+ }
656
+ });
657
+
658
+ // ... Other endpoints ...
659
+
660
+ app.listen(port, () => {
661
+ // const params = ['a1','c3'];
662
+ // const body = { params };
663
+ // console.log(`body:${JSON.stringify(body)}`)
664
+ console.log(`Express server running on port ${port}`);
665
+ });