@silvana-one/mina-utils 0.2.0

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 (174) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1 -0
  3. package/dist/node/config.d.ts +4 -0
  4. package/dist/node/config.js +5 -0
  5. package/dist/node/config.js.map +1 -0
  6. package/dist/node/index.cjs +1325 -0
  7. package/dist/node/index.d.ts +6 -0
  8. package/dist/node/index.js +7 -0
  9. package/dist/node/index.js.map +1 -0
  10. package/dist/node/networks.d.ts +32 -0
  11. package/dist/node/networks.js +81 -0
  12. package/dist/node/networks.js.map +1 -0
  13. package/dist/node/storage/index.d.ts +2 -0
  14. package/dist/node/storage/index.js +3 -0
  15. package/dist/node/storage/index.js.map +1 -0
  16. package/dist/node/storage/ipfs.d.ts +5 -0
  17. package/dist/node/storage/ipfs.js +16 -0
  18. package/dist/node/storage/ipfs.js.map +1 -0
  19. package/dist/node/storage/pinata.d.ts +6 -0
  20. package/dist/node/storage/pinata.js +40 -0
  21. package/dist/node/storage/pinata.js.map +1 -0
  22. package/dist/node/transactions/account.d.ts +4 -0
  23. package/dist/node/transactions/account.js +44 -0
  24. package/dist/node/transactions/account.js.map +1 -0
  25. package/dist/node/transactions/blockberry.d.ts +21 -0
  26. package/dist/node/transactions/blockberry.js +130 -0
  27. package/dist/node/transactions/blockberry.js.map +1 -0
  28. package/dist/node/transactions/chain.d.ts +1 -0
  29. package/dist/node/transactions/chain.js +2 -0
  30. package/dist/node/transactions/chain.js.map +1 -0
  31. package/dist/node/transactions/index.d.ts +8 -0
  32. package/dist/node/transactions/index.js +9 -0
  33. package/dist/node/transactions/index.js.map +1 -0
  34. package/dist/node/transactions/nonce.d.ts +17 -0
  35. package/dist/node/transactions/nonce.js +91 -0
  36. package/dist/node/transactions/nonce.js.map +1 -0
  37. package/dist/node/transactions/send.d.ts +31 -0
  38. package/dist/node/transactions/send.js +154 -0
  39. package/dist/node/transactions/send.js.map +1 -0
  40. package/dist/node/transactions/tiny-contract.d.ts +5 -0
  41. package/dist/node/transactions/tiny-contract.js +22 -0
  42. package/dist/node/transactions/tiny-contract.js.map +1 -0
  43. package/dist/node/transactions/transaction.d.ts +21 -0
  44. package/dist/node/transactions/transaction.js +222 -0
  45. package/dist/node/transactions/transaction.js.map +1 -0
  46. package/dist/node/transactions/txstatus.d.ts +8 -0
  47. package/dist/node/transactions/txstatus.js +16 -0
  48. package/dist/node/transactions/txstatus.js.map +1 -0
  49. package/dist/node/utils/base64-field.d.ts +5 -0
  50. package/dist/node/utils/base64-field.js +29 -0
  51. package/dist/node/utils/base64-field.js.map +1 -0
  52. package/dist/node/utils/base64.d.ts +6 -0
  53. package/dist/node/utils/base64.js +83 -0
  54. package/dist/node/utils/base64.js.map +1 -0
  55. package/dist/node/utils/fee.d.ts +6 -0
  56. package/dist/node/utils/fee.js +11 -0
  57. package/dist/node/utils/fee.js.map +1 -0
  58. package/dist/node/utils/fetch.d.ts +44 -0
  59. package/dist/node/utils/fetch.js +101 -0
  60. package/dist/node/utils/fetch.js.map +1 -0
  61. package/dist/node/utils/fields.d.ts +13 -0
  62. package/dist/node/utils/fields.js +39 -0
  63. package/dist/node/utils/fields.js.map +1 -0
  64. package/dist/node/utils/index.d.ts +8 -0
  65. package/dist/node/utils/index.js +9 -0
  66. package/dist/node/utils/index.js.map +1 -0
  67. package/dist/node/utils/indexed-map.d.ts +32 -0
  68. package/dist/node/utils/indexed-map.js +124 -0
  69. package/dist/node/utils/indexed-map.js.map +1 -0
  70. package/dist/node/utils/mina.d.ts +39 -0
  71. package/dist/node/utils/mina.js +123 -0
  72. package/dist/node/utils/mina.js.map +1 -0
  73. package/dist/node/utils/utils.d.ts +8 -0
  74. package/dist/node/utils/utils.js +61 -0
  75. package/dist/node/utils/utils.js.map +1 -0
  76. package/dist/tsconfig.tsbuildinfo +1 -0
  77. package/dist/tsconfig.web.tsbuildinfo +1 -0
  78. package/dist/web/config.d.ts +4 -0
  79. package/dist/web/config.js +5 -0
  80. package/dist/web/config.js.map +1 -0
  81. package/dist/web/index.d.ts +6 -0
  82. package/dist/web/index.js +7 -0
  83. package/dist/web/index.js.map +1 -0
  84. package/dist/web/networks.d.ts +32 -0
  85. package/dist/web/networks.js +81 -0
  86. package/dist/web/networks.js.map +1 -0
  87. package/dist/web/storage/index.d.ts +2 -0
  88. package/dist/web/storage/index.js +3 -0
  89. package/dist/web/storage/index.js.map +1 -0
  90. package/dist/web/storage/ipfs.d.ts +5 -0
  91. package/dist/web/storage/ipfs.js +16 -0
  92. package/dist/web/storage/ipfs.js.map +1 -0
  93. package/dist/web/storage/pinata.d.ts +6 -0
  94. package/dist/web/storage/pinata.js +40 -0
  95. package/dist/web/storage/pinata.js.map +1 -0
  96. package/dist/web/transactions/account.d.ts +4 -0
  97. package/dist/web/transactions/account.js +44 -0
  98. package/dist/web/transactions/account.js.map +1 -0
  99. package/dist/web/transactions/blockberry.d.ts +21 -0
  100. package/dist/web/transactions/blockberry.js +130 -0
  101. package/dist/web/transactions/blockberry.js.map +1 -0
  102. package/dist/web/transactions/chain.d.ts +1 -0
  103. package/dist/web/transactions/chain.js +2 -0
  104. package/dist/web/transactions/chain.js.map +1 -0
  105. package/dist/web/transactions/index.d.ts +8 -0
  106. package/dist/web/transactions/index.js +9 -0
  107. package/dist/web/transactions/index.js.map +1 -0
  108. package/dist/web/transactions/nonce.d.ts +17 -0
  109. package/dist/web/transactions/nonce.js +91 -0
  110. package/dist/web/transactions/nonce.js.map +1 -0
  111. package/dist/web/transactions/send.d.ts +31 -0
  112. package/dist/web/transactions/send.js +154 -0
  113. package/dist/web/transactions/send.js.map +1 -0
  114. package/dist/web/transactions/tiny-contract.d.ts +5 -0
  115. package/dist/web/transactions/tiny-contract.js +22 -0
  116. package/dist/web/transactions/tiny-contract.js.map +1 -0
  117. package/dist/web/transactions/transaction.d.ts +21 -0
  118. package/dist/web/transactions/transaction.js +222 -0
  119. package/dist/web/transactions/transaction.js.map +1 -0
  120. package/dist/web/transactions/txstatus.d.ts +8 -0
  121. package/dist/web/transactions/txstatus.js +16 -0
  122. package/dist/web/transactions/txstatus.js.map +1 -0
  123. package/dist/web/utils/base64-field.d.ts +5 -0
  124. package/dist/web/utils/base64-field.js +29 -0
  125. package/dist/web/utils/base64-field.js.map +1 -0
  126. package/dist/web/utils/base64.d.ts +6 -0
  127. package/dist/web/utils/base64.js +83 -0
  128. package/dist/web/utils/base64.js.map +1 -0
  129. package/dist/web/utils/fee.d.ts +6 -0
  130. package/dist/web/utils/fee.js +11 -0
  131. package/dist/web/utils/fee.js.map +1 -0
  132. package/dist/web/utils/fetch.d.ts +44 -0
  133. package/dist/web/utils/fetch.js +101 -0
  134. package/dist/web/utils/fetch.js.map +1 -0
  135. package/dist/web/utils/fields.d.ts +13 -0
  136. package/dist/web/utils/fields.js +39 -0
  137. package/dist/web/utils/fields.js.map +1 -0
  138. package/dist/web/utils/index.d.ts +8 -0
  139. package/dist/web/utils/index.js +9 -0
  140. package/dist/web/utils/index.js.map +1 -0
  141. package/dist/web/utils/indexed-map.d.ts +32 -0
  142. package/dist/web/utils/indexed-map.js +124 -0
  143. package/dist/web/utils/indexed-map.js.map +1 -0
  144. package/dist/web/utils/mina.d.ts +39 -0
  145. package/dist/web/utils/mina.js +123 -0
  146. package/dist/web/utils/mina.js.map +1 -0
  147. package/dist/web/utils/utils.d.ts +8 -0
  148. package/dist/web/utils/utils.js +61 -0
  149. package/dist/web/utils/utils.js.map +1 -0
  150. package/package.json +62 -0
  151. package/src/config.ts +5 -0
  152. package/src/index.ts +6 -0
  153. package/src/networks.ts +130 -0
  154. package/src/storage/index.ts +2 -0
  155. package/src/storage/ipfs.ts +20 -0
  156. package/src/storage/pinata.ts +56 -0
  157. package/src/transactions/account.ts +57 -0
  158. package/src/transactions/blockberry.ts +198 -0
  159. package/src/transactions/chain.ts +1 -0
  160. package/src/transactions/index.ts +8 -0
  161. package/src/transactions/nonce.ts +121 -0
  162. package/src/transactions/send.ts +228 -0
  163. package/src/transactions/tiny-contract.ts +9 -0
  164. package/src/transactions/transaction.ts +319 -0
  165. package/src/transactions/txstatus.ts +26 -0
  166. package/src/utils/base64-field.ts +34 -0
  167. package/src/utils/base64.ts +87 -0
  168. package/src/utils/fee.ts +11 -0
  169. package/src/utils/fetch.ts +130 -0
  170. package/src/utils/fields.ts +39 -0
  171. package/src/utils/index.ts +8 -0
  172. package/src/utils/indexed-map.ts +170 -0
  173. package/src/utils/mina.ts +171 -0
  174. package/src/utils/utils.ts +79 -0
