@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,515 @@
1
+ // Import the necessary library for interacting with Litecoin
2
+ const Litecoin = require('litecoin'); // Replace with actual library import
3
+ const async = require('async')
4
+ const util = require('util');
5
+ const litecore = require('bitcore-lib-ltc');
6
+ const COIN = 100000000
7
+ const STANDARD_FEE = 10000; // Standard fee in LTC
8
+ const client = new Litecoin.Client({
9
+ host: '127.0.0.1',
10
+ port: 18332,
11
+ user: 'user',
12
+ pass: 'pass',
13
+ timeout: 10000
14
+ });
15
+
16
+ // Promisify the necessary client functions
17
+ const getRawTransactionAsync = util.promisify(client.getRawTransaction.bind(client));
18
+ const createRawTransactionAsync = util.promisify(client.createRawTransaction.bind(client));
19
+ const listUnspentAsync = util.promisify(client.cmd.bind(client, 'listunspent'));
20
+ const decoderawtransactionAsync = util.promisify(client.cmd.bind(client, 'decoderawtransaction'));
21
+ const signrawtransactionwithwalletAsync = util.promisify(client.cmd.bind(client, 'signrawtransactionwithwallet'));
22
+ const dumpprivkeyAsync = util.promisify(client.cmd.bind(client, 'dumpprivkey'))
23
+ const DUST_THRESHOLD= 54600
24
+
25
+ const TxUtils = {
26
+ async getRawTransaction(txId) {
27
+ try {
28
+ // Use the promisified version of getRawTransaction
29
+ return await getRawTransactionAsync(txId, true); // true for verbose mode
30
+ } catch (error) {
31
+ console.error(`Error fetching transaction ${txId}:`, error);
32
+ throw error;
33
+ }
34
+ },
35
+
36
+ async getSender(txId) {
37
+ const tx = await this.getRawTransaction(txId);
38
+ if (!tx || !tx.vin || tx.vin.length === 0) {
39
+ throw new Error(`Invalid transaction data for ${txId}`);
40
+ }
41
+
42
+ const vin = tx.vin[0]; // Assuming we're only interested in the first input
43
+ if (!vin.txid) {
44
+ throw new Error(`No previous transaction reference in input for ${txId}`);
45
+ }
46
+
47
+ const parentTx = await this.getRawTransaction(vin.txid);
48
+ if (!parentTx || !parentTx.vout || parentTx.vout.length <= vin.vout) {
49
+ throw new Error(`Invalid parent transaction data for ${vin.txid}`);
50
+ }
51
+
52
+ const output = parentTx.vout[vin.vout];
53
+ if (!output || !output.scriptPubKey || !output.scriptPubKey.addresses) {
54
+ throw new Error(`No output found for vin ${vin.vout} in transaction ${vin.txid}`);
55
+ }
56
+
57
+ const senderAddress = output.scriptPubKey.addresses[0]; // Assuming single address
58
+ const amount = output.value; // Amount in LTC
59
+
60
+ return { senderAddress, amount };
61
+ },
62
+
63
+ async getReference(txId) {
64
+ try {
65
+ const tx = await this.getRawTransaction(txId);
66
+ if (!tx || !tx.vout) {
67
+ throw new Error(`Invalid transaction data for ${txId}`);
68
+ }
69
+
70
+ let referenceOutput = null;
71
+
72
+ // Iterate over outputs to find the last non-OP_RETURN output
73
+ for (let i = tx.vout.length - 1; i >= 0; i--) {
74
+ const output = tx.vout[i];
75
+ if (output.scriptPubKey.type !== 'nulldata') { // 'nulldata' type is typically used for OP_RETURN
76
+ referenceOutput = output;
77
+ break;
78
+ }
79
+ }
80
+
81
+ if (referenceOutput) {
82
+ const address = referenceOutput.scriptPubKey.addresses[0]; // Assuming single address
83
+ const satoshis = Math.round(referenceOutput.value * COIN); // Convert LTC to satoshis
84
+ console.log(satoshis)
85
+ return { address, satoshis };
86
+ } else {
87
+ throw new Error("Reference output not found");
88
+ }
89
+ } catch (error) {
90
+ console.error(`Error in getReference for transaction ${txId}:`, error);
91
+ throw error;
92
+ }
93
+ },
94
+
95
+ async listUnspent(minconf, maxconf, addresses) {
96
+ try {
97
+ // Use the promisified version of listUnspent
98
+ return await listUnspentAsync(minconf, maxconf, addresses);
99
+ } catch (error) {
100
+ console.error(`Error listing UTXOs:`, error);
101
+ throw error;
102
+ }
103
+ },
104
+
105
+ async decoderawtransaction(hexString) {
106
+ try {
107
+ // Use the promisified version of decoderawtransaction
108
+ return await decoderawtransactionAsync(hexString);
109
+ } catch (error) {
110
+ console.error(`Error decoding raw transaction:`, error);
111
+ throw error;
112
+ }
113
+ },
114
+
115
+ async signrawtransactionwithwallet(rawTx) {
116
+ try {
117
+ // Use the promisified version of signrawtransactionwithwallet
118
+ return await signrawtransactionwithwalletAsync(rawTx);
119
+ } catch (error) {
120
+ console.error(`Error signing raw transaction with wallet:`, error);
121
+ throw error;
122
+ }
123
+ },
124
+
125
+ async getPayload(txId) {
126
+ try {
127
+ const tx = await this.getRawTransaction(txId);
128
+ if (!tx || !tx.vout) {
129
+ throw new Error(`Invalid transaction data for ${txId}`);
130
+ }
131
+
132
+ for (const output of tx.vout) {
133
+ // Check if the output's script type is 'nulldata', which is used for OP_RETURN
134
+ if (output.scriptPubKey.type === 'nulldata') {
135
+ // The actual payload data is typically in the 'asm' part of the scriptPubKey
136
+ // It's usually hex-encoded, so you might need to convert it from hex to a string
137
+ const payloadData = output.scriptPubKey.asm;
138
+ return payloadData;
139
+ }
140
+ }
141
+
142
+ throw new Error("Payload not found in transaction");
143
+ } catch (error) {
144
+ console.error(`Error in getPayload for transaction ${txId}:`, error);
145
+ throw error;
146
+ }
147
+ },
148
+
149
+ async getAdditionalInputs(txId) {
150
+ try {
151
+ const tx = await this.getRawTransaction(txId);
152
+ if (!tx || !tx.vin || tx.vin.length <= 1) {
153
+ return []; // No additional inputs beyond the first
154
+ }
155
+
156
+ let additionalInputs = [];
157
+ for (let i = 1; i < tx.vin.length; i++) { // Start from second input
158
+ const input = tx.vin[i];
159
+
160
+ if (!input.txid) {
161
+ throw new Error(`No previous transaction reference in input for ${txId}`);
162
+ }
163
+
164
+ const parentTx = await this.getRawTransaction(input.txid);
165
+ if (!parentTx || !parentTx.vout || parentTx.vout.length <= input.vout) {
166
+ throw new Error(`Invalid parent transaction data for ${input.txid}`);
167
+ }
168
+
169
+ const output = parentTx.vout[input.vout];
170
+ if (!output || !output.scriptPubKey || !output.scriptPubKey.addresses) {
171
+ throw new Error(`No output found for vin ${input.vout} in transaction ${input.txid}`);
172
+ }
173
+
174
+ const address = output.scriptPubKey.addresses[0]; // Assuming single address
175
+ const amount = output.value; // Amount in LTC
176
+
177
+ additionalInputs.push({ address, amount });
178
+ }
179
+
180
+ return additionalInputs;
181
+ } catch (error) {
182
+ console.error(`Error in getAdditionalInputs for transaction ${txId}:`, error);
183
+ throw error;
184
+ }
185
+ },
186
+
187
+ async setSender(address, requiredAmount) {
188
+ // First, get UTXOs for the specific address
189
+ let utxos = await listUnspentAsync('listunspent', 0, 9999999, [address]);
190
+
191
+ // Sort UTXOs by amount, descending
192
+ utxos.sort((a, b) => b.amount - a.amount);
193
+
194
+ let selectedUtxos = [];
195
+ let totalAmount = 0;
196
+
197
+ // Try to meet the required amount with UTXOs from the specified address
198
+ for (let utxo of utxos) {
199
+ selectedUtxos.push(utxo);
200
+ totalAmount += utxo.amount;
201
+ if (totalAmount >= requiredAmount) {
202
+ return selectedUtxos;
203
+ }
204
+ }
205
+
206
+ // If not enough, get all UTXOs in the wallet
207
+ let allUtxos = await client.cmd('listunspent', 0, 9999999);
208
+ // Exclude UTXOs already selected
209
+ allUtxos = allUtxos.filter(utxo => !selectedUtxos.includes(utxo));
210
+
211
+ // Sort the remaining UTXOs by amount, descending
212
+ allUtxos.sort((a, b) => b.amount - a.amount);
213
+
214
+ // Add additional UTXOs from the wallet
215
+ for (let utxo of allUtxos) {
216
+ if (utxo.address !== address) { // Ensure UTXOs from the specified address are first
217
+ selectedUtxos.push(utxo);
218
+ totalAmount += utxo.amount;
219
+ if (totalAmount >= requiredAmount) {
220
+ break;
221
+ }
222
+ }
223
+ }
224
+
225
+ // Check if the total amount is still insufficient
226
+ if (totalAmount < requiredAmount) {
227
+ throw new Error('Insufficient funds: Total UTXOs amount is less than the required amount');
228
+ }
229
+
230
+ return selectedUtxos;
231
+ },
232
+
233
+ async createRawTransaction(inputs, outputs, locktime = 0, replaceable = false) {
234
+ const transaction = new litecore.Transaction();
235
+
236
+ for (const input of inputs) {
237
+ // Fetch the raw transaction to which this input refers
238
+ const tx = await this.getRawTransaction(input.txid);
239
+ const utxo = tx.vout[input.vout];
240
+ const scriptPubKey = utxo.scriptPubKey.hex;
241
+ const value = Math.round(utxo.value*COIN)
242
+ console.log(value)
243
+ // Add UTXO to the transaction
244
+ transaction.from({
245
+ txId: input.txid,
246
+ outputIndex: input.vout,
247
+ script: scriptPubKey,
248
+ satoshis: value // Convert LTC to satoshis
249
+ });
250
+ }
251
+
252
+ // Add outputs
253
+ outputs.forEach(output => {
254
+ if (output.address) {
255
+ transaction.to(output.address, output.amount * COIN); // Convert LTC to satoshis
256
+ console.log(output.amount*COIN)
257
+ }
258
+ // Handle data (OP_RETURN) outputs
259
+ else if (output.data) {
260
+ const script = litecore.Script.buildDataOut(output.data, 'hex');
261
+ transaction.addOutput(new litecore.Transaction.Output({ script: script, satoshis: 0 }));
262
+ }
263
+ });
264
+
265
+ // Set locktime if specified
266
+ if (locktime > 0) {
267
+ transaction.lockUntilDate(locktime);
268
+ }
269
+
270
+ return transaction;
271
+ },
272
+
273
+ addPayload(payload, rawTx) {
274
+ const transaction = new litecore.Transaction(rawTx);
275
+ const script = litecore.Script.buildDataOut('tl' + payload, 'hex');
276
+ transaction.addOutput(new litecore.Transaction.Output({ script: script, satoshis: 0 }));
277
+ return transaction.toString();
278
+ },
279
+
280
+ async setChange(senderAddress, rawTx) {
281
+ console.log(rawTx)
282
+ const transaction = new litecore.Transaction(rawTx);
283
+ console.log(transaction)
284
+ // Fetch UTXOs for the inputs to get their amounts
285
+ for (let input of transaction.inputs) {
286
+ let txid = input.prevTxId.toString('hex');
287
+ let index = input.outputIndex;
288
+ let utxoData = await this.getRawTransaction(txid);
289
+ let utxo = utxoData.vout[index];
290
+ input.output = new litecore.Transaction.Output({
291
+ satoshis: Math.round(utxo.value * COIN),
292
+ script: new litecore.Script(utxo.scriptPubKey.hex)
293
+ });
294
+ }
295
+
296
+ // Calculate the change amount
297
+ console.log(transaction.inputs)
298
+ console.log(transaction.outputs)
299
+ const inputAmount = transaction.inputs.reduce((sum, input) => sum + input.output.satoshis, 0);
300
+ const outputAmount = transaction.outputs.reduce((sum, output) => sum + output.satoshis, 0);
301
+ const changeAmount = inputAmount - outputAmount - STANDARD_FEE;
302
+
303
+ // Add change output if above dust threshold
304
+ if (changeAmount > DUST_THRESHOLD) {
305
+ transaction.change(senderAddress);
306
+ }
307
+
308
+ return transaction.serialize();
309
+ },
310
+
311
+
312
+
313
+ signTransaction(rawTx, privateKey) {
314
+ const transaction = new litecore.Transaction(rawTx);
315
+ const privateKeyObj = new litecore.PrivateKey(privateKey);
316
+ transaction.sign(privateKeyObj);
317
+ return transaction.toString();
318
+ },
319
+
320
+ async beginRawTransaction(txid, vout) {
321
+ try {
322
+ // Specify the input using txid and vout
323
+ const inputs = [{
324
+ txid: txid,
325
+ vout: vout
326
+ }];
327
+
328
+ // Define a minimal set of outputs, can be an empty object for now
329
+ const outputs = {};
330
+
331
+ // Create the raw transaction
332
+ const rawTx = await this.createRawTransaction(inputs, [outputs]);
333
+
334
+ return rawTx;
335
+ } catch (error) {
336
+ console.error(`Error in createRawTransaction:`, error);
337
+ throw error;
338
+ }
339
+ },
340
+
341
+
342
+ async addInputs(utxos, rawTx) {
343
+ // Decode the raw transaction to modify it
344
+ let decodedTx = await decoderawtransactionAsync('decoderawtransaction', rawTx);
345
+
346
+ // Add each UTXO as an input
347
+ utxos.forEach(utxo => {
348
+ decodedTx.vin.push({
349
+ txid: utxo.txid,
350
+ vout: utxo.vout
351
+ });
352
+ });
353
+
354
+ // Re-encode the transaction
355
+ return await client.cmd('createrawtransaction', decodedTx.vin, decodedTx.vout);
356
+ },
357
+
358
+ async constructInitialTradeTokenTx(params, senderChannel) {
359
+ // Retrieve the UTXO for the senderChannel address
360
+ const utxos = await listUnspentAsync('listunspent', 0, 9999999, [senderChannel]);
361
+ if (utxos.length === 0) {
362
+ throw new Error('No UTXOs found for the sender channel address');
363
+ }
364
+ // Select the appropriate UTXO (e.g., based on criteria like highest amount or specific logic)
365
+ const selectedUtxo = utxos[0]; // Simple selection logic, adjust as needed
366
+
367
+ // Update params with the chosen UTXO details
368
+ params.channelUtxo = {
369
+ txid: selectedUtxo.txid,
370
+ vout: selectedUtxo.vout
371
+ };
372
+
373
+ // Create the OP_RETURN payload
374
+ let payload = "tl3";
375
+ payload += Encoding.encodeTradeTokenForUTXO({
376
+ ...params,
377
+ // Include the reference address if needed
378
+ referenceAddress: senderChannel // or another address if required
379
+ });
380
+
381
+ // Create the transaction with the channel address as the first input
382
+ let rawTx = await client.cmd('createrawtransaction', [[{
383
+ txid: params.channelUtxo.txid,
384
+ vout: params.channelUtxo.vout
385
+ }], []]);
386
+
387
+ // Add the OP_RETURN payload
388
+ rawTx = await addPayload(payload, rawTx);
389
+
390
+ // Add a change output for the token seller
391
+ rawTx = await setChange(params.sellerChangeAddress, params.sellerChangeAmount, rawTx);
392
+
393
+ // Sign the transaction
394
+ let signedTx = await client.cmd('signrawtransactionwithwallet', rawTx);
395
+
396
+ // Return the partially constructed and signed raw transaction
397
+ return signedTx;
398
+ },
399
+
400
+ async finalizeTradeTokenTx(initialRawTx, additionalParams) {
401
+ // additionalParams might include additionalUtxos, buyerChangeAddress, referenceAddress, etc.
402
+
403
+ // Add additional UTXO inputs for UTXO consideration
404
+ let rawTx = await addInputs(additionalParams.additionalUtxos, initialRawTx);
405
+
406
+ // Add a change output for the UTXO spender/buyer
407
+ rawTx = await setChange(additionalParams.buyerChangeAddress, additionalParams.buyerChangeAmount, rawTx);
408
+
409
+ // Add the reference output, ensuring it matches the address in the OP_RETURN payload
410
+ // (Assuming the logic to add a standard output is similar to setChange)
411
+ rawTx = await setChange(additionalParams.referenceAddress, additionalParams.referenceAmount, rawTx);
412
+
413
+ // Re-sign the transaction to include the new inputs and outputs
414
+ let signedTx = await client.cmd('signrawtransactionwithwallet', rawTx);
415
+
416
+ // Return the fully constructed and signed raw transaction
417
+ return signedTx;
418
+ },
419
+
420
+
421
+ async parseAndCoSignMultisigTransaction(rawTx, expectedUTXOValue, coSignerAddress, coSignerPrivateKey, network) {
422
+ // Step 1: Decode the raw transaction
423
+ const decodedTx = await TxUtils.decodeRawTransaction(rawTx, network);
424
+
425
+ // Step 2: Analyze the transaction outputs to find the reference/payment address and its value
426
+ // Step 2: Analyze the transaction outputs to find the reference/payment address and its value
427
+ // The reference output is the last output before the OP_RETURN or null data output
428
+ let paymentOutputIndex = decodedTx.vout.findIndex(output => output.scriptPubKey.type === 'nulldata');
429
+ if (paymentOutputIndex === -1 || paymentOutputIndex === 0) {
430
+ throw new Error('No OP_RETURN output found or no outputs before OP_RETURN');
431
+ }
432
+ let paymentOutput = decodedTx.vout[paymentOutputIndex - 1]; // Getting the output before OP_RETURN
433
+
434
+ if (!paymentOutput || paymentOutput.value < expectedUTXOValue) {
435
+ throw new Error('Transaction does not meet the expected UTXO value criteria');
436
+ }
437
+
438
+ // Step 3: If the transaction is valid, prepare to co-sign it
439
+ // Fetch additional UTXOs for the coSignerAddress if necessary
440
+ const additionalUTXOs = await TxUtils.getAdditionalUTXOs(coSignerAddress, expectedUTXOValue - paymentOutput.value, network);
441
+
442
+ // Step 4: Add the additional UTXOs to the transaction
443
+ rawTx = await TxUtils.addInputsToTransaction(rawTx, additionalUTXOs, network);
444
+
445
+ // Step 5: Co-sign the transaction
446
+ const coSignedTx = await TxUtils.coSignTransaction(rawTx, coSignerPrivateKey, network);
447
+
448
+ // Step 6: Optionally, you can broadcast the transaction
449
+ // const txId = await TxUtils.broadcastTransaction(coSignedTx, network);
450
+
451
+ return coSignedTx; // Return the co-signed transaction
452
+ },
453
+
454
+ async sendTransaction(fromAddress, toAddress, amount, opReturnData = null) {
455
+ try {
456
+ // Get private key for the fromAddress
457
+ const privateKey = await dumpprivkeyAsync(fromAddress);
458
+
459
+ // Find a suitable UTXO
460
+ const minAmountSatoshis = amount + STANDARD_FEE; // Sum of amount and STANDARD_FEE to cover the cost
461
+ const utxo = await this.findSuitableUTXO(fromAddress, minAmountSatoshis);
462
+
463
+ // Create the transaction
464
+ let transaction = new litecore.Transaction()
465
+ .from(utxo)
466
+ .to(toAddress, amount)
467
+ .fee(STANDARD_FEE)
468
+ .change(fromAddress);
469
+
470
+ // Add OP_RETURN data if provided
471
+ if (opReturnData) {
472
+ transaction.addData(opReturnData);
473
+ }
474
+
475
+ // Sign the transaction
476
+ transaction.sign(privateKey);
477
+
478
+ // Serialize and send the transaction
479
+ const serializedTx = transaction.serialize();
480
+ const txid = await sendrawtransactionAsync(serializedTx);
481
+ return txid;
482
+ } catch (error) {
483
+ console.error('Error in sendTransaction:', error);
484
+ throw error;
485
+ }
486
+ },
487
+
488
+ async findSuitableUTXO(address, minAmount) {
489
+ const utxos = await listUnspentAsync(0, 9999999, [address]);
490
+ console.log("UTXOs:", utxos);
491
+ console.log("Min amount in satoshis:", minAmount);
492
+
493
+ const suitableUtxo = utxos.find(utxo => {
494
+ const utxoSatoshis = Math.round(utxo.amount * COIN);
495
+ console.log(`UTXO Amount in satoshis: ${utxoSatoshis}, Required Min Amount: ${minAmount}`);
496
+ return utxoSatoshis >= minAmount;
497
+ });
498
+
499
+ if (!suitableUtxo) {
500
+ throw new Error('No suitable UTXO found.');
501
+ }
502
+
503
+ return {
504
+ txId: suitableUtxo.txid,
505
+ outputIndex: suitableUtxo.vout,
506
+ address: suitableUtxo.address,
507
+ script: suitableUtxo.scriptPubKey,
508
+ satoshis: Math.round(suitableUtxo.amount * COIN)
509
+ };
510
+ }
511
+
512
+
513
+ };
514
+
515
+ module.exports = TxUtils;
@@ -0,0 +1,53 @@
1
+ const Validity = require('./validity.js')
2
+
3
+ async function testValidateActivateTradeLayer() {
4
+ const txId = 'dummyTxId';
5
+ const params = { txTypeToActivate: 0 };
6
+ const sender = 'tltc1qa0kd2d39nmeph3hvcx8ytv65ztcywg5sazhtw8';
7
+
8
+ // Mocking isTxTypeActive
9
+ //activationInstance.isTxTypeActive = async () => false;
10
+
11
+ const result = await Validity.validateActivateTradeLayer(txId, params, sender);
12
+ console.log('Test validateActivateTradeLayer:', result);
13
+ }
14
+
15
+ testValidateActivateTradeLayer();
16
+ /*
17
+ async function testValidateTokenIssue() {
18
+ const params = {
19
+ initialAmount: 100,
20
+ ticker: 'TOKEN',
21
+ type: 'native',
22
+ propertyId: 1
23
+ };
24
+
25
+ // Mocking isTxTypeActive
26
+ activationInstance.isTxTypeActive = async () => true;
27
+
28
+ const result = await validateTokenIssue(params);
29
+ console.log('Test validateTokenIssue:', result);
30
+ }
31
+
32
+ testValidateTokenIssue();
33
+
34
+ async function testValidateSend() {
35
+ const params = {
36
+ senderAddress: 'senderAddressExample',
37
+ propertyId: 1,
38
+ amount: 50
39
+ };
40
+
41
+ // Mocking isTxTypeActive
42
+ activationInstance.isTxTypeActive = async () => true;
43
+
44
+ // Mocking getTally
45
+ const TallyMap = require('./tally.js');
46
+ TallyMap.getTally = async () => ({ available: 100 });
47
+
48
+ const result = await validateSend(params);
49
+ console.log('Test validateSend:', result);
50
+ }
51
+
52
+ testValidateSend();
53
+ */
@@ -0,0 +1,72 @@
1
+ const level = require('level');
2
+ const db = level('./path_to_synthetic_vaults_db');
3
+
4
+ class SynthRegistry {
5
+ constructor() {
6
+ this.vaults = new Map();
7
+ this.syntheticTokens = new Map();
8
+ }
9
+
10
+ // Create a new vault for a synthetic token
11
+ createVault(propertyId, contractId) {
12
+ const vaultId = this.generateVaultId();
13
+ this.vaults.set(vaultId, { propertyId, contractId, amount: 0, address: '' /* ... other vault details ... */ });
14
+ this.saveVault(vaultId);
15
+ return vaultId;
16
+ }
17
+
18
+ // Update the amount in a vault
19
+ updateVault(vaultId, amount) {
20
+ if (!this.vaults.has(vaultId)) {
21
+ throw new Error('Vault not found');
22
+ }
23
+ const vault = this.vaults.get(vaultId);
24
+ vault.amount += amount;
25
+ this.saveVault(vaultId);
26
+ }
27
+
28
+ // Get vault information
29
+ getVault(vaultId) {
30
+ return this.vaults.get(vaultId);
31
+ }
32
+
33
+ // Register a new synthetic token
34
+ registerSyntheticToken(syntheticTokenId, vaultId, initialAmount) {
35
+ this.syntheticTokens.set(syntheticTokenId, { vaultId, amount: initialAmount });
36
+ this.saveSyntheticToken(syntheticTokenId);
37
+ }
38
+
39
+ // Check if a synthetic token exists
40
+ exists(syntheticTokenId) {
41
+ return this.syntheticTokens.has(syntheticTokenId);
42
+ }
43
+
44
+ // Get vault ID for a synthetic token
45
+ getVaultId(syntheticTokenId) {
46
+ return this.syntheticTokens.get(syntheticTokenId)?.vaultId;
47
+ }
48
+
49
+ // Generate a unique vault ID
50
+ generateVaultId() {
51
+ // Implement logic to generate a unique vault ID
52
+ }
53
+
54
+ // Persist vault data to the database
55
+ async saveVault(vaultId) {
56
+ await db.put(`vault-${vaultId}`, JSON.stringify(this.vaults.get(vaultId)));
57
+ }
58
+
59
+ // Persist synthetic token data to the database
60
+ async saveSyntheticToken(syntheticTokenId) {
61
+ await db.put(`synth-${syntheticTokenId}`, JSON.stringify(this.syntheticTokens.get(syntheticTokenId)));
62
+ }
63
+
64
+ // Load vaults and synthetic tokens from the database
65
+ async loadFromDatabase() {
66
+ // Implement loading logic
67
+ }
68
+
69
+ // ... other necessary methods ...
70
+ }
71
+
72
+ module.exports = SynthRegistry;