@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,82 @@
1
+ const path = require('path');
2
+ const Base256 = require(path.join(__dirname, '../src/base256.js'));
3
+
4
+ // Helpers
5
+ const hexToBuf = h => Buffer.from(h, 'hex');
6
+ const bufToHex = b => Buffer.from(b).toString('hex');
7
+ const pad64 = h => (h.length >= 64 ? h.slice(-64) : '0'.repeat(64 - h.length) + h);
8
+
9
+ function buildScript(tx1HexBE, tx2HexBE) {
10
+ // encode to your base-256 "printable" alphabet (multi-byte UTF-8)
11
+ const s1 = Base256.hexToBase256(tx1HexBE.toLowerCase());
12
+ const s2 = Base256.hexToBase256(tx2HexBE.toLowerCase());
13
+
14
+ const b1 = Buffer.from(s1, 'utf8');
15
+ const b2 = Buffer.from(s2, 'utf8');
16
+
17
+ if (b1.length > 255 || b2.length > 255) {
18
+ throw new Error(`Base256 UTF-8 is too long for 1-byte length fields: b1=${b1.length}, b2=${b2.length}`);
19
+ }
20
+
21
+ // 'tl' + tag(0x42) + len1 + len2 + data1 + data2
22
+ const header = Buffer.from([0x74, 0x6c, 0x42, b1.length, b2.length]);
23
+ const payload = Buffer.concat([header, b1, b2]);
24
+
25
+ // Minimal push wrapper
26
+ const len = payload.length;
27
+ let script;
28
+ if (len <= 75) {
29
+ script = Buffer.concat([Buffer.from([0x6a, len]), payload]);
30
+ } else if (len <= 0xff) {
31
+ script = Buffer.concat([Buffer.from([0x6a, 0x4c, len]), payload]); // PUSHDATA1
32
+ } else if (len <= 0xffff) {
33
+ script = Buffer.concat([Buffer.from([0x6a, 0x4d, len & 0xff, len >> 8]), payload]); // PUSHDATA2
34
+ } else {
35
+ const L = Buffer.allocUnsafe(4); L.writeUInt32LE(len, 0);
36
+ script = Buffer.concat([Buffer.from([0x6a, 0x4e]), L, payload]); // PUSHDATA4
37
+ }
38
+ return bufToHex(script);
39
+ }
40
+
41
+ function parseScript(scriptHex) {
42
+ const buf = hexToBuf(scriptHex);
43
+ if (buf[0] !== 0x6a) throw new Error('Not OP_RETURN');
44
+
45
+ const op = buf[1];
46
+ let len, off;
47
+ if (op <= 75) { len = op; off = 2; }
48
+ else if (op === 0x4c){ len = buf[2]; off = 3; }
49
+ else if (op === 0x4d){ len = buf[2] | (buf[3] << 8); off = 4; }
50
+ else if (op === 0x4e){ len = (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)) >>> 0; off = 6; }
51
+ else throw new Error('Unknown pushdata');
52
+
53
+ const data = buf.slice(off, off + len);
54
+ if (data[0] !== 0x74 || data[1] !== 0x6c) throw new Error('Missing "tl"');
55
+ if (data[2] !== 0x42) throw new Error('Unexpected tag (expected 0x42)');
56
+
57
+ const len1 = data[3], len2 = data[4];
58
+ if (5 + len1 + len2 !== data.length) throw new Error('Length mismatch');
59
+
60
+ const s1 = data.slice(5, 5 + len1).toString('utf8');
61
+ const s2 = data.slice(5 + len1, 5 + len1 + len2).toString('utf8');
62
+
63
+ const h1 = pad64(Base256.base256ToHex(s1).toLowerCase());
64
+ const h2 = pad64(Base256.base256ToHex(s2).toLowerCase());
65
+
66
+ return { txid1: h1, txid2: h2, payloadLen: len, scriptLen: buf.length };
67
+ }
68
+
69
+ // ---- demo ----
70
+ const TX1 = 'e2b11900c8e99d77bc527807c268bd937a991d975d7a6043725f4174e1fcc6a7';
71
+ const TX2 = 'acb58f122e0ffa34e82b3775289ef55218243d3712fb592f1ac70bdec8984e7c';
72
+
73
+ const scriptHex = buildScript(TX1, TX2);
74
+ console.log('ScriptPubKey (hex):', scriptHex); // log hex only (no beeps)
75
+
76
+ const parsed = parseScript(scriptHex);
77
+ console.log('Parsed:', parsed);
78
+
79
+ if (parsed.txid1 !== TX1 || parsed.txid2 !== TX2) {
80
+ throw new Error('Round-trip mismatch');
81
+ }
82
+ console.log('Round-trip OK.');
@@ -0,0 +1,205 @@
1
+ const { execSync } = require('child_process');
2
+ const { DateTime } = require('luxon');
3
+
4
+ // Configuration options for litecoin-cli
5
+ const config = {
6
+ datadir: "",
7
+ rpcuser: "",
8
+ rpcpassword: "",
9
+ rpcookiefile: "",
10
+ rpcconnect: "",
11
+ rpcport: "",
12
+ conf: ""
13
+ };
14
+
15
+ // Add the configuration options to the litecoin-cli call
16
+ const litecoinCliOptions = [];
17
+ if (config.datadir) litecoinCliOptions.push(`-datadir=${config.datadir}`);
18
+ if (config.rpcuser) litecoinCliOptions.push(`-rpcuser=${config.rpcuser}`);
19
+ if (config.rpcpassword) litecoinCliOptions.push(`-rpcpassword=${config.rpcpassword}`);
20
+ if (config.rpcookiefile) litecoinCliOptions.push(`-rpcookiefile=${config.rpcookiefile}`);
21
+ if (config.rpcconnect) litecoinCliOptions.push(`-rpcconnect=${config.rpcconnect}`);
22
+ if (config.rpcport) litecoinCliOptions.push(`-rpcport=${config.rpcport}`);
23
+ if (config.conf) litecoinCliOptions.push(`-conf=${config.conf}`);
24
+
25
+ // Shortcut function to call the node
26
+ function askNode(command) {
27
+ const cmd = ['litecoin-cli', ...litecoinCliOptions, ...command].join(' ');
28
+ try {
29
+ return execSync(cmd).toString().trim();
30
+ } catch (error) {
31
+ console.error("Error connecting to your node. Trouble shooting steps:");
32
+ console.error("1) Make sure litecoin-cli is working. Try command 'litecoin-cli getblockcount'");
33
+ console.error("2) Make sure config file litecoin.conf has server=1");
34
+ console.error("3) Explore the litecoin-cli options in this script");
35
+ console.error("The command was: " + cmd);
36
+ console.error("The error from litecoin-cli was:", error);
37
+ process.exit(1);
38
+ }
39
+ }
40
+
41
+ // Get the latest block from the node
42
+ const blockCount = parseInt(askNode(['getblockcount']));
43
+ const blockHash = askNode(['getblockhash', blockCount]);
44
+ const blockHeader = JSON.parse(askNode(['getblockheader', blockHash, 'true']));
45
+ const latestTimeInSeconds = blockHeader.time;
46
+ const latestDateTime = DateTime.fromSeconds(latestTimeInSeconds, { zone: 'utc' });
47
+ const latestPriceDate = latestDateTime.minus({ days: 1 }).toISODate();
48
+
49
+ console.log(`Connected to local node at block #: ${blockCount}`);
50
+ console.log(`Latest available price date is: ${latestPriceDate}`);
51
+ console.log("Earliest available price date is: 2020-07-26 (full node)");
52
+
53
+ // Get the desired date to estimate the price
54
+ const readline = require('readline').createInterface({
55
+ input: process.stdin,
56
+ output: process.stdout
57
+ });
58
+
59
+ readline.question("Enter date in YYYY-MM-DD (or 'q' to quit): ", dateEntered => {
60
+ if (dateEntered.toLowerCase() === 'q') {
61
+ readline.close();
62
+ process.exit(0);
63
+ }
64
+
65
+ let datetimeEntered;
66
+ try {
67
+ datetimeEntered = DateTime.fromISO(dateEntered, { zone: 'utc' });
68
+ if (!datetimeEntered.isValid || datetimeEntered >= latestDateTime.startOf('day')) {
69
+ throw new Error("Invalid date");
70
+ }
71
+
72
+ const minDate = DateTime.fromISO("2020-07-26", { zone: 'utc' });
73
+ if (datetimeEntered < minDate) {
74
+ throw new Error("Date is before 2020-07-26");
75
+ }
76
+ } catch (error) {
77
+ console.error("Error interpreting date. Likely not entered in format YYYY-MM-DD");
78
+ console.error("Please try again");
79
+ readline.close();
80
+ process.exit(1);
81
+ }
82
+
83
+ const priceDaySeconds = datetimeEntered.toSeconds();
84
+ const priceDayDateUtc = datetimeEntered.toLocaleString(DateTime.DATE_FULL);
85
+ readline.close();
86
+
87
+ // Hunt through blocks to find the first block on the target day
88
+ let secondsSincePriceDay = latestTimeInSeconds - priceDaySeconds;
89
+ let blocksAgoEstimate = Math.round(144 * secondsSincePriceDay / (60 * 60 * 24));
90
+ let priceDayBlockEstimate = blockCount - blocksAgoEstimate;
91
+
92
+ let blockHashB = askNode(['getblockhash', priceDayBlockEstimate]);
93
+ let blockHeaderB = JSON.parse(askNode(['getblockheader', blockHashB, 'true']));
94
+ let timeInSeconds = blockHeaderB.time;
95
+ let secondsDifference = timeInSeconds - priceDaySeconds;
96
+ let blockJumpEstimate = Math.round(144 * secondsDifference / (60 * 60 * 24));
97
+
98
+ let lastEstimate = 0;
99
+ let lastLastEstimate = 0;
100
+ while (blockJumpEstimate > 6 && blockJumpEstimate !== lastLastEstimate) {
101
+ lastLastEstimate = lastEstimate;
102
+ lastEstimate = blockJumpEstimate;
103
+
104
+ priceDayBlockEstimate -= blockJumpEstimate;
105
+ blockHashB = askNode(['getblockhash', priceDayBlockEstimate]);
106
+ blockHeaderB = JSON.parse(askNode(['getblockheader', blockHashB, 'true']));
107
+ timeInSeconds = blockHeaderB.time;
108
+ secondsDifference = timeInSeconds - priceDaySeconds;
109
+ blockJumpEstimate = Math.round(144 * secondsDifference / (60 * 60 * 24));
110
+ }
111
+
112
+ if (timeInSeconds > priceDaySeconds) {
113
+ while (timeInSeconds > priceDaySeconds) {
114
+ priceDayBlockEstimate -= 1;
115
+ blockHashB = askNode(['getblockhash', priceDayBlockEstimate]);
116
+ blockHeaderB = JSON.parse(askNode(['getblockheader', blockHashB, 'true']));
117
+ timeInSeconds = blockHeaderB.time;
118
+ }
119
+ priceDayBlockEstimate += 1;
120
+ } else if (timeInSeconds < priceDaySeconds) {
121
+ while (timeInSeconds < priceDaySeconds) {
122
+ priceDayBlockEstimate += 1;
123
+ blockHashB = askNode(['getblockhash', priceDayBlockEstimate]);
124
+ blockHeaderB = JSON.parse(askNode(['getblockheader', blockHashB, 'true']));
125
+ timeInSeconds = blockHeaderB.time;
126
+ }
127
+ }
128
+
129
+ const priceDayBlock = priceDayBlockEstimate;
130
+
131
+ // Build the container to hold the output amounts bell curve
132
+ const firstBinValue = -6;
133
+ const lastBinValue = 6;
134
+ const rangeBinValues = lastBinValue - firstBinValue;
135
+ const outputBellCurveBins = [0.0];
136
+
137
+ for (let exponent = -6; exponent < 6; exponent++) {
138
+ for (let b = 0; b < 200; b++) {
139
+ const binValue = Math.pow(10, exponent + b / 200);
140
+ outputBellCurveBins.push(binValue);
141
+ }
142
+ }
143
+
144
+ const numberOfBins = outputBellCurveBins.length;
145
+ const outputBellCurveBinCounts = new Array(numberOfBins).fill(0.0);
146
+
147
+ // Get all output amounts from all blocks on target day
148
+ console.log(`\nReading all blocks on ${priceDayDateUtc}...`);
149
+ console.log("\nThis will take a few minutes (~144 blocks)...");
150
+ console.log("\nHeight\tTime(utc)\t\tTime(32bit)\t\t Completion %");
151
+
152
+ let blockHeight = priceDayBlock;
153
+ let blockHashB = askNode(['getblockhash', blockHeight]);
154
+ let blockB = JSON.parse(askNode(['getblock', blockHashB, '2']));
155
+ let timeInSeconds = blockB.time;
156
+ let timeDateTime = DateTime.fromSeconds(timeInSeconds, { zone: 'utc' });
157
+ let timeUtc = timeDateTime.toFormat('HH:mm:ss');
158
+ let dayOfMonth = timeDateTime.day;
159
+ let targetDayOfMonth = dayOfMonth;
160
+ let time32Bit = (timeInSeconds & 0b11111111111111111111111111111111).toString(2).padStart(32, '0');
161
+
162
+ while (targetDayOfMonth === dayOfMonth) {
163
+ const progressEstimate = 100.0 * (timeDateTime.hour + timeDateTime.minute / 60) / 24.0;
164
+ console.log(`${blockHeight}\t${timeUtc}\t${time32Bit}\t${progressEstimate.toFixed(2)}%`);
165
+
166
+ for (const tx of blockB.tx) {
167
+ for (const output of tx.vout) {
168
+ const amount = parseFloat(output.value);
169
+ if (amount > 1e-6 && amount < 1e6) {
170
+ const amountLog = Math.log10(amount);
171
+ const percentInRange = (amountLog - firstBinValue) / rangeBinValues;
172
+ let binNumberEst = Math.floor(percentInRange * numberOfBins);
173
+ while (outputBellCurveBins[binNumberEst] <= amount) {
174
+ binNumberEst += 1;
175
+ }
176
+ const binNumber = binNumberEst - 1;
177
+ outputBellCurveBinCounts[binNumber] += 1.0;
178
+ }
179
+ }
180
+ }
181
+
182
+ blockHeight += 1;
183
+ blockHashB = askNode(['getblockhash', blockHeight]);
184
+ blockB = JSON.parse(askNode(['getblock', blockHashB, '2']));
185
+ timeInSeconds = blockB.time;
186
+ timeDateTime = DateTime.fromSeconds(timeInSeconds, { zone: 'utc' });
187
+ timeUtc = timeDateTime.toFormat('HH:mm:ss');
188
+ dayOfMonth = timeDateTime.day;
189
+ time32Bit = (timeInSeconds & 0b11111111111111111111111111111111).toString(2).padStart(32, '0');
190
+ }
191
+
192
+ console.log("\nNormalizing and displaying histogram...");
193
+
194
+ // Normalize and plot the histogram
195
+ const totalOutputs = outputBellCurveBinCounts.reduce((a, b) => a + b, 0.0);
196
+ for (let b = 0; b < numberOfBins; b++) {
197
+ outputBellCurveBinCounts[b] /= totalOutputs;
198
+ }
199
+
200
+ for (let b = 1; b < numberOfBins; b++) {
201
+ if (outputBellCurveBinCounts[b] > 0.01) {
202
+ console.log(`Bin ${b}: ${outputBellCurveBins[b].toFixed(8)} LTC - ${outputBellCurveBinCounts[b].toFixed(4)}`);
203
+ }
204
+ }
205
+ });
@@ -0,0 +1,23 @@
1
+ const baseConverter = require('bigint-base-converter');
2
+
3
+ // Define the Base 94 character set
4
+ const base94Chars = [...Array(94).keys()].map((i) => String.fromCharCode(i + 33));
5
+
6
+ // Convert a decimal string to base 94
7
+ function toBase94(decimalString) {
8
+ return baseConverter(decimalString, 10, base94Chars.join(''));
9
+ }
10
+
11
+ // Convert hexadecimal (base16) string to base94
12
+ function hexToBase94(hex) {
13
+ // Convert the hexadecimal string to a decimal string
14
+ const decimalString = BigInt(`0x${hex}`).toString(10);
15
+
16
+ // Convert the decimal string to base94
17
+ return toBase94(decimalString);
18
+ }
19
+
20
+ // Example usage:
21
+ const hex = '540016785dec88efdc71ebbf13d9c8c690100c9f776c6e275cb1e2a19c27b983';
22
+ const base94Encoded = hexToBase94(hex);
23
+ console.log(`Base 94 Encoded: ${base94Encoded}`);
@@ -0,0 +1,62 @@
1
+ const TxUtils = require('./txUtils.js');
2
+
3
+ async function cancelOrders() {
4
+ // Admin address
5
+ const adminAddress = 'tltc1qfffvwpftp8w3kv6gg6273ejtsfnu2dara5x4tr'//tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8';
6
+
7
+ // Mode 1: Cancel all contract orders
8
+ const cancelParamsMode1 = {
9
+ fromAddress: adminAddress,
10
+ isContract: 0,
11
+ offeredPropertyId: 5, // Replace with the correct property ID
12
+ desiredPropertyId: 4, // Replace with the correct property ID
13
+ cancelAll: true,
14
+ };
15
+
16
+ //await TxUtils.createCancelTransaction(adminAddress, cancelParamsMode1, 6);
17
+
18
+ // Mode 2: Cancel a specific contract order by txid
19
+ const cancelParamsMode2 = {
20
+ fromAddress: adminAddress,
21
+ isContract: 1,
22
+ contractId: 1, // Replace with the correct property ID
23
+ cancelAll: 0,
24
+ cancelParams: {
25
+ txid: '8b146ed06d51a7856e3f27ba1d0d80229b34885cbc63784a2c1051de1ccdc37b', // Replace with the actual txid
26
+ },
27
+ };
28
+
29
+ //await TxUtils.createCancelTransaction(adminAddress, cancelParamsMode2, 6);
30
+
31
+ // Mode 3: Cancel contract buy orders above 0.5
32
+ const cancelParamsMode3Buy = {
33
+ fromAddress: adminAddress,
34
+ isContract: 0,
35
+ offeredPropertyId: 3, // Replace with the correct property ID
36
+ desiredPropertyId: 4, // Replace with the correct property ID
37
+ cancelAll: 0,
38
+ cancelParams: {
39
+ price: 0.5,
40
+ side: 1,
41
+ },
42
+ };
43
+
44
+ //await TxUtils.createCancelTransaction(adminAddress, cancelParamsMode3Buy, 6);
45
+
46
+ // Mode 4: Cancel contract sell orders below 0.48
47
+ const cancelParamsMode4Sell = {
48
+ fromAddress: adminAddress,
49
+ isContract: 1,
50
+ contractId: 1, // Replace with the correct property ID
51
+ cancelAll: 1/*,
52
+ cancelParams: {
53
+ price: 42500, // Replace with the actual price
54
+ side: 0,
55
+ },*/
56
+ };
57
+
58
+ await TxUtils.createCancelTransaction(adminAddress, cancelParamsMode1, 6);
59
+ }
60
+
61
+ // Call the asynchronous function
62
+ cancelOrders();
@@ -0,0 +1,48 @@
1
+ const adminAddress = "tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8";
2
+
3
+ async function delay(ms) {
4
+ return new Promise(resolve => setTimeout(resolve, ms));
5
+ }
6
+
7
+ const expressInterface = require('../src/walletInterface.js');
8
+
9
+ async function runTest() {
10
+ await expressInterface.initMain();
11
+ await delay(1000)
12
+
13
+ /*const address = 'tltc1q7r6x4v67n8vnaftnz8pk33yvf9t9gpynuwdfgk';
14
+ const contractId = 1; // example contract ID
15
+
16
+ const balance2 = await expressInterface.getAllBalancesForAddress('tltc1q7r6x4v67n8vnaftnz8pk33yvf9t9gpynuwdfgk');
17
+ console.log(`Balance for tltc1q7r6x4v67n8vnaftnz8pk33yvf9t9gpynuwdfgk:`, balance2);
18
+
19
+ const balance3 = await expressInterface.getAllBalancesForAddress('tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8');
20
+ console.log(`Balance for tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8:`, balance3);
21
+
22
+ // New calls
23
+ const contractSeries = await expressInterface.listContractSeries();
24
+ console.log('Contract Series:', contractSeries);
25
+
26
+ const oracles = await expressInterface.listOracles();
27
+ console.log('Oracles:', oracles);
28
+
29
+ // Get contract position for the address
30
+ const contractPosition = await expressInterface.getContractPositionForAddressAndContractId(address, contractId);
31
+ console.log(`Contract Position for Address ${address} and Contract ID ${contractId}:`, contractPosition);
32
+
33
+ // Get trade history for the contract
34
+ const contractTradeHistory = await expressInterface.getContractTradeHistory(contractId);
35
+ console.log(`Trade History for Contract ID ${contractId}:`, contractTradeHistory);
36
+
37
+ // Load order books
38
+ const orderBook1 = await expressInterface.getContractOrderBook(1);
39
+ console.log('Order Book for Contract ID 1:', orderBook1);
40
+
41
+ const trades = await expressInterface.getContractTradeHistory(1)
42
+ console.log('trade history '+trades)
43
+ */
44
+
45
+
46
+ }
47
+
48
+ runTest();
@@ -0,0 +1,65 @@
1
+ const BigNumber = require('bignumber.js');
2
+
3
+ // Function to encode using BigNumber and base-36
4
+ function encodeTradeTokenForUTXO(params) {
5
+ console.log('--- Encoding ---');
6
+ console.log('Input Amount:', params.amountOffered);
7
+
8
+ // Use BigNumber for precision and convert to base-36
9
+ const amount = new BigNumber(params.amountOffered).toString(36);
10
+ console.log('Amount in base-36:', amount);
11
+
12
+ const payload = [
13
+ params.propertyId.toString(36),
14
+ amount,
15
+ params.columnA ? '1' : '0',
16
+ params.satsExpected.toString(36),
17
+ params.tokenOutput.toString(36),
18
+ params.payToAddress.toString(36)
19
+ ];
20
+
21
+ console.log('Encoded Payload:', payload.join(','));
22
+ return payload.join(',');
23
+ }
24
+
25
+ // Function to decode back to original value
26
+ function decodeTradeTokenForUTXO(payload) {
27
+ console.log('--- Decoding ---');
28
+ console.log('Payload:', payload);
29
+
30
+ const parts = payload.split(',');
31
+
32
+ // Decode the amount using BigNumber and base-36
33
+ const amount = new BigNumber(parts[1], 36).toNumber();
34
+ console.log('Decoded Amount:', amount);
35
+
36
+ return {
37
+ propertyId: parseInt(parts[0], 36),
38
+ amount: amount, // This should now return the correct value
39
+ columnA: parts[2] === '1',
40
+ satsExpected: parseInt(parts[3], 36),
41
+ tokenOutput: parseInt(parts[4], 36),
42
+ payToAddress: parseInt(parts[5], 36)
43
+ };
44
+ }
45
+
46
+ // Test with the 0.1 that is causing issues in the larger codebase
47
+ const testInput = {
48
+ propertyId: 1,
49
+ amountOffered: 0.1,
50
+ columnA: true,
51
+ satsExpected: 1000,
52
+ tokenOutput: 2,
53
+ payToAddress: 3
54
+ };
55
+
56
+ // Encode the test input
57
+ console.log('Encoding test input...');
58
+ const encoded = encodeTradeTokenForUTXO(testInput);
59
+
60
+ // Decode it back to see if we get the original values
61
+ console.log('Decoding test input...');
62
+ const decoded = decodeTradeTokenForUTXO(encoded);
63
+
64
+ console.log('--- Final Decoded Object ---');
65
+ console.log(decoded);
@@ -0,0 +1,100 @@
1
+ const Litecoin = require('litecoin'); // Import the litecoin npm package
2
+ const util = require('util')
3
+
4
+ // Litecoin client configuration
5
+ const client = new Litecoin.Client({
6
+ host: 'localhost', // Replace with your Litecoin node's host if different
7
+ port: 18332, // The port to connect to (RPC port for Litecoin)
8
+ user: 'user', // Replace with your Litecoin RPC username
9
+ pass: 'pass', // Replace with your Litecoin RPC password
10
+ timeout: 30000 // Optional: adjust as needed
11
+ });
12
+
13
+ const block = 3496378
14
+
15
+ function getBlockHash(height) {
16
+ return util.promisify(client.cmd.bind(client, 'getblockhash'))(height);
17
+ }
18
+
19
+ function getrawtransaction(...params) {
20
+ return util.promisify(client.cmd.bind(client, 'getrawtransaction'))(...params);
21
+ }
22
+ // Replace with actual method to get raw transaction from txid
23
+ async function fetchTransactionData(txId, verbose, block) {
24
+ console.log(block)
25
+ const blockHash = await getBlockHash(block)
26
+
27
+ const transaction = await getrawtransaction(txId, verbose, blockHash );
28
+ const decodedTx = await DecodeRawTransaction(transaction,true)
29
+ }
30
+
31
+
32
+ async function DecodeRawTransaction(thisTx,flag) {
33
+ try {
34
+ //const decodedTx = await this.client.decoderawtransaction(rawTx);
35
+
36
+
37
+ const opReturnOutput = thisTx.vout.find(output => output.scriptPubKey.type === 'nulldata');
38
+
39
+ console.log(thisTx.vout)
40
+
41
+
42
+ if (opReturnOutput) {
43
+ console.log('op return ' +opReturnOutput)
44
+ const opReturnData = opReturnOutput.scriptPubKey.hex;
45
+ if(flag){console.log('OP_RETURN Data:', opReturnData)};
46
+ // Extract and log the "tl" marker
47
+
48
+ // Check if the hex contains the marker "746c" (which corresponds to "tl")
49
+ let markerHex = "746c"; // Hex for "tl"
50
+ let payloadStart =8
51
+ let markerPosition = opReturnData.indexOf(markerHex); // Check if the marker is anywhere in the string
52
+ if(flag){console.log('marker position '+markerPosition)}
53
+ if (markerPosition === -1||markerPosition>6) {
54
+ //console.error('Marker "tl" not found in OP_RETURN data');
55
+ return null;
56
+ }else if(markerHex = opReturnData.substring(4, 8)){
57
+ payloadStart= 8
58
+ }else if(markerHex==opReturnData.substring(5, 9)){
59
+ payloadStart= 9
60
+ }else if(markerHex==opReturnData.substring(6,10)){
61
+ payloadStart=10
62
+ }; // '746c' for 'tl'
63
+ let marker = Buffer.from(markerHex, 'hex').toString();
64
+ if(flag){console.log('checking marker '+marker+ ' payload start '+payloadStart)}
65
+ // Extract and log the actual payload
66
+ const payloadHex = opReturnData.substring(payloadStart);
67
+ const payload = Buffer.from(payloadHex, 'hex').toString();
68
+ console.log('market data ' +markerHex+' '+marker+' '+payload)
69
+ if(marker=='tl'){console.log('Pre-decoded and Decoded Payload:', opReturnData + ' ' + payload+ ' decoding the whole thing '+Buffer.from(opReturnData, 'hex').toString())};
70
+ return { marker, payload , decodedTx};
71
+ } else {
72
+ //console.log('No OP_RETURN output found.');
73
+ return null;
74
+ }
75
+ // Process decoded transaction logic here...
76
+ return decodedTx;
77
+ } catch (error) {
78
+ //console.error('Error decoding raw transaction:', error);
79
+ }
80
+ }
81
+
82
+
83
+ // Main function to test the txId
84
+ async function testTxId(txId) {
85
+ // Fetch the raw transaction data
86
+ const rawTxHex = await fetchTransactionData(txId, true, block);
87
+
88
+ if (!rawTxHex) {
89
+ console.log('No raw transaction data found for txId:', txId);
90
+ return;
91
+ }
92
+
93
+ // Decode the raw transaction and check for the OP_RETURN marker
94
+ console.log(`Testing txId: ${txId}`);
95
+ await decodeTransaction(rawTxHex);
96
+ }
97
+
98
+ // Test the transaction by its txId
99
+ const txId = 'bc395db7a7a11b42e9711e192a860da2fffe64955cae6dd673e267532f328b3d'; // Replace with your txId
100
+ testTxId(txId);
@@ -0,0 +1,47 @@
1
+ const dbInstance = require('./db');
2
+
3
+ // Load tallyMapDelta database
4
+ const tallyMapDeltaDB = dbInstance.getDatabase('tallyMapDelta');
5
+
6
+ // Function to tally amounts and calculate balance for each type
7
+ async function calculateBalanceForAddress(address) {
8
+ try {
9
+ // Find all delta records for the given address
10
+ const deltaRecords = await tallyMapDeltaDB.findAsync({ 'data.address': address });
11
+
12
+ // Create a map to store counts for each type
13
+ const typeCounts = {};
14
+
15
+ // Iterate through delta records and tally counts for each type
16
+ deltaRecords.forEach(delta => {
17
+ const { type } = delta.data;
18
+
19
+ // Update type count
20
+ typeCounts[type] = (typeCounts[type] || 0) + 1;
21
+ });
22
+
23
+ // Sort type counts by type
24
+ const sortedTypeCounts = Object.entries(typeCounts).sort((a, b) => {
25
+ const typeA = a[0].toUpperCase(); // ignore case
26
+ const typeB = b[0].toUpperCase();
27
+ return typeA.localeCompare(typeB);
28
+ });
29
+
30
+ // Display sorted type counts
31
+ console.log(`Type counts for address ${address}:`);
32
+ sortedTypeCounts.forEach(([type, count]) => {
33
+ console.log(`${type}: ${count}`);
34
+ });
35
+
36
+ return sortedTypeCounts;
37
+ } catch (error) {
38
+ console.error('Error calculating balance:', error);
39
+ throw error;
40
+ }
41
+ }
42
+
43
+ // Example: Replace 'your_address_here' with the actual address you want to calculate the balance for
44
+ const addressToCalculate = 'tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8';
45
+
46
+ // Call the function to calculate and display the type counts
47
+ calculateBalanceForAddress(addressToCalculate);