@@ -0,0 +1,1325 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // dist/node/index.js
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Devnet: () => Devnet,
24
+ Lightnet: () => Lightnet,
25
+ Local: () => Local,
26
+ Mainnet: () => Mainnet,
27
+ Memory: () => Memory,
28
+ TinyContract: () => TinyContract,
29
+ Zeko: () => Zeko,
30
+ accountBalance: () => accountBalance,
31
+ accountBalanceMina: () => accountBalanceMina,
32
+ accountExists: () => accountExists,
33
+ bigintFromBase56: () => bigintFromBase56,
34
+ bigintFromBase64: () => bigintFromBase64,
35
+ bigintToBase56: () => bigintToBase56,
36
+ bigintToBase64: () => bigintToBase64,
37
+ checkAddress: () => checkAddress,
38
+ checkMinaZkappTransaction: () => checkMinaZkappTransaction,
39
+ createIpfsURL: () => createIpfsURL,
40
+ createTransactionPayloads: () => createTransactionPayloads,
41
+ currentNetwork: () => currentNetwork,
42
+ deserializeFields: () => deserializeFields,
43
+ deserializeIndexedMerkleMap: () => deserializeIndexedMerkleMap,
44
+ fee: () => fee,
45
+ fetchMinaAccount: () => fetchMinaAccount,
46
+ fetchMinaActions: () => fetchMinaActions,
47
+ fieldFromBase56: () => fieldFromBase56,
48
+ fieldFromBase64: () => fieldFromBase64,
49
+ fieldToBase56: () => fieldToBase56,
50
+ fieldToBase64: () => fieldToBase64,
51
+ formatTime: () => formatTime,
52
+ fromBase: () => fromBase,
53
+ getAccountNonce: () => getAccountNonce,
54
+ getCurrentNetwork: () => getCurrentNetwork,
55
+ getDeployer: () => getDeployer,
56
+ getNetworkIdHash: () => getNetworkIdHash,
57
+ getNonce: () => getNonce,
58
+ getPaymentTxsFromBlockBerry: () => getPaymentTxsFromBlockBerry,
59
+ getTxStatusFast: () => getTxStatusFast,
60
+ getZkAppFromBlockBerry: () => getZkAppFromBlockBerry,
61
+ getZkAppTxFromBlockBerry: () => getZkAppTxFromBlockBerry,
62
+ getZkAppTxsFromBlockBerry: () => getZkAppTxsFromBlockBerry,
63
+ initBlockchain: () => initBlockchain,
64
+ loadIndexedMerkleMap: () => loadIndexedMerkleMap,
65
+ makeString: () => makeString,
66
+ networks: () => networks,
67
+ parseIndexedMapSerialized: () => parseIndexedMapSerialized,
68
+ parseTransactionPayloads: () => parseTransactionPayloads,
69
+ pinJSON: () => pinJSON,
70
+ saveIndexedMerkleMap: () => saveIndexedMerkleMap,
71
+ sendTx: () => sendTx,
72
+ serializeFields: () => serializeFields,
73
+ serializeIndexedMap: () => serializeIndexedMap,
74
+ serializeTransaction: () => serializeTransaction,
75
+ sleep: () => sleep,
76
+ toBase: () => toBase,
77
+ tokenBalance: () => tokenBalance,
78
+ transactionParams: () => transactionParams,
79
+ txStatusBlockberry: () => txStatusBlockberry
80
+ });
81
+ module.exports = __toCommonJS(index_exports);
82
+
83
+ // dist/node/utils/base64-field.js
84
+ var import_o1js = require("o1js");
85
+
86
+ // dist/node/utils/base64.js
87
+ var TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
88
+ function bigintToBase56(value) {
89
+ const digits = toBase(value, 56n);
90
+ const str = digits.map((x) => TABLE[Number(x)]).join("");
91
+ return str;
92
+ }
93
+ function bigintFromBase56(str) {
94
+ const base56Digits = str.split("").map((x2) => BigInt(TABLE.indexOf(x2)));
95
+ const x = fromBase(base56Digits, 56n);
96
+ return x;
97
+ }
98
+ function bigintToBase64(value) {
99
+ const digits = toBase(value, 64n);
100
+ const str = digits.map((x) => TABLE[Number(x)]).join("");
101
+ return str;
102
+ }
103
+ function bigintFromBase64(str) {
104
+ const base64Digits = str.split("").map((x2) => BigInt(TABLE.indexOf(x2)));
105
+ const x = fromBase(base64Digits, 64n);
106
+ return x;
107
+ }
108
+ function fromBase(digits, base) {
109
+ if (base <= 0n)
110
+ throw Error("fromBase: base must be positive");
111
+ let basePowers = [];
112
+ for (let power = base, n = 1; n < digits.length; power **= 2n, n *= 2) {
113
+ basePowers.push(power);
114
+ }
115
+ let k = basePowers.length;
116
+ digits = digits.concat(Array(2 ** k - digits.length).fill(0n));
117
+ for (let i = 0; i < k; i++) {
118
+ let newDigits = Array(digits.length >> 1);
119
+ let basePower = basePowers[i];
120
+ for (let j = 0; j < newDigits.length; j++) {
121
+ newDigits[j] = digits[2 * j] + basePower * digits[2 * j + 1];
122
+ }
123
+ digits = newDigits;
124
+ }
125
+ console.assert(digits.length === 1);
126
+ let [digit] = digits;
127
+ return digit;
128
+ }
129
+ function toBase(x, base) {
130
+ if (base <= 0n)
131
+ throw Error("toBase: base must be positive");
132
+ let basePowers = [];
133
+ for (let power = base; power <= x; power **= 2n) {
134
+ basePowers.push(power);
135
+ }
136
+ let digits = [x];
137
+ let k = basePowers.length;
138
+ for (let i = 0; i < k; i++) {
139
+ let newDigits = Array(2 * digits.length);
140
+ let basePower = basePowers[k - 1 - i];
141
+ for (let j = 0; j < digits.length; j++) {
142
+ let x2 = digits[j];
143
+ let high = x2 / basePower;
144
+ newDigits[2 * j + 1] = high;
145
+ newDigits[2 * j] = x2 - high * basePower;
146
+ }
147
+ digits = newDigits;
148
+ }
149
+ while (digits[digits.length - 1] === 0n) {
150
+ digits.pop();
151
+ }
152
+ return digits;
153
+ }
154
+
155
+ // dist/node/utils/base64-field.js
156
+ var TABLE2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
157
+ function fieldToBase56(field) {
158
+ const digits = toBase(field.toBigInt(), 56n);
159
+ const str = digits.map((x) => TABLE2[Number(x)]).join("");
160
+ return str;
161
+ }
162
+ function fieldFromBase56(str) {
163
+ const base56Digits = str.split("").map((x2) => BigInt(TABLE2.indexOf(x2)));
164
+ const x = fromBase(base56Digits, 56n);
165
+ return (0, import_o1js.Field)(x);
166
+ }
167
+ function fieldToBase64(field) {
168
+ const digits = toBase(field.toBigInt(), 64n);
169
+ const str = digits.map((x) => TABLE2[Number(x)]).join("");
170
+ return str;
171
+ }
172
+ function fieldFromBase64(str) {
173
+ const base64Digits = str.split("").map((x2) => BigInt(TABLE2.indexOf(x2)));
174
+ const x = fromBase(base64Digits, 64n);
175
+ return (0, import_o1js.Field)(x);
176
+ }
177
+
178
+ // dist/node/utils/fetch.js
179
+ var import_o1js2 = require("o1js");
180
+
181
+ // dist/node/utils/utils.js
182
+ function sleep(ms) {
183
+ return new Promise((resolve) => setTimeout(resolve, ms));
184
+ }
185
+ function makeString(length) {
186
+ let outString = ``;
187
+ const inOptions = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`;
188
+ for (let i = 0; i < length; i++) {
189
+ outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length));
190
+ }
191
+ return outString;
192
+ }
193
+ function formatTime(ms) {
194
+ if (ms === void 0)
195
+ return "";
196
+ if (ms < 1e3)
197
+ return ms.toString() + " ms";
198
+ if (ms < 60 * 1e3)
199
+ return parseInt((ms / 1e3).toString()).toString() + " sec";
200
+ if (ms < 60 * 60 * 1e3) {
201
+ const minutes = parseInt((ms / 1e3 / 60).toString());
202
+ const seconds = parseInt(((ms - minutes * 60 * 1e3) / 1e3).toString());
203
+ return minutes.toString() + " min " + seconds.toString() + " sec";
204
+ } else {
205
+ const hours = parseInt((ms / 1e3 / 60 / 60).toString());
206
+ const minutes = parseInt(((ms - hours * 60 * 60 * 1e3) / 1e3 / 60).toString());
207
+ return hours.toString() + " h " + minutes.toString() + " min";
208
+ }
209
+ }
210
+ var _Memory = class _Memory {
211
+ constructor() {
212
+ _Memory.rss = 0;
213
+ }
214
+ // eslint-disable-next-line @typescript-eslint/no-inferrable-types
215
+ static info(description = ``, fullInfo = false) {
216
+ const memoryData = process.memoryUsage();
217
+ const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024)} MB`;
218
+ const oldRSS = _Memory.rss;
219
+ _Memory.rss = Math.round(memoryData.rss / 1024 / 1024);
220
+ const memoryUsage = fullInfo ? {
221
+ step: `${description}:`,
222
+ rssDelta: `${(oldRSS === 0 ? 0 : _Memory.rss - oldRSS).toString()} MB -> Resident Set Size memory change`,
223
+ rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated`,
224
+ heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
225
+ heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
226
+ external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`
227
+ } : `RSS memory ${description}: ${formatMemoryUsage(memoryData.rss)}${oldRSS === 0 ? `` : `, changed by ` + (_Memory.rss - oldRSS).toString() + ` MB`}`;
228
+ console.log(memoryUsage);
229
+ }
230
+ };
231
+ _Memory.rss = 0;
232
+ var Memory = _Memory;
233
+
234
+ // dist/node/utils/fetch.js
235
+ async function fetchMinaAccount(params) {
236
+ const { publicKey, tokenId, force = false } = params;
237
+ const timeout = 1e3 * 60 * 3;
238
+ let attempt = 0;
239
+ const startTime = Date.now();
240
+ let result = { account: void 0 };
241
+ while (Date.now() - startTime < timeout) {
242
+ try {
243
+ const result2 = await (0, import_o1js2.fetchAccount)({
244
+ publicKey,
245
+ tokenId
246
+ }, void 0, { timeout: 5 * 1e3 });
247
+ return result2;
248
+ } catch (error) {
249
+ if (force === true)
250
+ console.log("Error in fetchMinaAccount:", {
251
+ error,
252
+ publicKey: typeof publicKey === "string" ? publicKey : publicKey.toBase58(),
253
+ tokenId: tokenId?.toString(),
254
+ force
255
+ });
256
+ else {
257
+ console.log("fetchMinaAccount error", {
258
+ error,
259
+ publicKey: typeof publicKey === "string" ? publicKey : publicKey.toBase58(),
260
+ tokenId: tokenId?.toString(),
261
+ force
262
+ });
263
+ return result;
264
+ }
265
+ }
266
+ attempt++;
267
+ await sleep(1e3 * 6 * attempt);
268
+ }
269
+ if (force === true)
270
+ throw new Error(`fetchMinaAccount timeout
271
+ ${{
272
+ publicKey: typeof publicKey === "string" ? publicKey : publicKey.toBase58(),
273
+ tokenId: tokenId?.toString(),
274
+ force
275
+ }}`);
276
+ else
277
+ console.log("fetchMinaAccount timeout", typeof publicKey === "string" ? publicKey : publicKey.toBase58(), tokenId?.toString(), force);
278
+ return result;
279
+ }
280
+ async function fetchMinaActions(publicKey, fromActionState, endActionState) {
281
+ const timeout = 1e3 * 60 * 600;
282
+ const startTime = Date.now();
283
+ while (Date.now() - startTime < timeout) {
284
+ try {
285
+ let actions = await import_o1js2.Mina.fetchActions(publicKey, {
286
+ fromActionState,
287
+ endActionState
288
+ });
289
+ if (Array.isArray(actions))
290
+ return actions;
291
+ else
292
+ console.log("Cannot fetch actions - wrong format");
293
+ } catch (error) {
294
+ console.log("Error in fetchMinaActions", error.toString().substring(0, 300));
295
+ }
296
+ await sleep(1e3 * 60 * 2);
297
+ }
298
+ console.log("Timeout in fetchMinaActions");
299
+ return void 0;
300
+ }
301
+ async function checkMinaZkappTransaction(hash) {
302
+ try {
303
+ const result = await (0, import_o1js2.checkZkappTransaction)(hash);
304
+ return result;
305
+ } catch (error) {
306
+ console.error("Error in checkZkappTransaction:", error);
307
+ return { success: false };
308
+ }
309
+ }
310
+
311
+ // dist/node/utils/fields.js
312
+ var import_o1js3 = require("o1js");
313
+ function serializeFields(fields) {
314
+ const hash = import_o1js3.Poseidon.hash(fields);
315
+ const value = [(0, import_o1js3.Field)(fields.length), hash, ...fields];
316
+ return value.map((f) => fieldToBase64(f)).join(".");
317
+ }
318
+ function deserializeFields(s) {
319
+ try {
320
+ const value = s.split(".").map((n) => fieldFromBase64(n));
321
+ const length = value[0];
322
+ if ((0, import_o1js3.Field)(value.length - 2).equals(length).toBoolean() === false)
323
+ throw new Error("deserializeFields: invalid length");
324
+ const hash = import_o1js3.Poseidon.hash(value.slice(2));
325
+ if (hash.equals(value[1]).toBoolean()) {
326
+ return value.slice(2);
327
+ } else
328
+ throw new Error("deserializeFields: invalid hash: data mismatch");
329
+ } catch (e) {
330
+ throw new Error(`deserializeFields: invalid string: ${s}: ${e}`);
331
+ }
332
+ }
333
+
334
+ // dist/node/utils/fee.js
335
+ var import_o1js4 = require("o1js");
336
+
337
+ // dist/node/config.js
338
+ var config = {
339
+ MINAFEE: "200000000"
340
+ };
341
+ var config_default = config;
342
+
343
+ // dist/node/utils/fee.js
344
+ async function fee() {
345
+ return import_o1js4.UInt64.fromJSON(config_default.MINAFEE);
346
+ }
347
+
348
+ // dist/node/utils/mina.js
349
+ var import_o1js5 = require("o1js");
350
+
351
+ // dist/node/networks.js
352
+ var Mainnet = {
353
+ mina: [
354
+ //"https://proxy.devnet.minaexplorer.com/graphql",
355
+ "https://api.minascan.io/node/mainnet/v1/graphql"
356
+ ],
357
+ archive: [
358
+ "https://api.minascan.io/archive/mainnet/v1/graphql"
359
+ //"https://archive.devnet.minaexplorer.com",
360
+ ],
361
+ explorerAccountUrl: "https://minascan.io/mainnet/account/",
362
+ explorerTransactionUrl: "https://minascan.io/mainnet/tx/",
363
+ chainId: "mainnet",
364
+ name: "Mainnet"
365
+ };
366
+ var Local = {
367
+ mina: [],
368
+ archive: [],
369
+ chainId: "local"
370
+ };
371
+ var Devnet = {
372
+ mina: [
373
+ "https://api.minascan.io/node/devnet/v1/graphql"
374
+ //"https://proxy.devnet.minaexplorer.com/graphql",
375
+ ],
376
+ archive: [
377
+ "https://api.minascan.io/archive/devnet/v1/graphql"
378
+ //"https://archive.devnet.minaexplorer.com",
379
+ ],
380
+ explorerAccountUrl: "https://minascan.io/devnet/account/",
381
+ explorerTransactionUrl: "https://minascan.io/devnet/tx/",
382
+ chainId: "devnet",
383
+ name: "Devnet",
384
+ faucet: "https://faucet.minaprotocol.com"
385
+ };
386
+ var Zeko = {
387
+ mina: ["https://devnet.zeko.io/graphql"],
388
+ archive: ["https://devnet.zeko.io/graphql"],
389
+ explorerAccountUrl: "https://zekoscan.io/devnet/account/",
390
+ explorerTransactionUrl: "https://zekoscan.io/devnet/tx/",
391
+ chainId: "zeko",
392
+ name: "Zeko",
393
+ faucet: "https://zeko.io/faucet"
394
+ };
395
+ var Lightnet = {
396
+ mina: ["http://localhost:8080/graphql"],
397
+ archive: ["http://localhost:8282"],
398
+ accountManager: "http://localhost:8181",
399
+ chainId: "lightnet",
400
+ name: "Lightnet"
401
+ };
402
+ var networks = [Mainnet, Local, Devnet, Zeko, Lightnet];
403
+
404
+ // dist/node/utils/mina.js
405
+ var currentNetwork = void 0;
406
+ function getNetworkIdHash() {
407
+ if (currentNetwork === void 0) {
408
+ throw new Error("Network is not initialized");
409
+ }
410
+ return currentNetwork.networkIdHash;
411
+ }
412
+ function getCurrentNetwork() {
413
+ if (currentNetwork === void 0) {
414
+ throw new Error("Network is not initialized");
415
+ }
416
+ return currentNetwork;
417
+ }
418
+ function getDeployer() {
419
+ if (currentNetwork === void 0) {
420
+ throw new Error("Network is not initialized");
421
+ }
422
+ if (currentNetwork.keys.length < 1)
423
+ return void 0;
424
+ return currentNetwork.keys[0];
425
+ }
426
+ async function initBlockchain(instance, deployersNumber = 0, proofsEnabled = true) {
427
+ if (currentNetwork !== void 0) {
428
+ if (currentNetwork?.network.chainId === instance) {
429
+ return currentNetwork;
430
+ } else {
431
+ throw new Error(`Network is already initialized to different chain ${currentNetwork.network.chainId}, cannot initialize to ${instance}`);
432
+ }
433
+ }
434
+ const networkIdHash = import_o1js5.CircuitString.fromString(instance).hash();
435
+ if (instance === "local") {
436
+ const local = await import_o1js5.Mina.LocalBlockchain({
437
+ proofsEnabled
438
+ });
439
+ import_o1js5.Mina.setActiveInstance(local);
440
+ if (deployersNumber > local.testAccounts.length)
441
+ throw new Error("Not enough test accounts");
442
+ currentNetwork = {
443
+ keys: local.testAccounts,
444
+ network: Local,
445
+ networkIdHash
446
+ };
447
+ return currentNetwork;
448
+ }
449
+ const network = networks.find((n) => n.chainId === instance);
450
+ if (network === void 0) {
451
+ throw new Error("Unknown network");
452
+ }
453
+ const networkInstance = import_o1js5.Mina.Network({
454
+ mina: network.mina,
455
+ archive: network.archive,
456
+ lightnetAccountManager: network.accountManager,
457
+ networkId: instance === "mainnet" ? "mainnet" : "testnet"
458
+ });
459
+ import_o1js5.Mina.setActiveInstance(networkInstance);
460
+ const keys = [];
461
+ if (deployersNumber > 0) {
462
+ if (instance === "lightnet") {
463
+ for (let i = 0; i < deployersNumber; i++) {
464
+ const keyPair = await import_o1js5.Lightnet.acquireKeyPair();
465
+ const key = import_o1js5.Mina.TestPublicKey(keyPair.privateKey);
466
+ keys.push(key);
467
+ }
468
+ } else {
469
+ const deployers = process.env.DEPLOYERS;
470
+ if (deployers === void 0 || Array.isArray(deployers) === false || deployers.length < deployersNumber)
471
+ throw new Error("Deployers are not set");
472
+ for (let i = 0; i < deployersNumber; i++) {
473
+ const privateKey = import_o1js5.PrivateKey.fromBase58(deployers[i]);
474
+ const key = import_o1js5.Mina.TestPublicKey(privateKey);
475
+ keys.push(key);
476
+ }
477
+ }
478
+ }
479
+ currentNetwork = {
480
+ keys,
481
+ network,
482
+ networkIdHash
483
+ };
484
+ return currentNetwork;
485
+ }
486
+ async function accountBalance(address) {
487
+ await (0, import_o1js5.fetchAccount)({ publicKey: address });
488
+ if (import_o1js5.Mina.hasAccount(address))
489
+ return import_o1js5.Mina.getBalance(address);
490
+ else
491
+ return import_o1js5.UInt64.from(0);
492
+ }
493
+ async function accountBalanceMina(address) {
494
+ return Number((await accountBalance(address)).toBigInt()) / 1e9;
495
+ }
496
+
497
+ // dist/node/utils/indexed-map.js
498
+ var import_o1js6 = require("o1js");
499
+
500
+ // dist/node/storage/pinata.js
501
+ async function pinJSON(params) {
502
+ const { data, name = "data.json", keyvalues = { library: "zkcloudworker" } } = params;
503
+ const auth = params.auth ?? process.env.PINATA_JWT ?? process.env.NEXT_PUBLIC_PINATA_JWT ?? process.env.REACT_APP_PINATA_JWT;
504
+ if (!auth)
505
+ throw new Error("pinJSON: auth, PINATA_JWT, NEXT_PUBLIC_PINATA_JWT or REACT_APP_PINATA_JWT should be defined");
506
+ try {
507
+ const pinataData = {
508
+ pinataOptions: {
509
+ cidVersion: 1
510
+ },
511
+ pinataMetadata: {
512
+ name,
513
+ keyvalues
514
+ },
515
+ pinataContent: data
516
+ };
517
+ const res = await fetch("https://api.pinata.cloud/pinning/pinJSONToIPFS", {
518
+ method: "POST",
519
+ headers: {
520
+ "Content-Type": "application/json",
521
+ Authorization: "Bearer " + auth
522
+ },
523
+ body: JSON.stringify(pinataData)
524
+ });
525
+ if (!res.ok) {
526
+ throw new Error(`Pinata error: status: ${res.status} ${res.statusText}`);
527
+ }
528
+ const responseData = await res.json();
529
+ console.log("saveToIPFS result:", responseData);
530
+ return responseData?.IpfsHash;
531
+ } catch (error) {
532
+ console.error("saveToIPFS error:", error?.message);
533
+ return void 0;
534
+ }
535
+ }
536
+
537
+ // dist/node/utils/indexed-map.js
538
+ var { IndexedMerkleMap } = import_o1js6.Experimental;
539
+ async function loadIndexedMerkleMap(params) {
540
+ const { url, type, timeout = 6e4, attempts = 5 } = params;
541
+ let attempt = 0;
542
+ const start = Date.now();
543
+ let response = await fetch(url);
544
+ while (!response.ok && attempt < attempts && Date.now() - start < timeout) {
545
+ attempt++;
546
+ await sleep(5e3 * attempt);
547
+ response = await fetch(url);
548
+ }
549
+ if (!response.ok) {
550
+ throw new Error("Failed to fetch IndexedMerkleMap");
551
+ }
552
+ const json = await response.json();
553
+ const serializedIndexedMap = json.map;
554
+ if (!serializedIndexedMap)
555
+ throw new Error("wrong IndexedMerkleMap json format");
556
+ const map = deserializeIndexedMerkleMapInternal({
557
+ serializedIndexedMap,
558
+ type
559
+ });
560
+ if (!map) {
561
+ throw new Error("Failed to deserialize whitelist");
562
+ }
563
+ return map;
564
+ }
565
+ async function saveIndexedMerkleMap(params) {
566
+ const { map, name = "indexed-map", keyvalues, auth } = params;
567
+ const serialized = serializeIndexedMap(map);
568
+ const ipfsHash = await pinJSON({
569
+ data: { map: serialized },
570
+ name,
571
+ keyvalues,
572
+ auth
573
+ });
574
+ return ipfsHash;
575
+ }
576
+ function serializeIndexedMap(map) {
577
+ return {
578
+ height: map.height,
579
+ root: map.root.toJSON(),
580
+ length: map.length.toJSON(),
581
+ nodes: JSON.stringify(map.data.get().nodes, (_, v) => typeof v === "bigint" ? "n" + bigintToBase64(v) : v),
582
+ sortedLeaves: JSON.stringify(map.data.get().sortedLeaves.map((v) => [
583
+ bigintToBase64(v.key),
584
+ bigintToBase64(v.nextKey),
585
+ bigintToBase64(v.value),
586
+ bigintToBase64(BigInt(v.index))
587
+ ]))
588
+ };
589
+ }
590
+ function deserializeIndexedMerkleMap(params) {
591
+ try {
592
+ const { serializedIndexedMap, type } = params;
593
+ return deserializeIndexedMerkleMapInternal({
594
+ serializedIndexedMap,
595
+ type: type ?? IndexedMerkleMap(serializedIndexedMap.height)
596
+ });
597
+ } catch (error) {
598
+ console.error("Error deserializing map:", error?.message ?? error);
599
+ return void 0;
600
+ }
601
+ }
602
+ function parseIndexedMapSerialized(serializedMap) {
603
+ const json = JSON.parse(serializedMap);
604
+ if (json.height === void 0 || json.root === void 0 || json.length === void 0 || json.nodes === void 0 || json.sortedLeaves === void 0)
605
+ throw new Error("wrong IndexedMerkleMap json format");
606
+ if (typeof json.height !== "number")
607
+ throw new Error("wrong IndexedMerkleMap height format");
608
+ if (typeof json.root !== "string")
609
+ throw new Error("wrong IndexedMerkleMap root format");
610
+ if (typeof json.length !== "string")
611
+ throw new Error("wrong IndexedMerkleMap length format");
612
+ if (typeof json.nodes !== "string")
613
+ throw new Error("wrong IndexedMerkleMap nodes format");
614
+ if (typeof json.sortedLeaves !== "string")
615
+ throw new Error("wrong IndexedMerkleMap sortedLeaves format");
616
+ return json;
617
+ }
618
+ function deserializeIndexedMerkleMapInternal(params) {
619
+ const { serializedIndexedMap, type } = params;
620
+ const map = new type();
621
+ if (serializedIndexedMap.height !== map.height) {
622
+ throw new Error("wrong IndexedMap height");
623
+ }
624
+ const nodes = JSON.parse(serializedIndexedMap.nodes, (_, v) => {
625
+ if (typeof v === "string" && v[0] === "n") {
626
+ return bigintFromBase64(v.slice(1));
627
+ }
628
+ return v;
629
+ });
630
+ const sortedLeaves = JSON.parse(serializedIndexedMap.sortedLeaves).map((row) => {
631
+ return {
632
+ key: bigintFromBase64(row[0]),
633
+ nextKey: bigintFromBase64(row[1]),
634
+ value: bigintFromBase64(row[2]),
635
+ index: Number(bigintFromBase64(row[3]))
636
+ };
637
+ });
638
+ map.root = import_o1js6.Field.fromJSON(serializedIndexedMap.root);
639
+ map.length = import_o1js6.Field.fromJSON(serializedIndexedMap.length);
640
+ map.data.updateAsProver(() => {
641
+ return {
642
+ nodes: nodes.map((row) => [...row]),
643
+ sortedLeaves: [...sortedLeaves]
644
+ };
645
+ });
646
+ return map;
647
+ }
648
+
649
+ // dist/node/storage/ipfs.js
650
+ function createIpfsURL(params) {
651
+ let { hash, gateway, apiToken } = params;
652
+ gateway ??= process.env.PINATA_IPFS_GATEWAY ?? process.env.NEXT_PUBLIC_PINATA_IPFS_GATEWAY ?? process.env.REACT_APP_PINATA_IPFS_GATEWAY;
653
+ apiToken ??= process.env.PINATA_GATEWAY_TOKEN ?? process.env.NEXT_PUBLIC_PINATA_GATEWAY_TOKEN ?? process.env.REACT_APP_PINATA_GATEWAY_TOKEN;
654
+ if (!gateway) {
655
+ gateway = "https://gateway.pinata.cloud/ipfs/";
656
+ }
657
+ return gateway + hash + (apiToken ? "?pinataGatewayToken=" + apiToken : "");
658
+ }
659
+
660
+ // dist/node/transactions/blockberry.js
661
+ async function getZkAppTxsFromBlockBerry(params) {
662
+ const { account, chain, blockBerryApiKey } = params;
663
+ const options = {
664
+ method: "GET",
665
+ headers: {
666
+ accept: "application/json",
667
+ "x-api-key": blockBerryApiKey
668
+ }
669
+ };
670
+ try {
671
+ const controller = new AbortController();
672
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
673
+ const response = await fetch(`https://api.blockberry.one/mina-${chain}/v1/zkapps/accounts/${account}/txs?size=10&orderBy=DESC&sortBy=AGE`, {
674
+ ...options,
675
+ signal: controller.signal
676
+ });
677
+ clearTimeout(timeoutId);
678
+ if (!response.ok) {
679
+ console.error("Cannot fetch zkApp txs for account:", account, chain, response.statusText);
680
+ return void 0;
681
+ }
682
+ const result = await response.json();
683
+ return result;
684
+ } catch (err) {
685
+ console.error("Cannot fetch zkApp txs for account - catch:", account, chain, err);
686
+ return void 0;
687
+ }
688
+ }
689
+ async function getPaymentTxsFromBlockBerry(params) {
690
+ const { account, chain, blockBerryApiKey } = params;
691
+ const options = {
692
+ method: "GET",
693
+ headers: {
694
+ accept: "application/json",
695
+ "x-api-key": blockBerryApiKey
696
+ }
697
+ };
698
+ try {
699
+ const controller = new AbortController();
700
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
701
+ const response = await fetch(`https://api.blockberry.one/mina-${chain}/v1/accounts/` + account + "/txs?page=0&size=1&orderBy=DESC&sortBy=AGE&direction=OUT", {
702
+ ...options,
703
+ signal: controller.signal
704
+ });
705
+ clearTimeout(timeoutId);
706
+ if (!response.ok) {
707
+ console.error("Cannot fetch payment txs for account:", account, chain, response.statusText);
708
+ return void 0;
709
+ }
710
+ const result = await response.json();
711
+ return result;
712
+ } catch (err) {
713
+ console.error("Cannot fetch payment txs for account - catch:", account, chain, err);
714
+ return void 0;
715
+ }
716
+ }
717
+ async function getZkAppTxFromBlockBerry(params) {
718
+ const { hash, chain, blockBerryApiKey } = params;
719
+ const options = {
720
+ method: "GET",
721
+ headers: {
722
+ accept: "application/json",
723
+ "x-api-key": blockBerryApiKey
724
+ }
725
+ };
726
+ try {
727
+ const controller = new AbortController();
728
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
729
+ const response = await fetch(`https://api.blockberry.one/mina-${chain}/v1/zkapps/txs/${hash}`, {
730
+ ...options,
731
+ signal: controller.signal
732
+ });
733
+ clearTimeout(timeoutId);
734
+ if (response.ok) {
735
+ const result = await response.json();
736
+ return result;
737
+ } else {
738
+ console.error("getZkAppTxFromBlockBerry error while getting hash - not ok", { hash, chain, text: response.statusText, status: response.status });
739
+ return void 0;
740
+ }
741
+ } catch (err) {
742
+ console.error("getZkAppTxFromBlockBerry error while getting mainnet hash - catch", hash, chain, err);
743
+ return void 0;
744
+ }
745
+ }
746
+ async function getZkAppFromBlockBerry(params) {
747
+ const { account, chain, blockBerryApiKey } = params;
748
+ const options = {
749
+ method: "GET",
750
+ headers: {
751
+ accept: "application/json",
752
+ "x-api-key": blockBerryApiKey
753
+ }
754
+ };
755
+ try {
756
+ const controller = new AbortController();
757
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
758
+ const response = await fetch(`https://api.blockberry.one/mina-${chain}/v1/zkapps/${account}`, {
759
+ ...options,
760
+ signal: controller.signal
761
+ });
762
+ clearTimeout(timeoutId);
763
+ if (response.ok) {
764
+ const result = await response.json();
765
+ return result;
766
+ } else {
767
+ console.error("getZkAppFromBlockBerry error while getting account", {
768
+ account,
769
+ chain,
770
+ text: response.statusText,
771
+ status: response.status
772
+ });
773
+ return void 0;
774
+ }
775
+ } catch (err) {
776
+ console.error("getZkAppFromBlockBerry error while getting account - catch", account, chain, err);
777
+ return void 0;
778
+ }
779
+ }
780
+
781
+ // dist/node/transactions/nonce.js
782
+ var import_o1js7 = require("o1js");
783
+ async function getNonce(params) {
784
+ const { account, chain, blockBerryApiKey } = params;
785
+ try {
786
+ if (account === void 0 || account === null || account === "") {
787
+ return {
788
+ success: false,
789
+ nonce: -1,
790
+ message: "Account is required"
791
+ };
792
+ }
793
+ if (blockBerryApiKey === void 0 || blockBerryApiKey === null || blockBerryApiKey === "") {
794
+ return {
795
+ success: false,
796
+ nonce: -1,
797
+ message: "blockBerryApiKey is required"
798
+ };
799
+ }
800
+ const zkAppTxsPromise = getZkAppTxsFromBlockBerry({
801
+ account,
802
+ chain,
803
+ blockBerryApiKey
804
+ });
805
+ const paymentTxs = getPaymentTxsFromBlockBerry({
806
+ account,
807
+ chain,
808
+ blockBerryApiKey
809
+ });
810
+ const paymentNonce = (await paymentTxs)?.data[0]?.nonce ?? -1;
811
+ let zkNonce = -1;
812
+ let found = false;
813
+ const zkAppTxs = await zkAppTxsPromise;
814
+ const size = zkAppTxs?.data?.length ?? 0;
815
+ let i = 0;
816
+ while (!found && i < size) {
817
+ if (zkAppTxs?.data[i]?.proverAddress === account) {
818
+ zkNonce = zkAppTxs?.data[i]?.nonce;
819
+ found = true;
820
+ }
821
+ i++;
822
+ }
823
+ const nonce = Math.max(zkNonce, paymentNonce);
824
+ return {
825
+ success: true,
826
+ nonce
827
+ };
828
+ } catch (error) {
829
+ return {
830
+ success: false,
831
+ nonce: -1,
832
+ message: String(error)
833
+ };
834
+ }
835
+ }
836
+ async function getAccountNonce(params) {
837
+ const { account, chain = getCurrentNetwork().network.chainId, blockBerryApiKey, verbose = true } = params;
838
+ const canUseBlockBerry = blockBerryApiKey !== void 0 && (chain === "devnet" || chain === "mainnet");
839
+ if (chain === "zeko") {
840
+ const publicKey = import_o1js7.PublicKey.fromBase58(account);
841
+ await fetchMinaAccount({ publicKey });
842
+ const nonce = Number(import_o1js7.Mina.getAccount(publicKey).nonce.toBigint());
843
+ return nonce;
844
+ } else {
845
+ const blockberryNoncePromise = canUseBlockBerry ? getNonce({
846
+ account,
847
+ blockBerryApiKey,
848
+ chain
849
+ }) : void 0;
850
+ const publicKey = import_o1js7.PublicKey.fromBase58(account);
851
+ await fetchMinaAccount({ publicKey });
852
+ const senderNonce = Number(import_o1js7.Mina.getAccount(publicKey).nonce.toBigint());
853
+ const blockberryNonce = blockberryNoncePromise ? (await blockberryNoncePromise).nonce ?? -1 : -1;
854
+ const nonce = Math.max(senderNonce, blockberryNonce + 1);
855
+ if (verbose && nonce > senderNonce)
856
+ console.log(`Nonce changed from ${senderNonce} to ${nonce} for ${account}`);
857
+ return nonce;
858
+ }
859
+ }
860
+
861
+ // dist/node/transactions/transaction.js
862
+ var import_o1js8 = require("o1js");
863
+ function createTransactionPayloads(tx) {
864
+ const transaction = tx.toJSON();
865
+ const txJSON = JSON.parse(transaction);
866
+ const signedData = JSON.stringify({ zkappCommand: txJSON });
867
+ const proverPayload = serializeTransaction(tx);
868
+ const fee2 = tx.transaction.feePayer.body.fee.toJSON();
869
+ const sender = tx.transaction.feePayer.body.publicKey.toBase58();
870
+ const nonce = Number(tx.transaction.feePayer.body.nonce.toBigint());
871
+ const memo = tx.transaction.memo;
872
+ const minaSignerPayload = {
873
+ zkappCommand: txJSON,
874
+ feePayer: {
875
+ feePayer: sender,
876
+ fee: fee2,
877
+ nonce,
878
+ memo
879
+ }
880
+ };
881
+ const walletPayload = {
882
+ transaction,
883
+ nonce,
884
+ onlySign: true,
885
+ feePayer: {
886
+ fee: fee2,
887
+ memo
888
+ }
889
+ };
890
+ return {
891
+ sender,
892
+ nonce,
893
+ memo,
894
+ fee: fee2,
895
+ walletPayload,
896
+ minaSignerPayload,
897
+ proverPayload,
898
+ signedData,
899
+ transaction
900
+ };
901
+ }
902
+ function transactionParams(params) {
903
+ const { proverPayload, signedData } = params;
904
+ const signedJson = JSON.parse(signedData);
905
+ const { sender, tx } = JSON.parse(proverPayload);
906
+ const transaction = import_o1js8.Mina.Transaction.fromJSON(JSON.parse(tx));
907
+ const memo = transaction.transaction.memo;
908
+ return {
909
+ fee: import_o1js8.UInt64.from(signedJson.zkappCommand.feePayer.body.fee),
910
+ sender: import_o1js8.PublicKey.fromBase58(sender),
911
+ nonce: Number(signedJson.zkappCommand.feePayer.body.nonce),
912
+ memo
913
+ };
914
+ }
915
+ function parseTransactionPayloads(params) {
916
+ const { txNew } = params;
917
+ const proverPayload = "payloads" in params ? params.payloads.proverPayload : params.proverPayload;
918
+ const signedData = "payloads" in params ? params.payloads.signedData : params.signedData;
919
+ const signedJson = JSON.parse(signedData);
920
+ const { tx, blindingValues, length, forestJSONs } = JSON.parse(proverPayload);
921
+ const transaction = import_o1js8.Mina.Transaction.fromJSON(JSON.parse(tx));
922
+ const forests = forestJSONs.map((f) => JSON.parse(f));
923
+ if (length !== txNew.transaction.accountUpdates.length) {
924
+ throw new Error(`New Transaction length mismatch: ${length} !== ${txNew.transaction.accountUpdates.length}`);
925
+ }
926
+ if (length !== transaction.transaction.accountUpdates.length) {
927
+ throw new Error(`Serialized Transaction length mismatch: ${length} !== ${transaction.transaction.accountUpdates.length}`);
928
+ }
929
+ for (let i = 0; i < length; i++) {
930
+ transaction.transaction.accountUpdates[i].lazyAuthorization = txNew.transaction.accountUpdates[i].lazyAuthorization;
931
+ if (blindingValues[i] !== "") {
932
+ if (transaction.transaction.accountUpdates[i].lazyAuthorization === void 0 || transaction.transaction.accountUpdates[i].lazyAuthorization.blindingValue === void 0) {
933
+ throw new Error(`Lazy authorization blinding value is undefined for item ${i}`);
934
+ }
935
+ transaction.transaction.accountUpdates[i].lazyAuthorization.blindingValue = import_o1js8.Field.fromJSON(blindingValues[i]);
936
+ }
937
+ if (forests[i].length > 0) {
938
+ if (transaction.transaction.accountUpdates[i].lazyAuthorization === void 0 || transaction.transaction.accountUpdates[i].lazyAuthorization.args === void 0) {
939
+ throw new Error(`Lazy authorization args is undefined for item ${i}`);
940
+ }
941
+ deserializeLazyAuthorization(transaction.transaction.accountUpdates[i].lazyAuthorization.args, forests[i]);
942
+ if (forests[i].restoredItems !== forests[i].length) {
943
+ throw new Error(`Forest ${i} not fully restored`);
944
+ }
945
+ }
946
+ }
947
+ transaction.transaction.feePayer.authorization = signedJson.zkappCommand.feePayer.authorization;
948
+ transaction.transaction.feePayer.body.fee = import_o1js8.UInt64.from(signedJson.zkappCommand.feePayer.body.fee);
949
+ for (let i = 0; i < length; i++) {
950
+ const signature = signedJson.zkappCommand.accountUpdates[i].authorization.signature;
951
+ if (signature !== void 0 && signature !== null) {
952
+ transaction.transaction.accountUpdates[i].authorization.signature = signedJson.zkappCommand.accountUpdates[i].authorization.signature;
953
+ }
954
+ }
955
+ return transaction;
956
+ }
957
+ function serializeTransaction(tx) {
958
+ const length = tx.transaction.accountUpdates.length;
959
+ let i;
960
+ const blindingValues = [];
961
+ const forests = [];
962
+ for (i = 0; i < length; i++) {
963
+ const la = tx.transaction.accountUpdates[i].lazyAuthorization;
964
+ if (la !== void 0 && la.blindingValue !== void 0 && la.kind === "lazy-proof")
965
+ blindingValues.push(la.blindingValue.toJSON());
966
+ else
967
+ blindingValues.push("");
968
+ const forest = { length: 0, items: [] };
969
+ serializeLazyAuthorization(tx.transaction.accountUpdates[i].lazyAuthorization?.args, forest);
970
+ forests.push(forest);
971
+ }
972
+ const serializedTransaction = JSON.stringify({
973
+ tx: tx.toJSON(),
974
+ blindingValues,
975
+ forestJSONs: forests.map((f) => JSON.stringify(f)),
976
+ length,
977
+ fee: tx.transaction.feePayer.body.fee.toJSON(),
978
+ sender: tx.transaction.feePayer.body.publicKey.toBase58(),
979
+ nonce: tx.transaction.feePayer.body.nonce.toBigint().toString()
980
+ }, null, 2);
981
+ return serializedTransaction;
982
+ }
983
+ function serializeLazyAuthorization(lazyAuthorization, serialized) {
984
+ if (lazyAuthorization?.hash !== void 0 && lazyAuthorization.hash.toJSON) {
985
+ serialized.items.push({
986
+ h: fieldToBase64(lazyAuthorization.hash)
987
+ });
988
+ }
989
+ if (lazyAuthorization?.previousHash !== void 0 && lazyAuthorization.previousHash.toJSON) {
990
+ serialized.items.push({
991
+ p: fieldToBase64(lazyAuthorization.previousHash)
992
+ });
993
+ }
994
+ if (lazyAuthorization?.callData !== void 0 && lazyAuthorization.callData.toJSON) {
995
+ serialized.items.push({
996
+ c: fieldToBase64(lazyAuthorization.callData)
997
+ });
998
+ }
999
+ if (lazyAuthorization?.id !== void 0) {
1000
+ serialized.items.push({
1001
+ i: lazyAuthorization.id
1002
+ });
1003
+ }
1004
+ if (Array.isArray(lazyAuthorization)) {
1005
+ for (const item of lazyAuthorization) {
1006
+ serializeLazyAuthorization(item, serialized);
1007
+ }
1008
+ }
1009
+ if (typeof lazyAuthorization === "object") {
1010
+ for (const key in lazyAuthorization) {
1011
+ serializeLazyAuthorization(lazyAuthorization[key], serialized);
1012
+ }
1013
+ }
1014
+ serialized.length = serialized.items.length;
1015
+ }
1016
+ function deserializeLazyAuthorization(lazyAuthorization, serialized) {
1017
+ if (serialized.restoredItems === void 0)
1018
+ serialized.restoredItems = 0;
1019
+ if (lazyAuthorization?.hash !== void 0 && lazyAuthorization.hash.toJSON) {
1020
+ if (serialized.restoredItems >= serialized.length)
1021
+ throw new Error("Restored more items than expected");
1022
+ const hash = serialized.items[serialized.restoredItems].h;
1023
+ if (hash === void 0)
1024
+ throw new Error(`Hash is undefined for item ${serialized.restoredItems}`);
1025
+ lazyAuthorization.hash = fieldFromBase64(hash);
1026
+ serialized.restoredItems++;
1027
+ }
1028
+ if (lazyAuthorization?.previousHash !== void 0 && lazyAuthorization.previousHash.toJSON) {
1029
+ if (serialized.restoredItems >= serialized.length)
1030
+ throw new Error("Restored more items than expected");
1031
+ const previousHash = serialized.items[serialized.restoredItems].p;
1032
+ if (previousHash === void 0)
1033
+ throw new Error(`Previous hash is undefined for item ${serialized.restoredItems}`);
1034
+ lazyAuthorization.previousHash = fieldFromBase64(previousHash);
1035
+ serialized.restoredItems++;
1036
+ }
1037
+ if (lazyAuthorization?.callData !== void 0 && lazyAuthorization.callData.toJSON) {
1038
+ if (serialized.restoredItems >= serialized.length)
1039
+ throw new Error("Restored more items than expected");
1040
+ const callData = serialized.items[serialized.restoredItems].c;
1041
+ if (callData === void 0)
1042
+ throw new Error(`Call data is undefined for item ${serialized.restoredItems}`);
1043
+ lazyAuthorization.callData = fieldFromBase64(callData);
1044
+ serialized.restoredItems++;
1045
+ }
1046
+ if (lazyAuthorization?.id !== void 0) {
1047
+ if (serialized.restoredItems >= serialized.length)
1048
+ throw new Error("Restored more items than expected");
1049
+ const id = serialized.items[serialized.restoredItems].i;
1050
+ if (id === void 0)
1051
+ throw new Error(`Id is undefined for item ${serialized.restoredItems}`);
1052
+ lazyAuthorization.id = id;
1053
+ serialized.restoredItems++;
1054
+ }
1055
+ if (Array.isArray(lazyAuthorization)) {
1056
+ for (const item of lazyAuthorization) {
1057
+ deserializeLazyAuthorization(item, serialized);
1058
+ }
1059
+ }
1060
+ if (typeof lazyAuthorization === "object") {
1061
+ for (const key in lazyAuthorization) {
1062
+ deserializeLazyAuthorization(lazyAuthorization[key], serialized);
1063
+ }
1064
+ }
1065
+ }
1066
+
1067
+ // dist/node/transactions/txstatus.js
1068
+ var TIMEOUT = 1e3 * 60 * 21;
1069
+ async function txStatusBlockberry(params) {
1070
+ const { hash, chain, time, blockBerryApiKey } = params;
1071
+ const tx = await getZkAppTxFromBlockBerry({ hash, chain, blockBerryApiKey });
1072
+ if (tx?.txStatus)
1073
+ return tx?.txStatus;
1074
+ if (Date.now() - time > (params.timeout ?? TIMEOUT)) {
1075
+ console.error("txStatus: Timeout while checking tx with blockberry", chain, hash);
1076
+ return "replaced";
1077
+ } else {
1078
+ return "pending";
1079
+ }
1080
+ }
1081
+
1082
+ // dist/node/transactions/tiny-contract.js
1083
+ var import_tslib = require("tslib");
1084
+ var import_o1js9 = require("o1js");
1085
+ var TinyContract = class extends import_o1js9.SmartContract {
1086
+ constructor() {
1087
+ super(...arguments);
1088
+ this.value = (0, import_o1js9.State)();
1089
+ }
1090
+ async setValue(value) {
1091
+ this.value.set(value);
1092
+ }
1093
+ };
1094
+ (0, import_tslib.__decorate)([
1095
+ (0, import_o1js9.state)(import_o1js9.Field),
1096
+ (0, import_tslib.__metadata)("design:type", Object)
1097
+ ], TinyContract.prototype, "value", void 0);
1098
+ (0, import_tslib.__decorate)([
1099
+ import_o1js9.method,
1100
+ (0, import_tslib.__metadata)("design:type", Function),
1101
+ (0, import_tslib.__metadata)("design:paramtypes", [import_o1js9.Field]),
1102
+ (0, import_tslib.__metadata)("design:returntype", Promise)
1103
+ ], TinyContract.prototype, "setValue", null);
1104
+
1105
+ // dist/node/transactions/send.js
1106
+ var import_o1js10 = require("o1js");
1107
+ async function sendTx(params) {
1108
+ const { tx, description = "", verbose = true, wait = true, chain = getCurrentNetwork().network.chainId, delay = chain === "zeko" || chain === "lightnet" ? 5e3 : 6e4, retry = 30 } = params;
1109
+ const accountUpdates = JSON.parse(tx.toJSON()).accountUpdates;
1110
+ const auCount = [];
1111
+ let proofAuthorizationCount = 0;
1112
+ for (const au of accountUpdates) {
1113
+ const { publicKey, tokenId, authorizationKind } = au.body;
1114
+ if (au.authorization.proof) {
1115
+ proofAuthorizationCount++;
1116
+ if (authorizationKind.isProved === false)
1117
+ console.error("Proof authorization exists but isProved is false");
1118
+ } else if (authorizationKind.isProved === true)
1119
+ console.error("isProved is true but no proof authorization");
1120
+ const index = auCount.findIndex((item) => item.publicKey === publicKey && item.tokenId === tokenId);
1121
+ if (index === -1)
1122
+ auCount.push({ publicKey, tokenId, count: 1 });
1123
+ else
1124
+ auCount[index].count++;
1125
+ }
1126
+ if (verbose)
1127
+ console.log(`Account updates for ${description ?? "tx"}: ${auCount.length}, proof authorizations: ${proofAuthorizationCount}`);
1128
+ for (const au of auCount) {
1129
+ if (au.count > 1) {
1130
+ if (verbose)
1131
+ console.log(`DUPLICATE AU ${description ?? ""}: ${au.publicKey} ${au.tokenId !== "wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf" ? "tokenId: " + au.tokenId : ""} count: ${au.count}`);
1132
+ }
1133
+ }
1134
+ try {
1135
+ let txSent;
1136
+ let sent = false;
1137
+ let attempt = 1;
1138
+ while (!sent && attempt <= retry) {
1139
+ txSent = await tx.safeSend();
1140
+ if (txSent.status === "pending") {
1141
+ sent = true;
1142
+ if (verbose)
1143
+ console.log(`${description ?? ""} tx sent: hash: ${txSent.hash} status: ${txSent.status}`);
1144
+ } else if (chain !== "local") {
1145
+ attempt++;
1146
+ console.error(`${description} tx NOT sent: hash: ${txSent?.hash} status: ${txSent?.status}, errors: ${String(txSent.errors ?? "")}`);
1147
+ if (verbose)
1148
+ console.log(`Retrying ${chain} tx, retry:`, attempt);
1149
+ await sleep(1e4 * attempt);
1150
+ } else
1151
+ attempt = retry + 1;
1152
+ }
1153
+ if (txSent === void 0)
1154
+ throw new Error("txSent is undefined");
1155
+ if ((txSent.errors?.length ?? 0) > 0) {
1156
+ console.error(`${description ?? ""} tx error: hash: ${txSent.hash} status: ${txSent.status} errors: ${String(txSent.errors ?? "")}`);
1157
+ }
1158
+ if (txSent.status === "pending" && wait !== false && chain !== "zeko") {
1159
+ if (verbose)
1160
+ console.log(`Waiting for tx inclusion...`);
1161
+ let txIncluded = await txSent.safeWait();
1162
+ if (txIncluded.status !== "included") {
1163
+ console.error(`${description ?? ""} tx NOT included into block: hash: ${txIncluded.hash} status: ${txIncluded.status}, errors: ${String(txIncluded.errors ?? "")}`);
1164
+ }
1165
+ if (chain !== "local") {
1166
+ const { publicKey, nonce } = tx.transaction.feePayer.body;
1167
+ const started = Date.now();
1168
+ while (Date.now() - started < 1e3 * 60 * 10) {
1169
+ const newNonce = (await fetchMinaAccount({
1170
+ publicKey,
1171
+ force: true
1172
+ })).account?.nonce;
1173
+ if (newNonce && Number(newNonce.toBigint()) > Number(nonce.toBigint())) {
1174
+ let txIncluded2 = await txSent.safeWait();
1175
+ if (txIncluded2.status === "included") {
1176
+ if (verbose)
1177
+ console.log(`${description ?? ""} tx included into block: hash: ${txIncluded2.hash} status: ${txIncluded2.status}`);
1178
+ if (delay > 0)
1179
+ await sleep(delay);
1180
+ return txIncluded2;
1181
+ } else if (txIncluded2.status === "rejected") {
1182
+ console.error(`tx rejected: ${chain}: hash: ${txIncluded2.hash} status: ${txIncluded2.status} errors: ${txIncluded2.errors}`);
1183
+ await sleep(3e4);
1184
+ txIncluded2 = await txSent.safeWait();
1185
+ if (txIncluded2.status === "included") {
1186
+ if (verbose)
1187
+ console.log(`${description ?? ""} tx included into block: hash: ${txIncluded2.hash} status: ${txIncluded2.status}`);
1188
+ if (delay > 0)
1189
+ await sleep(delay);
1190
+ return txIncluded2;
1191
+ }
1192
+ console.error(`tx failed: ${chain}: hash: ${txIncluded2.hash} status: ${txIncluded2.status} errors: ${txIncluded2.errors}`);
1193
+ return txIncluded2;
1194
+ }
1195
+ }
1196
+ if (verbose)
1197
+ console.log(`Waiting for ${chain} to update state for ${Math.floor((Date.now() - started) / 1e3)} sec...`);
1198
+ await sleep(3e4);
1199
+ }
1200
+ console.error(`${chain} do not reflect nonce update for tx ${txIncluded.hash} with status ${txIncluded.status}`);
1201
+ }
1202
+ if (verbose)
1203
+ console.log(`${description ?? ""} tx included into block: hash: ${txIncluded.hash} status: ${txIncluded.status}`);
1204
+ return txIncluded;
1205
+ } else
1206
+ return txSent;
1207
+ } catch (error) {
1208
+ if (chain !== "zeko")
1209
+ console.error("Error sending tx", error);
1210
+ }
1211
+ }
1212
+ async function getTxStatusFast(params) {
1213
+ const { hash, chain = getCurrentNetwork().network.chainId } = params;
1214
+ if (chain === "local" || chain === "zeko")
1215
+ return { success: true, result: true };
1216
+ try {
1217
+ const txStatus = await (0, import_o1js10.checkZkappTransaction)(hash);
1218
+ return {
1219
+ success: true,
1220
+ result: txStatus?.success ?? false
1221
+ };
1222
+ } catch (error) {
1223
+ console.error("getTxStatusFast error while getting tx status - catch", hash, error);
1224
+ return { success: false, error: error?.message ?? "Cannot get tx status" };
1225
+ }
1226
+ }
1227
+
1228
+ // dist/node/transactions/account.js
1229
+ var import_o1js11 = require("o1js");
1230
+ async function accountExists(address, tokenId) {
1231
+ try {
1232
+ const publicKey = typeof address === "string" ? import_o1js11.PublicKey.fromBase58(address) : address;
1233
+ await fetchMinaAccount({ publicKey, tokenId, force: false });
1234
+ return import_o1js11.Mina.hasAccount(publicKey, tokenId);
1235
+ } catch (error) {
1236
+ return false;
1237
+ }
1238
+ }
1239
+ async function tokenBalance(address, tokenId) {
1240
+ try {
1241
+ const publicKey = typeof address === "string" ? import_o1js11.PublicKey.fromBase58(address) : address;
1242
+ await fetchMinaAccount({ publicKey, tokenId, force: false });
1243
+ return import_o1js11.Mina.hasAccount(publicKey, tokenId) ? Number(import_o1js11.Mina.getAccount(publicKey, tokenId).balance.toBigInt()) : void 0;
1244
+ } catch (error) {
1245
+ console.error("Cannot fetch account balance", error);
1246
+ return void 0;
1247
+ }
1248
+ }
1249
+ async function checkAddress(address) {
1250
+ if (!address || typeof address !== "string") {
1251
+ console.error("checkAddress params are invalid:", address);
1252
+ return false;
1253
+ }
1254
+ try {
1255
+ const publicKey = import_o1js11.PublicKey.fromBase58(address);
1256
+ if (address !== publicKey.toBase58()) {
1257
+ console.log("checkAddress: address is not valid", address, publicKey.toBase58());
1258
+ return false;
1259
+ }
1260
+ return true;
1261
+ } catch (error) {
1262
+ console.error("checkAddress catch", { address, error });
1263
+ return false;
1264
+ }
1265
+ }
1266
+ // Annotate the CommonJS export names for ESM import in node:
1267
+ 0 && (module.exports = {
1268
+ Devnet,
1269
+ Lightnet,
1270
+ Local,
1271
+ Mainnet,
1272
+ Memory,
1273
+ TinyContract,
1274
+ Zeko,
1275
+ accountBalance,
1276
+ accountBalanceMina,
1277
+ accountExists,
1278
+ bigintFromBase56,
1279
+ bigintFromBase64,
1280
+ bigintToBase56,
1281
+ bigintToBase64,
1282
+ checkAddress,
1283
+ checkMinaZkappTransaction,
1284
+ createIpfsURL,
1285
+ createTransactionPayloads,
1286
+ currentNetwork,
1287
+ deserializeFields,
1288
+ deserializeIndexedMerkleMap,
1289
+ fee,
1290
+ fetchMinaAccount,
1291
+ fetchMinaActions,
1292
+ fieldFromBase56,
1293
+ fieldFromBase64,
1294
+ fieldToBase56,
1295
+ fieldToBase64,
1296
+ formatTime,
1297
+ fromBase,
1298
+ getAccountNonce,
1299
+ getCurrentNetwork,
1300
+ getDeployer,
1301
+ getNetworkIdHash,
1302
+ getNonce,
1303
+ getPaymentTxsFromBlockBerry,
1304
+ getTxStatusFast,
1305
+ getZkAppFromBlockBerry,
1306
+ getZkAppTxFromBlockBerry,
1307
+ getZkAppTxsFromBlockBerry,
1308
+ initBlockchain,
1309
+ loadIndexedMerkleMap,
1310
+ makeString,
1311
+ networks,
1312
+ parseIndexedMapSerialized,
1313
+ parseTransactionPayloads,
1314
+ pinJSON,
1315
+ saveIndexedMerkleMap,
1316
+ sendTx,
1317
+ serializeFields,
1318
+ serializeIndexedMap,
1319
+ serializeTransaction,
1320
+ sleep,
1321
+ toBase,
1322
+ tokenBalance,
1323
+ transactionParams,
1324
+ txStatusBlockberry
1325
+ });