@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,136 @@
1
+ const litecoin = require('litecoin');
2
+ const util = require('util');
3
+ const litecore = require('bitcore-lib-ltc');
4
+ const encoder = require('../src/txEncoder.js'); // Assuming encoder handles OP_RETURN payloads
5
+ const BigNumber = require('bignumber.js')
6
+ const clientConfig = {
7
+ host: '127.0.0.1',
8
+ port: 18332,
9
+ user: 'user',
10
+ pass: 'pass',
11
+ timeout: 10000
12
+ };
13
+
14
+ const client = new litecoin.Client(clientConfig);
15
+
16
+ const listUnspentAsync = util.promisify(client.cmd.bind(client, 'listunspent'));
17
+ const dumpPrivKeyAsync = util.promisify(client.cmd.bind(client, 'dumpprivkey'));
18
+ const sendrawtransactionAsync = util.promisify(client.cmd.bind(client, 'sendrawtransaction'));
19
+
20
+ // Standard fee for Litecoin transactions
21
+ const STANDARD_FEE = 2700; // in satoshis (0.00001 LTC)
22
+
23
+ async function createAndSendContractTrade(senderAddress, tradeParams, blockHeight) {
24
+ try {
25
+ console.log(`Fetching UTXOs for ${senderAddress}...`);
26
+ const utxos = await listUnspentAsync(1, 9999999, [senderAddress]);
27
+ console.log(JSON.stringify(utxos))
28
+ if (!utxos || utxos.length === 0) {
29
+ throw new Error(`No UTXOs found for address: ${senderAddress}`);
30
+ }
31
+
32
+ // Generate OP_RETURN payload for contract trade
33
+ const tradePayload = encoder.encodeTradeContractOnchain(tradeParams);
34
+ if (!tradePayload) {
35
+ throw new Error("Failed to encode trade payload");
36
+ }
37
+
38
+ console.log("Encoded trade payload:", tradePayload.toString('hex'));
39
+
40
+ // Select a UTXO to spend
41
+ const selectedUtxo = utxos[0];
42
+
43
+ // Get the sender's private key from the wallet
44
+ console.log(`Fetching private key for ${senderAddress}...`);
45
+ const privateKeyWIF = await dumpPrivKeyAsync(senderAddress);
46
+ const privateKey = new litecore.PrivateKey(privateKeyWIF);
47
+ const senderPublicKey = privateKey.toPublicKey();
48
+
49
+ console.log('checking values for trade tx '+selectedUtxo+' '+new BigNumber(selectedUtxo.amount).times(1e8).toNumber())
50
+ // Construct the transaction
51
+ const tx = new litecore.Transaction()
52
+ .from(selectedUtxo) // Use the first available UTXO
53
+ .addOutput(new litecore.Transaction.Output({
54
+ script: litecore.Script.buildDataOut(tradePayload), // Attach OP_RETURN
55
+ satoshis: 0 // No value in OP_RETURN output
56
+ }))
57
+ .to(senderAddress, new BigNumber(selectedUtxo.amount).times(1e8).toNumber() - STANDARD_FEE) // Send change back
58
+ .fee(STANDARD_FEE)
59
+ .sign(privateKey);
60
+
61
+ // Serialize and broadcast the transaction
62
+ const serializedTx = tx.serialize();
63
+ console.log("Signed TX:", serializedTx);
64
+
65
+ const txid = await sendrawtransactionAsync(serializedTx);
66
+ console.log(`Transaction sent! TXID: ${txid}`);
67
+ return txid;
68
+
69
+ } catch (error) {
70
+ console.error("Error creating and sending contract trade:", error);
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ // Suppose these are two test addresses with enough LTC & collateral
76
+ const aliceAddress = 'tltc1qfffvwpftp8w3kv6gg6273ejtsfnu2dara5x4tr'//tltc1qtee90ysf57393hfqyn79syj9mkekm7hq0epqzw';
77
+ const bobAddress = 'tltc1qn3src8lgu50gxhndn5hnd6zrc9yv2364wu858m'//tltc1qxcyu5682whfzpjunwu6ek39dvc8lqmjtvxmscc';
78
+ const carolAddress = 'tltc1qqgru3cahyq5tj7l5q066ssv33gg3v7z9auxkcg'
79
+
80
+ contractId =3
81
+ // We'll create & broadcast a series of trades.
82
+ // Make sure you have wallet handling in your code or direct signing.
83
+
84
+ async function structuredTestTrades() {
85
+ // ============ 1) Alice places a BUY at price 5000, amount=5 ============
86
+ const aliceBuy = {
87
+ contractId: contractId,
88
+ amount: 475,
89
+ price: 142.5,
90
+ sell: false
91
+ };
92
+ // blockTime param is handled in your code, so you just pass in e.g. block=100
93
+ await createAndSendContractTrade(bobAddress,/*aliceAddress,*/ aliceBuy, 100);
94
+
95
+ // ============ 2) Bob places a SELL at price 5000, amount=5 ============
96
+ const bobSell = {
97
+ contractId: contractId,
98
+ amount: 850,
99
+ price: 142.7,
100
+ sell: false
101
+ };
102
+
103
+ //await createAndSendContractTrade(aliceAddress, aliceBuy, 100);
104
+
105
+ // We'll assume these both appear in block #100 or so.
106
+ // In your real setup, you might need to manually confirm the block is mined
107
+ // or wait a small time for `Main.processBlock(100)` to run.
108
+
109
+ // ============ 3) Bob partially closes 2 contracts in block #101 ============
110
+ // Now price might have changed to 5100. We'll do a buy order from Bob
111
+ // so he's effectively reducing his short from 5 to 3.
112
+ const bobClose = {
113
+ contractId: contractId,
114
+ amount: 5,
115
+ price: 104.5,
116
+ sell: true // buy to close
117
+ };
118
+ //await createAndSendContractTrade(bobAddress, bobClose, 101);
119
+
120
+ const aliceClose = {
121
+ contractId: contractId,
122
+ amount: 50,
123
+ price: 128,
124
+ sell: false // buy
125
+ };
126
+
127
+ //await createAndSendContractTrade(aliceAddress, aliceClose, 101);
128
+
129
+
130
+ // Done
131
+ console.log('Structured trades broadcast complete.');
132
+ }
133
+
134
+ structuredTestTrades().catch(err => {
135
+ console.error('Error in structured test trades:', err);
136
+ });
@@ -0,0 +1,90 @@
1
+ const bitcoin = require('bitcoinjs-lib');
2
+ const { ECPairFactory } = require('ecpair');
3
+ const ecc = require('tiny-secp256k1');
4
+
5
+ // Create the ECPair factory
6
+ const ECPair = ECPairFactory(ecc);
7
+
8
+ // The Dogecoin network parameters
9
+ const dogecoinNetwork = {
10
+ messagePrefix: '\x19Dogecoin Signed Message:\n',
11
+ bech32: null,
12
+ bip32: {
13
+ public: 0x02facafd,
14
+ private: 0x02fac398,
15
+ },
16
+ pubKeyHash: 0x1e, // 'D' prefix
17
+ scriptHash: 0x16, // '9' prefix
18
+ wif: 0x9e,
19
+ };
20
+
21
+ /**
22
+ * Verify a P2PKH signature in a raw Dogecoin transaction input.
23
+ *
24
+ * @param {string} rawTxHex - Raw transaction hex.
25
+ * @param {number} inputIndex - Index of the input to verify.
26
+ * @param {string} scriptPubKeyHex - The scriptPubKey in hex from the UTXO.
27
+ */
28
+ function verifySignature(rawTxHex, inputIndex, scriptPubKeyHex) {
29
+ try {
30
+ // 1) Parse the raw transaction
31
+ const tx = bitcoin.Transaction.fromHex(rawTxHex);
32
+
33
+ // 2) Get the input
34
+ const input = tx.ins[inputIndex];
35
+ if (!input) throw new Error(`Input index ${inputIndex} does not exist in the transaction.`);
36
+
37
+ // 3) Decompile the scriptSig -> [signature, publicKey]
38
+ const scriptSig = bitcoin.script.decompile(input.script);
39
+ if (!scriptSig || scriptSig.length !== 2) {
40
+ throw new Error('Invalid scriptSig format (expected [signature, publicKey]).');
41
+ }
42
+ const [rawSigWithSighash, publicKey] = scriptSig;
43
+
44
+ // 4) Decode the signature to extract the DER-encoded bytes & the sighash type
45
+ const { signature, hashType } = bitcoin.script.signature.decode(rawSigWithSighash);
46
+ // signature is the DER-encoded signature without the sighash byte
47
+ // hashType is the sighash type (0x01 = SIGHASH_ALL, etc.)
48
+
49
+ // 5) scriptPubKey & embedded pubKeyHash
50
+ const spkBuf = Buffer.from(scriptPubKeyHex, 'hex');
51
+ const decompiledSPK = bitcoin.script.decompile(spkBuf);
52
+ const embeddedHash = decompiledSPK[2]; // pubKeyHash (20 bytes)
53
+
54
+ // 6) Compute pubKeyHash from the publicKey
55
+ const computedPubKeyHash = bitcoin.crypto.hash160(publicKey);
56
+
57
+ console.log('Computed Public Key Hash (Hex):', computedPubKeyHash.toString('hex'));
58
+ console.log('Embedded Hash in scriptPubKey (Hex):', embeddedHash.toString('hex'));
59
+
60
+ if (!computedPubKeyHash.equals(embeddedHash)) {
61
+ throw new Error('Public key hash does not match the scriptPubKey.');
62
+ }
63
+ console.log('Public key hash matches the scriptPubKey!');
64
+
65
+ // 7) Recreate the transaction hash for the sighash type
66
+ const txHash = tx.hashForSignature(inputIndex, spkBuf, hashType);
67
+
68
+ // 8) Verify the signature
69
+ const keyPair = ECPair.fromPublicKey(publicKey, { network: dogecoinNetwork });
70
+ const isValid = keyPair.verify(txHash, signature);
71
+
72
+ if (isValid) {
73
+ console.log('Signature verification succeeded!');
74
+ } else {
75
+ console.log('Signature verification failed.');
76
+ }
77
+
78
+ } catch (err) {
79
+ console.error('Error verifying signature:', err.message);
80
+ }
81
+ }
82
+
83
+ // Example usage:
84
+ const rawTxHex =
85
+ '01000000013ef1cce4f7e8addcf5f5896e89da2aac7661d471c944e78f80a47c8938078205000000006a4730440220302e2844546d714b6d4b5e5cf8ede384ff9bd110ddd102158d86fa104f920d5302204ffda812249fc8b7b885312c7302dd3d57eeb8b70e029dc0b7aa3a1147ddc85b01210233c70a81caf97dd605a5ac92791b65f467001adf36e201b6d9442b1e76be10ccffffffff020027b929000000001976a914a7dcce4bf35b50dbe9da38e5dc6758b7ab78ae5a88ac0000000000000000416a3f746c30303b313b323b333b342c316d76616a35386c69696135316d653975753963673276796e746c7534376734347766316537717175387a39736a3464386600000000';
86
+
87
+ const inputIndex = 0;
88
+ const scriptPubKeyHex = '76a914a7dcce4bf35b50dbe9da38e5dc6758b7ab78ae5a88ac';
89
+
90
+ verifySignature(rawTxHex, inputIndex, scriptPubKeyHex);
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+
3
+ const crypto = require('crypto');
4
+
5
+ // 1) Replace these with your actual hex values:
6
+ const scriptPubKeyHex = '00204a64b51ca4b44f11f87da5ff33142660b39a0e3bcce6b658ebbdadb7f3660fd6';
7
+ const witnessScriptHex = '52210292eece65f01fcd2e035cfd8e5e13b06f4db32dd22e7b6bc1947eb8769f0d0149210274e3b737c001205e209e6f3f290dfe3ef8e2df9f08a928eb4b742b8a6473af4c52ae';
8
+
9
+ // 2) Convert hex strings to Buffers
10
+ const scriptPubKeyBuf = Buffer.from(scriptPubKeyHex, 'hex');
11
+ const witnessScriptBuf = Buffer.from(witnessScriptHex, 'hex');
12
+
13
+ // 3) P2WSH scriptPubKey must be: OP_0 (0x00), PUSH_32 (0x20), then 32-byte hash
14
+ // So the first byte is 0x00, second byte is 0x20, next 32 bytes is the script hash.
15
+ if (scriptPubKeyBuf.length !== 34 || scriptPubKeyBuf[0] !== 0x00 || scriptPubKeyBuf[1] !== 0x20) {
16
+ console.error('scriptPubKey does not look like a native P2WSH (expected 00 20 <32-bytes>)');
17
+ process.exit(1);
18
+ }
19
+
20
+ // Extract the 32-byte (sha256) hash part
21
+ const expectedHash = scriptPubKeyBuf.slice(2); // from byte index 2 to the end
22
+
23
+ // 4) Compute sha256 of your witnessScript
24
+ const actualHash = crypto.createHash('sha256').update(witnessScriptBuf).digest();
25
+
26
+ // 5) Compare them
27
+ const matches = expectedHash.equals(actualHash);
28
+
29
+ console.log('----------------------------------------');
30
+ console.log(' scriptPubKey:', scriptPubKeyHex);
31
+ console.log(' witnessScript:', witnessScriptHex);
32
+ console.log(' expectedHash (from scriptPubKey):', expectedHash.toString('hex'));
33
+ console.log(' actualHash (sha256 of witnessScript):', actualHash.toString('hex'));
34
+ console.log(' Do they match?', matches);
35
+ console.log('----------------------------------------');
36
+
37
+ if (!matches) {
38
+ console.error('❌ The witnessScript does NOT match the scriptPubKey’s 32-byte hash.');
39
+ } else {
40
+ console.log('✅ The witnessScript matches the scriptPubKey hash (P2WSH is correct).');
41
+ }
@@ -0,0 +1,172 @@
1
+ // Import necessary modules and interfaces
2
+ const Litecoin = require('litecoin');
3
+ const config = {host: '127.0.0.1',
4
+ port: 8332,
5
+ user: 'user',
6
+ pass: 'pass',
7
+ timeout: 10000}
8
+ const rpcClient = new Litecoin(config) // Replace with your actual wallet interface module
9
+ const { isMyAddressAllWallets, getTallyForAddress } = require('./interface.js'); // Helper functions, to be implemented
10
+ const tallyMap = require('tally3.js')
11
+ class WalletCache {
12
+ constructor() {
13
+ this.walletBalancesCache = new Map(); // A map to store wallet balances
14
+ }
15
+
16
+ /**
17
+ * Updates the cache with the latest state and returns the number of changes made to wallet addresses.
18
+ */
19
+
20
+ async updateWalletCache(label) {
21
+ let numChanges = 0;
22
+ const addresses = await rpcClient.getAddressesByLabel(label);
23
+
24
+ for (const address of addresses) {
25
+ const balance = await TallyMap.getAddressBalances(address);
26
+
27
+ if (!this.walletBalancesCache.has(address) || this.isBalanceDifferent(this.walletBalancesCache.get(address), balance)) {
28
+ numChanges++;
29
+ this.walletBalancesCache.set(address, balance);
30
+ }
31
+ }
32
+
33
+ return numChanges;
34
+ }
35
+
36
+
37
+ async getAllWalletBalances(label) {
38
+ try {
39
+ // Get all TradeLayer addresses with the specified label from the wallet
40
+ const addresses = await rpcClient.getAddressesByLabel(label);
41
+ const allBalances = [];
42
+
43
+ // For each TradeLayer address, get all balances
44
+ for (const address of addresses) {
45
+ const balances = await TallyMap.getAddressBalances(address);
46
+ allBalances.push({ address, balances });
47
+ }
48
+
49
+ return allBalances;
50
+ } catch (error) {
51
+ console.error('Error getting all wallet balances for TradeLayer addresses:', error);
52
+ throw error;
53
+ }
54
+ }
55
+
56
+
57
+ // Gets the balance for a specific address from the cache
58
+ getBalance(address) {
59
+ return this.walletBalancesCache.get(address) || 0;
60
+ }
61
+
62
+ // Gets a map of all addresses with their respective balances
63
+ getAllBalances() {
64
+ return this.walletBalancesCache;
65
+ }
66
+
67
+ /**
68
+ * Compares two sets of balance data to determine if they are different.
69
+ */
70
+ isBalanceDifferent(balanceData1, balanceData2) {
71
+ // Implement comparison logic based on your balance data structure
72
+ // Example:
73
+ return JSON.stringify(balanceData1) !== JSON.stringify(balanceData2);
74
+ }
75
+
76
+
77
+ /**
78
+ * Retrieves contract positions for all addresses in the wallet.
79
+ */
80
+ async getPositions() {
81
+ try {
82
+ // Get all TradeLayer addresses with the specified label from the wallet
83
+ const label = 'TL'; // Replace with your actual label used for TradeLayer addresses
84
+ const addresses = await rpcClient.getAddressesByLabel(label);
85
+ const allPositions = [];
86
+
87
+ // For each TradeLayer address, get contract positions
88
+ for (const address of addresses) {
89
+ const contractPositions = await this.getContractPositionsForAddress(address);
90
+ if (contractPositions.length > 0) {
91
+ allPositions.push({ address, contractPositions });
92
+ }
93
+ }
94
+
95
+ return allPositions;
96
+ } catch (error) {
97
+ console.error('Error getting contract positions for TradeLayer addresses:', error);
98
+ throw error;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Retrieves contract positions for a specific address from MarginMaps.
104
+ */
105
+ async getContractPositionsForAddress(address) {
106
+ const MarginMap = require('./MarginMap'); // Replace with your MarginMap module
107
+ const ContractsRegistry = require('./ContractsRegistry'); // Replace with your ContractsRegistry module
108
+ const positions = [];
109
+
110
+ // Fetch margin map for the address
111
+ const marginMap = await MarginMap.getMarginMapForAddress(address);
112
+
113
+ // Check for valid margin map
114
+ if (!marginMap) {
115
+ console.log(`No margin map found for address: ${address}`);
116
+ return positions;
117
+ }
118
+
119
+ // Iterate over contracts in the margin map
120
+ for (const [contractId, positionData] of Object.entries(marginMap.contracts)) {
121
+ const contractInfo = await ContractsRegistry.getContractInfo(contractId);
122
+ if (contractInfo) {
123
+ positions.push({
124
+ contractId: contractId,
125
+ positionSize: positionData.size,
126
+ avgEntryPrice: positionData.avgEntryPrice,
127
+ // Include other relevant contract position details
128
+ });
129
+ }
130
+ }
131
+
132
+ return positions;
133
+ }
134
+
135
+ async getContractPositionForAddressAndContractId(address, contractId) {
136
+ const MarginMap = require('./MarginMap'); // Replace with your MarginMap module
137
+ const ContractsRegistry = require('./ContractsRegistry'); // Replace with your ContractsRegistry module
138
+
139
+ // Fetch margin map for the address
140
+ const marginMap = await MarginMap.getMarginMapForAddress(address);
141
+
142
+ // Check for valid margin map
143
+ if (!marginMap) {
144
+ console.log(`No margin map found for address: ${address}`);
145
+ return null;
146
+ }
147
+
148
+ // Check if the address has a position for the specified contract
149
+ const positionData = marginMap.contracts[contractId];
150
+ if (!positionData) {
151
+ console.log(`No position data found for contract ID: ${contractId} at address: ${address}`);
152
+ return null;
153
+ }
154
+
155
+ const contractInfo = await ContractsRegistry.getContractInfo(contractId);
156
+ if (!contractInfo) {
157
+ console.log(`No contract info found for contract ID: ${contractId}`);
158
+ return null;
159
+ }
160
+
161
+ // Return contract position details
162
+ return {
163
+ contractId: contractId,
164
+ positionSize: positionData.size,
165
+ avgEntryPrice: positionData.avgEntryPrice,
166
+ // Include other relevant contract position details
167
+ };
168
+ }
169
+
170
+ }
171
+
172
+ module.exports = WalletCache;
@@ -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('./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,66 @@
1
+ const Litecoin = require(litecoin); // Replace with your actual Litecoin RPC interface module
2
+ const config = {host: '127.0.0.1',
3
+ port: 18332,
4
+ user: 'user',
5
+ pass: 'pass',
6
+ timeout: 10000}
7
+ const client = new Litecoin(config)
8
+
9
+
10
+ class WalletFetchTxs {
11
+ /**
12
+ * Returns an ordered list of TradeLayer transactions relevant to the wallet.
13
+ */ static async fetchWalletTradeLayerTransactions(wallet, count, startBlock, endBlock) {
14
+ const mapResponse = new Map();
15
+ const seenHashes = new Set();
16
+
17
+ // Fetch wallet transactions using Litecoin RPC
18
+ const transactions = await client.listTransactions("*", 1000, 0, true);
19
+
20
+ // Iterate over transactions to filter and decode TradeLayer transactions
21
+ for (const transaction of transactions) {
22
+ const txHash = transaction.txid;
23
+
24
+ if (seenHashes.has(txHash)) continue;
25
+
26
+ // Retrieve detailed transaction data
27
+ const detailedTx = await client.getTransaction(txHash);
28
+
29
+ // Check for block range
30
+ if (detailedTx.blockindex < startBlock || detailedTx.blockindex > endBlock) {
31
+ continue;
32
+ }
33
+
34
+ // Check and decode OP_Return data
35
+ const opReturnData = this.decodeOpReturn(detailedTx);
36
+ if (opReturnData) {
37
+ // Add transaction data to the map
38
+ mapResponse.set(txHash, {
39
+ blockHeight: detailedTx.blockindex,
40
+ opReturnData,
41
+ transactionDetails: detailedTx
42
+ });
43
+
44
+ seenHashes.add(txHash);
45
+ if (mapResponse.size >= count) break;
46
+ }
47
+ }
48
+
49
+ return mapResponse;
50
+ }
51
+
52
+ static decodeOpReturn(tx) {
53
+ // Decode the OP_Return data from the transaction
54
+ // This function needs to be implemented based on how TradeLayer encodes its data
55
+ // Example:
56
+ const nulldataOutput = tx.vout.find(vout => vout.scriptPubKey.type === 'nulldata');
57
+ if (nulldataOutput) {
58
+ const hexData = nulldataOutput.scriptPubKey.hex;
59
+ // Additional decoding logic goes here
60
+ return hexData;
61
+ }
62
+ return null;
63
+ }
64
+ }
65
+
66
+ module.exports = WalletFetchTxs;
@@ -0,0 +1,97 @@
1
+ const Litecoin = require('litecoin');
2
+ const walletInterface = require('./walletInterface'); // Replace with your actual wallet interface module
3
+ const { addressToPublicKey, decodeDestination, isValidDestination, isHex, parseHex, isValidPubKey, getEstimatedFeePerKb, selectCoins, isMyAddress, getMarketPrice, calculateEconomicThreshold } = require('./walletUtilsHelper'); // Helper functions, to be implemented based on your specific needs// Replace with your actual Litecoin RPC interface module
4
+ const config = {host: '127.0.0.1',
5
+ port: 8332,
6
+ user: 'user',
7
+ pass: 'pass',
8
+ timeout: 10000}
9
+ const client = new Litecoin(config)
10
+
11
+ class WalletUtils {
12
+
13
+
14
+ /**
15
+ * Creates a new TradeLayer address and labels it 'TL'.
16
+ */
17
+ static async createTLAddress(wallet) {
18
+ try {
19
+ // Create a new address
20
+ const newAddress = await client.getNewAddress();
21
+
22
+ // Label the new address as 'TL'
23
+ await client.setLabel(newAddress, "TL");
24
+
25
+ console.log(`New TradeLayer address created and labeled: ${newAddress}`);
26
+ return newAddress;
27
+ } catch (error) {
28
+ console.error('Error creating TradeLayer address:', error);
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Retrieves a public key from the wallet, or converts a hex-string to a public key.
35
+ */
36
+ static async addressToPubKey(wallet, key) {
37
+ if (isValidDestination(key)) {
38
+ const keyID = wallet.getKeyForDestination(key);
39
+ if (!keyID) {
40
+ console.error(`Error: redemption address ${key} does not refer to a public key`);
41
+ return false;
42
+ }
43
+ const pubKey = await wallet.getPubKey(keyID);
44
+ if (!pubKey) {
45
+ console.error(`Error: no public key in wallet for redemption address ${key}`);
46
+ return false;
47
+ }
48
+ return pubKey;
49
+ } else if (isHex(key)) {
50
+ const pubKey = bitcoin.ECPair.fromPublicKey(Buffer.from(parseHex(key)));
51
+ return pubKey;
52
+ }
53
+
54
+ console.error(`Invalid redemption key ${key}`);
55
+ return false;
56
+ }
57
+
58
+ /**
59
+ * Checks, whether enough spendable outputs are available to pay for transaction fees.
60
+ */
61
+ static async checkFee(wallet, fromAddress, dataSize) {
62
+ const feePerKB = await getEstimatedFeePerKb(wallet);
63
+ const inputTotal = await selectCoins(wallet, fromAddress, feePerKB, dataSize);
64
+ return inputTotal >= feePerKB;
65
+ }
66
+
67
+ /**
68
+ * Checks, whether the output qualifies as input for a transaction.
69
+ */
70
+ static checkInput(output, currentHeight) {
71
+ const dest = bitcoin.address.fromOutputScript(output.script, bitcoin.networks.bitcoin); // Adjust for your network
72
+ return isValidDestination(dest) && isValidPubKey(output.scriptPubKey, currentHeight);
73
+ }
74
+
75
+ /**
76
+ * Wrapper to determine whether the address is in the wallet.
77
+ */
78
+ static isMyAddress(wallet, address) {
79
+ return wallet.isMyAddress(address);
80
+ }
81
+
82
+ /**
83
+ * Estimate the minimum fee considering user set parameters and the required fee.
84
+ */
85
+ static getEstimatedFeePerKb(wallet) {
86
+ return wallet.getEstimatedFeePerKb(); // Placeholder, implement based on your wallet interface
87
+ }
88
+
89
+ /**
90
+ * Output values below this value are considered uneconomic.
91
+ */
92
+ static getEconomicThreshold(wallet, output) {
93
+ return calculateEconomicThreshold(wallet, output);
94
+ }
95
+ }
96
+
97
+ module.exports = WalletUtils;