@arkade-os/sdk 0.5.4 → 0.5.5

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 (112) hide show
  1. package/README.md +103 -17
  2. package/dist/adapters/expo.cjs +7 -6
  3. package/dist/adapters/expo.d.cts +4 -3
  4. package/dist/adapters/expo.d.ts +4 -3
  5. package/dist/adapters/expo.js +4 -3
  6. package/dist/{asyncStorageTaskQueue-DTBa8EH7.d.cts → asyncStorageTaskQueue-BbH-THYJ.d.cts} +1 -1
  7. package/dist/{asyncStorageTaskQueue-DHMIxY04.d.ts → asyncStorageTaskQueue-BlvkJyTa.d.ts} +1 -1
  8. package/dist/base-C-Y5t_0F.d.cts +359 -0
  9. package/dist/base-C-Y5t_0F.d.ts +359 -0
  10. package/dist/{chunk-AG4TFD6F.js → chunk-4I53THL6.js} +79 -884
  11. package/dist/chunk-4I53THL6.js.map +1 -0
  12. package/dist/{chunk-B6VNKGIH.cjs → chunk-5SYUEVJH.cjs} +10 -10
  13. package/dist/{chunk-B6VNKGIH.cjs.map → chunk-5SYUEVJH.cjs.map} +1 -1
  14. package/dist/{chunk-BTRCN4JJ.js → chunk-7GIKLFHC.js} +64 -4
  15. package/dist/chunk-7GIKLFHC.js.map +1 -0
  16. package/dist/{chunk-E6OOJEHL.cjs → chunk-AMH7Q3DF.cjs} +60 -934
  17. package/dist/chunk-AMH7Q3DF.cjs.map +1 -0
  18. package/dist/{chunk-6CUP6ZIF.js → chunk-BCA6D255.js} +17 -841
  19. package/dist/chunk-BCA6D255.js.map +1 -0
  20. package/dist/{chunk-TUOLZBNC.js → chunk-CE46RS6L.js} +5 -4
  21. package/dist/chunk-CE46RS6L.js.map +1 -0
  22. package/dist/chunk-DNFTHG73.js +829 -0
  23. package/dist/chunk-DNFTHG73.js.map +1 -0
  24. package/dist/chunk-FDJ734CH.js +882 -0
  25. package/dist/chunk-FDJ734CH.js.map +1 -0
  26. package/dist/chunk-FLPWNMX3.cjs +930 -0
  27. package/dist/chunk-FLPWNMX3.cjs.map +1 -0
  28. package/dist/{chunk-MWVAWFX6.js → chunk-FVVXCDNE.js} +4 -4
  29. package/dist/{chunk-MWVAWFX6.js.map → chunk-FVVXCDNE.js.map} +1 -1
  30. package/dist/{chunk-DNITZVNG.cjs → chunk-HQQ4NRXI.cjs} +18 -17
  31. package/dist/chunk-HQQ4NRXI.cjs.map +1 -0
  32. package/dist/chunk-JFJNB7ZH.cjs +884 -0
  33. package/dist/chunk-JFJNB7ZH.cjs.map +1 -0
  34. package/dist/{chunk-GHUUT54D.cjs → chunk-KCL5AVML.cjs} +89 -933
  35. package/dist/chunk-KCL5AVML.cjs.map +1 -0
  36. package/dist/{chunk-ZJHLLDBP.js → chunk-OO2KEK64.js} +2624 -1277
  37. package/dist/chunk-OO2KEK64.js.map +1 -0
  38. package/dist/{chunk-F3FAE7VJ.cjs → chunk-T254PXSN.cjs} +3115 -1752
  39. package/dist/chunk-T254PXSN.cjs.map +1 -0
  40. package/dist/chunk-V3ZLL5VY.js +380 -0
  41. package/dist/chunk-V3ZLL5VY.js.map +1 -0
  42. package/dist/chunk-X6ZI53DZ.cjs +383 -0
  43. package/dist/chunk-X6ZI53DZ.cjs.map +1 -0
  44. package/dist/{chunk-WXNSISXK.cjs → chunk-XWUCNMPN.cjs} +79 -18
  45. package/dist/chunk-XWUCNMPN.cjs.map +1 -0
  46. package/dist/compiler.cjs +50 -0
  47. package/dist/compiler.cjs.map +1 -0
  48. package/dist/compiler.d.cts +38 -0
  49. package/dist/compiler.d.ts +38 -0
  50. package/dist/compiler.js +47 -0
  51. package/dist/compiler.js.map +1 -0
  52. package/dist/contracts/handlers/index.cjs +11 -9
  53. package/dist/contracts/handlers/index.d.cts +6 -4
  54. package/dist/contracts/handlers/index.d.ts +6 -4
  55. package/dist/contracts/handlers/index.js +4 -2
  56. package/dist/{delegate-xrSBNybC.d.ts → delegate-gGkUnYpi.d.cts} +1 -1
  57. package/dist/{delegate-f4_t864Z.d.cts → delegate-iyDum4fw.d.ts} +1 -1
  58. package/dist/{index-BJDz15ms.d.ts → index-BWwVnJhU.d.cts} +5 -270
  59. package/dist/{index-BjiVGtp8.d.cts → index-Bx-iArDs.d.ts} +5 -270
  60. package/dist/{index-DRwe0UDN.d.ts → index-DCml4QJn.d.ts} +1593 -1711
  61. package/dist/{index-DRwe0UDN.d.cts → index-DkyzIzKL.d.cts} +1593 -1711
  62. package/dist/index.cjs +457 -378
  63. package/dist/index.d.cts +633 -378
  64. package/dist/index.d.ts +633 -378
  65. package/dist/index.js +7 -4
  66. package/dist/{wallet-jVBDQl6R.d.cts → keyringDescriptorProvider-CS4w4PWd.d.ts} +412 -361
  67. package/dist/{wallet-Oc3Wd5gv.d.ts → keyringDescriptorProvider-CmHXrIXd.d.cts} +412 -361
  68. package/dist/program-BARSNg3X.d.ts +286 -0
  69. package/dist/program-znrWkxE4.d.cts +286 -0
  70. package/dist/repositories/realm/index.cjs +71 -51
  71. package/dist/repositories/realm/index.cjs.map +1 -1
  72. package/dist/repositories/realm/index.d.cts +20 -9
  73. package/dist/repositories/realm/index.d.ts +20 -9
  74. package/dist/repositories/realm/index.js +42 -23
  75. package/dist/repositories/realm/index.js.map +1 -1
  76. package/dist/repositories/sqlite/index.cjs +81 -56
  77. package/dist/repositories/sqlite/index.cjs.map +1 -1
  78. package/dist/repositories/sqlite/index.d.cts +17 -8
  79. package/dist/repositories/sqlite/index.d.ts +17 -8
  80. package/dist/repositories/sqlite/index.js +55 -31
  81. package/dist/repositories/sqlite/index.js.map +1 -1
  82. package/dist/{taskRunner-CDlNeth0.d.ts → taskRunner-DgMLSk_O.d.ts} +1 -1
  83. package/dist/{taskRunner-BPPU-YHG.d.cts → taskRunner-buh6aFpG.d.cts} +1 -1
  84. package/dist/wallet/expo/background.cjs +17 -14
  85. package/dist/wallet/expo/background.cjs.map +1 -1
  86. package/dist/wallet/expo/background.d.cts +5 -4
  87. package/dist/wallet/expo/background.d.ts +5 -4
  88. package/dist/wallet/expo/background.js +9 -6
  89. package/dist/wallet/expo/background.js.map +1 -1
  90. package/dist/wallet/expo/index.cjs +29 -16
  91. package/dist/wallet/expo/index.cjs.map +1 -1
  92. package/dist/wallet/expo/index.d.cts +12 -7
  93. package/dist/wallet/expo/index.d.ts +12 -7
  94. package/dist/wallet/expo/index.js +19 -6
  95. package/dist/wallet/expo/index.js.map +1 -1
  96. package/dist/worker/expo/index.cjs +12 -9
  97. package/dist/worker/expo/index.cjs.map +1 -1
  98. package/dist/worker/expo/index.d.cts +6 -5
  99. package/dist/worker/expo/index.d.ts +6 -5
  100. package/dist/worker/expo/index.js +8 -5
  101. package/dist/worker/expo/index.js.map +1 -1
  102. package/package.json +16 -1
  103. package/dist/chunk-6CUP6ZIF.js.map +0 -1
  104. package/dist/chunk-AG4TFD6F.js.map +0 -1
  105. package/dist/chunk-BTRCN4JJ.js.map +0 -1
  106. package/dist/chunk-DNITZVNG.cjs.map +0 -1
  107. package/dist/chunk-E6OOJEHL.cjs.map +0 -1
  108. package/dist/chunk-F3FAE7VJ.cjs.map +0 -1
  109. package/dist/chunk-GHUUT54D.cjs.map +0 -1
  110. package/dist/chunk-TUOLZBNC.js.map +0 -1
  111. package/dist/chunk-WXNSISXK.cjs.map +0 -1
  112. package/dist/chunk-ZJHLLDBP.js.map +0 -1
@@ -0,0 +1,829 @@
1
+ import { __export, sequenceToCanonicalTimelock, VtxoScript, ConditionCSVMultisigTapscript, CSVMultisigTapscript, CLTVMultisigTapscript, ConditionMultisigTapscript, MultisigTapscript } from './chunk-FDJ734CH.js';
2
+ import { hex } from '@scure/base';
3
+ import { ScriptNum, OP } from '@scure/btc-signer';
4
+ import { equalBytes } from '@scure/btc-signer/utils.js';
5
+ import * as P from 'micro-packed';
6
+ import { schnorr, secp256k1 } from '@noble/curves/secp256k1.js';
7
+ import { bytesToNumberBE } from '@noble/curves/utils.js';
8
+
9
+ // src/utils/keys.ts
10
+ function toXOnly(key, label = "public key") {
11
+ if (key.length === 32) return key;
12
+ if (key.length === 33 && (key[0] === 2 || key[0] === 3)) return key.subarray(1);
13
+ throw new Error(`${label} is not a compressed or x-only public key`);
14
+ }
15
+ var ARKADE_OP = {
16
+ // Merkle Branch Verification (0xb3 — repurposed NOP4 slot)
17
+ MERKLEBRANCHVERIFY: 179,
18
+ PUT: 187,
19
+ // Digest (0xc3)
20
+ DIGEST: 195,
21
+ // SHA256 Streaming (0xc4-0xc6)
22
+ SHA256INITIALIZE: 196,
23
+ SHA256UPDATE: 197,
24
+ SHA256FINALIZE: 198,
25
+ // Input Introspection (0xc7-0xcb)
26
+ INSPECTINPUTOUTPOINT: 199,
27
+ INSPECTINPUTARKADESCRIPTHASH: 200,
28
+ INSPECTINPUTVALUE: 201,
29
+ INSPECTINPUTSCRIPTPUBKEY: 202,
30
+ INSPECTINPUTSEQUENCE: 203,
31
+ // Signatures (0xcc-0xcd)
32
+ CHECKSIGFROMSTACK: 204,
33
+ PUSHCURRENTINPUTINDEX: 205,
34
+ // Input Arkade Witness Introspection (0xce)
35
+ INSPECTINPUTARKADEWITNESSHASH: 206,
36
+ // Output Introspection (0xcf, 0xd1)
37
+ INSPECTOUTPUTVALUE: 207,
38
+ INSPECTOUTPUTSCRIPTPUBKEY: 209,
39
+ // Transaction Introspection (0xd2-0xd6)
40
+ INSPECTVERSION: 210,
41
+ INSPECTLOCKTIME: 211,
42
+ INSPECTNUMINPUTS: 212,
43
+ INSPECTNUMOUTPUTS: 213,
44
+ TXWEIGHT: 214,
45
+ // Byte/Number Conversion & Arithmetic (0xd7-0xda)
46
+ NUM2BIN: 215,
47
+ BIN2NUM: 216,
48
+ REVERSEBYTES: 217,
49
+ MODEXP: 218,
50
+ // VTXO Expiry & Emulator Clock (0xdb-0xdc)
51
+ PUSHEXPIRY: 219,
52
+ CHECKTIME: 220,
53
+ // 0xdd-0xdf are unassigned (OP_UNKNOWN221-223)
54
+ // EC Operations (0xe0-0xe2)
55
+ ECADD: 224,
56
+ ECMUL: 225,
57
+ ECPAIRING: 226,
58
+ // EC Operations (0xe3-0xe4)
59
+ ECMULSCALARVERIFY: 227,
60
+ TWEAKVERIFY: 228,
61
+ // Asset Groups (0xe5-0xf2)
62
+ INSPECTNUMASSETGROUPS: 229,
63
+ INSPECTASSETGROUPASSETID: 230,
64
+ INSPECTASSETGROUPCTRL: 231,
65
+ FINDASSETGROUPBYASSETID: 232,
66
+ INSPECTASSETGROUPMETADATAHASH: 233,
67
+ INSPECTASSETGROUPNUM: 234,
68
+ INSPECTASSETGROUP: 235,
69
+ INSPECTASSETGROUPSUM: 236,
70
+ INSPECTOUTASSETCOUNT: 237,
71
+ INSPECTOUTASSETAT: 238,
72
+ INSPECTOUTASSETLOOKUP: 239,
73
+ INSPECTINASSETCOUNT: 240,
74
+ INSPECTINASSETAT: 241,
75
+ INSPECTINASSETLOOKUP: 242,
76
+ // Transaction ID (0xf3)
77
+ TXID: 243,
78
+ // Packet Introspection (0xf4-0xf5) — added in emulator v0.0.1
79
+ INSPECTPACKET: 244,
80
+ INSPECTINPUTPACKET: 245,
81
+ // Signature Hash (0xf6)
82
+ SIGHASH: 246,
83
+ // Continuation & Intent Introspection (0xf7-0xf8)
84
+ TUNNEL: 247,
85
+ INSPECTINTENTMESSAGE: 248
86
+ };
87
+ var ARKADE_OPCODES = Object.values(ARKADE_OP);
88
+ var ARKADE_OPCODE_NAMES = Object.fromEntries(
89
+ Object.entries(ARKADE_OP).map(([name, value]) => [value, name])
90
+ );
91
+ var ARKADE_OPCODE_VALUES = Object.fromEntries(
92
+ Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [name, Number(value)])
93
+ );
94
+ function buildBitcoinOpcodeNames() {
95
+ const names = {};
96
+ for (const [key, value] of Object.entries(OP)) {
97
+ if (typeof value === "number") {
98
+ const name = key.startsWith("OP_") ? key : `OP_${key}`;
99
+ names[value] = name;
100
+ }
101
+ }
102
+ names[0] = "OP_0";
103
+ return names;
104
+ }
105
+ function buildBitcoinOpcodeValues() {
106
+ const values = {};
107
+ for (const [key, value] of Object.entries(OP)) {
108
+ if (typeof value === "number") {
109
+ const name = key.startsWith("OP_") ? key : `OP_${key}`;
110
+ values[name] = value;
111
+ values[key] = value;
112
+ }
113
+ }
114
+ return values;
115
+ }
116
+ var BITCOIN_OPCODE_NAMES = buildBitcoinOpcodeNames();
117
+ var BITCOIN_OPCODE_VALUES = buildBitcoinOpcodeValues();
118
+ var OPCODE_NAMES = {
119
+ ...BITCOIN_OPCODE_NAMES,
120
+ // Add Arkade opcodes with OP_ prefix
121
+ ...Object.fromEntries(
122
+ Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [Number(value), `OP_${name}`])
123
+ )
124
+ };
125
+ var OPCODE_VALUES = {
126
+ ...BITCOIN_OPCODE_VALUES,
127
+ // Add Arkade opcodes with and without OP_ prefix
128
+ ...ARKADE_OPCODE_VALUES,
129
+ ...Object.fromEntries(
130
+ Object.entries(ARKADE_OPCODE_VALUES).map(([name, value]) => [`OP_${name}`, value])
131
+ )
132
+ };
133
+ function getOpcodeName(value) {
134
+ if (value >= 1 && value <= 75) {
135
+ return `OP_DATA_${value}`;
136
+ }
137
+ return OPCODE_NAMES[value];
138
+ }
139
+ function getOpcodeValue(name) {
140
+ const dataMatch = name.match(/^OP_DATA_(\d+)$/);
141
+ if (dataMatch) {
142
+ const n = parseInt(dataMatch[1], 10);
143
+ if (n >= 1 && n <= 75) {
144
+ return n;
145
+ }
146
+ return void 0;
147
+ }
148
+ return OPCODE_VALUES[name];
149
+ }
150
+
151
+ // src/arkade/bignum.ts
152
+ var bignum_exports = {};
153
+ __export(bignum_exports, {
154
+ BIGNUM_MAX_BYTES: () => BIGNUM_MAX_BYTES,
155
+ decode: () => decode,
156
+ encode: () => encode
157
+ });
158
+ var BIGNUM_MAX_BYTES = 520;
159
+ var codec = ScriptNum(
160
+ BIGNUM_MAX_BYTES,
161
+ /* forceMinimal */
162
+ true
163
+ );
164
+ function encode(value) {
165
+ const result = codec.encode(value);
166
+ if (result.length > BIGNUM_MAX_BYTES) {
167
+ throw new Error(`BigNum value exceeds 520 bytes (encoded to ${result.length} bytes)`);
168
+ }
169
+ return result;
170
+ }
171
+ function decode(value) {
172
+ return codec.decode(value);
173
+ }
174
+
175
+ // src/arkade/script.ts
176
+ var ARKADE_OPS = { ...OP, ...ARKADE_OP };
177
+ var ArkadeOPNames = {};
178
+ for (const [k, v] of Object.entries(ARKADE_OPS)) {
179
+ if (typeof v === "number") ArkadeOPNames[v] = k;
180
+ }
181
+ var ArkadeScript = P.wrap({
182
+ encodeStream: (w, value) => {
183
+ for (let o of value) {
184
+ if (typeof o === "string") {
185
+ const v = ARKADE_OPS[o];
186
+ if (v === void 0) throw new Error(`Unknown opcode=${o}`);
187
+ w.byte(v);
188
+ continue;
189
+ } else if (typeof o === "number" || typeof o === "bigint") {
190
+ const big = typeof o === "number" ? BigInt(o) : o;
191
+ o = encode(big);
192
+ }
193
+ if (!(o instanceof Uint8Array)) throw new Error(`Wrong Script OP=${o} (${typeof o})`);
194
+ const len = o.length;
195
+ if (len === 1 && o[0] >= 1 && o[0] <= 16) {
196
+ w.byte(OP.OP_1 - 1 + o[0]);
197
+ continue;
198
+ } else if (len === 1 && o[0] === 129) {
199
+ w.byte(OP["1NEGATE"]);
200
+ continue;
201
+ } else if (len < OP.PUSHDATA1) w.byte(len);
202
+ else if (len <= 255) {
203
+ w.byte(OP.PUSHDATA1);
204
+ w.byte(len);
205
+ } else if (len <= 65535) {
206
+ w.byte(OP.PUSHDATA2);
207
+ w.bytes(P.U16LE.encode(len));
208
+ } else {
209
+ w.byte(OP.PUSHDATA4);
210
+ w.bytes(P.U32LE.encode(len));
211
+ }
212
+ w.bytes(o);
213
+ }
214
+ },
215
+ decodeStream: (r) => {
216
+ const out = [];
217
+ while (!r.isEnd()) {
218
+ const cur = r.byte();
219
+ if (OP.OP_0 < cur && cur <= OP.PUSHDATA4) {
220
+ let len;
221
+ if (cur < OP.PUSHDATA1) len = cur;
222
+ else if (cur === OP.PUSHDATA1) len = P.U8.decodeStream(r);
223
+ else if (cur === OP.PUSHDATA2) len = P.U16LE.decodeStream(r);
224
+ else if (cur === OP.PUSHDATA4) len = P.U32LE.decodeStream(r);
225
+ else throw new Error("Should be not possible");
226
+ out.push(r.bytes(len));
227
+ } else if (cur === 0) {
228
+ out.push(0);
229
+ } else if (OP.OP_1 <= cur && cur <= OP.OP_16) {
230
+ out.push(cur - (OP.OP_1 - 1));
231
+ } else if (cur === OP["1NEGATE"]) {
232
+ out.push(-1);
233
+ } else {
234
+ const op = ArkadeOPNames[cur];
235
+ if (op === void 0) throw new Error(`Unknown opcode=${cur.toString(16)}`);
236
+ out.push(op);
237
+ }
238
+ }
239
+ return out;
240
+ }
241
+ });
242
+ function toASM(script) {
243
+ const parts = [];
244
+ for (const op of script) {
245
+ if (typeof op === "string") {
246
+ const name = op.startsWith("OP_") ? op : `OP_${op}`;
247
+ parts.push(name);
248
+ } else if (typeof op === "number" || typeof op === "bigint") {
249
+ if (op === 0 || op === 0n) {
250
+ parts.push("OP_0");
251
+ } else if (op >= 1 && op <= 16) {
252
+ parts.push(`OP_${op}`);
253
+ } else if (op === -1 || op === -1n) {
254
+ parts.push("OP_1NEGATE");
255
+ } else {
256
+ parts.push(hex.encode(encode(BigInt(op))));
257
+ }
258
+ } else {
259
+ parts.push(hex.encode(op));
260
+ }
261
+ }
262
+ return parts.join(" ");
263
+ }
264
+ function fromASM(asm) {
265
+ const tokens = asm.trim().split(/\s+/).filter(Boolean);
266
+ const out = [];
267
+ for (const token of tokens) {
268
+ if (token === "OP_0" || token === "OP_FALSE") {
269
+ out.push(0);
270
+ continue;
271
+ }
272
+ if (token === "OP_TRUE") {
273
+ out.push(1);
274
+ continue;
275
+ }
276
+ const numMatch = token.match(/^OP_(\d+)$/);
277
+ if (numMatch) {
278
+ const n = parseInt(numMatch[1], 10);
279
+ if (n >= 1 && n <= 16) {
280
+ out.push(n);
281
+ continue;
282
+ }
283
+ }
284
+ let key;
285
+ if (token.startsWith("OP_")) {
286
+ key = token.slice(3);
287
+ } else {
288
+ key = token;
289
+ }
290
+ if (key in ARKADE_OPS) {
291
+ out.push(key);
292
+ continue;
293
+ }
294
+ if (/^[0-9a-fA-F]+$/.test(token) && token.length % 2 === 0) {
295
+ try {
296
+ out.push(hex.decode(token));
297
+ continue;
298
+ } catch {
299
+ }
300
+ }
301
+ throw new Error(`Invalid ASM token: ${token}`);
302
+ }
303
+ return out;
304
+ }
305
+ function asmToBytes(asm) {
306
+ return ArkadeScript.encode(fromASM(asm));
307
+ }
308
+ function bytesToASM(script) {
309
+ return toASM(ArkadeScript.decode(script));
310
+ }
311
+ var TAG_SCRIPT = "ArkScriptHash";
312
+ var TAG_WITNESS = "ArkWitnessHash";
313
+ function arkadeScriptHash(script) {
314
+ return schnorr.utils.taggedHash(TAG_SCRIPT, script);
315
+ }
316
+ function arkadeWitnessHash(witness) {
317
+ if (witness.length === 0) {
318
+ return new Uint8Array(32);
319
+ }
320
+ return schnorr.utils.taggedHash(TAG_WITNESS, witness);
321
+ }
322
+ function computeArkadeScriptPublicKey(pubKey, script) {
323
+ const hash = arkadeScriptHash(script);
324
+ const point = schnorr.utils.lift_x(bytesToNumberBE(toXOnly(pubKey, "emulator key")));
325
+ const scalar = bytesToNumberBE(hash) % secp256k1.Point.CURVE().n;
326
+ const tweak = secp256k1.Point.BASE.multiply(scalar);
327
+ return schnorr.utils.pointToBytes(point.add(tweak));
328
+ }
329
+
330
+ // src/arkade/program.ts
331
+ var MinimalScriptNum = ScriptNum(void 0, true);
332
+ var ARKADE_TYPE_ENCODINGS = {
333
+ pubkey: "raw",
334
+ signature: "schnorr-64",
335
+ bytes: "raw",
336
+ bytes20: "raw-20",
337
+ bytes32: "raw-32",
338
+ asset: "raw-32",
339
+ int: "scriptnum",
340
+ bool: "scriptnum",
341
+ AssetGroup: "scriptnum"
342
+ };
343
+ var SUPPORTED_PROGRAM_VERSION = 1;
344
+ var UnsupportedProgramVersionError = class extends Error {
345
+ constructor(version, context) {
346
+ super(
347
+ `${context}: unsupported program version ${String(version)}; this SDK supports version ${SUPPORTED_PROGRAM_VERSION}. Recover it with an SDK that reads version ${String(version)}, re-create it with current params, or delete it.`
348
+ );
349
+ this.version = version;
350
+ }
351
+ version;
352
+ name = "UnsupportedProgramVersionError";
353
+ };
354
+ function bindValue(bind, name) {
355
+ const v = Object.hasOwn(bind, name) ? bind[name] : void 0;
356
+ if (v === void 0) throw new Error(`unbound parameter '${name}'`);
357
+ return v;
358
+ }
359
+ function resolveTimelockValue(value, args) {
360
+ if (typeof value === "bigint") return value;
361
+ if (value.startsWith("$")) {
362
+ const v = bindValue(args, value.slice(1));
363
+ if (typeof v === "bigint" || typeof v === "number") return BigInt(v);
364
+ throw new Error(`timelock value '${value}' must resolve to a number`);
365
+ }
366
+ throw new Error(
367
+ `invalid timelock value '${value}' \u2014 expected a bigint or a '$param' reference`
368
+ );
369
+ }
370
+ function resolveCsvTimelock(csv, args) {
371
+ const value = resolveTimelockValue(csv.value, args);
372
+ if (csv.type !== "sequence") return { type: csv.type, value };
373
+ const timelock = sequenceToCanonicalTimelock(value);
374
+ if (!timelock) {
375
+ throw new Error(
376
+ `csv '${csv.value}' resolved to ${value}, which is not a canonical BIP68 sequence`
377
+ );
378
+ }
379
+ return timelock;
380
+ }
381
+ function resolveAsm(asm, bind) {
382
+ const tokens = asm.map((t) => {
383
+ if (typeof t === "string" && t.startsWith("$")) {
384
+ return bindValue(bind, t.slice(1));
385
+ }
386
+ if (t === "<SELF>") {
387
+ throw new Error(
388
+ "<SELF> is not a placeholder; use INSPECTINPUTSCRIPTPUBKEY for continuation covenants"
389
+ );
390
+ }
391
+ return t;
392
+ });
393
+ return ArkadeScript.encode(tokens);
394
+ }
395
+ function witnessRefToBytes(ref, callArgs, programArgs) {
396
+ if (ref instanceof Uint8Array) return ref;
397
+ if (typeof ref === "number" || typeof ref === "bigint") {
398
+ return MinimalScriptNum.encode(BigInt(ref));
399
+ }
400
+ const v = ref.startsWith("$") ? bindValue(programArgs, ref.slice(1)) : bindValue(callArgs, ref);
401
+ if (v instanceof Uint8Array) return v;
402
+ return MinimalScriptNum.encode(BigInt(v));
403
+ }
404
+ function staticWitness(refs, programArgs) {
405
+ try {
406
+ return (refs ?? []).map((ref) => witnessRefToBytes(ref, {}, programArgs));
407
+ } catch {
408
+ return null;
409
+ }
410
+ }
411
+ function validateTapscript(seg) {
412
+ if (!seg.signers || seg.signers.length === 0) {
413
+ throw new Error("tapscript: at least one signer is required");
414
+ }
415
+ if (seg.asm !== void 0 && seg.cltv !== void 0) {
416
+ throw new Error(
417
+ "tapscript: `asm` and `cltv` conflict \u2014 arkd has no condition+CLTV closure"
418
+ );
419
+ }
420
+ if (seg.csv !== void 0 && seg.cltv !== void 0) {
421
+ throw new Error("tapscript: `csv` and `cltv` conflict \u2014 use at most one timelock");
422
+ }
423
+ for (const t of seg.asm ?? []) {
424
+ if (typeof t === "string" && t in ARKADE_OP) {
425
+ throw new Error(
426
+ `tapscript: arkade opcode '${t}' is not enforceable on-chain \u2014 move it to arkadeScript`
427
+ );
428
+ }
429
+ }
430
+ }
431
+ function collectParamRefs(program) {
432
+ const refs = /* @__PURE__ */ new Set();
433
+ const collect = (items) => {
434
+ for (const t of items ?? []) {
435
+ if (typeof t === "string" && t.startsWith("$")) refs.add(t.slice(1));
436
+ else if (isTweakedSigner(t) && t.tweak.startsWith("$")) refs.add(t.tweak.slice(1));
437
+ }
438
+ };
439
+ for (const fn of Object.values(program.functions)) {
440
+ const tap = fn.tapscript;
441
+ collect(tap.signers);
442
+ collect(tap.asm);
443
+ collect(tap.witness);
444
+ collect(tap.csv ? [tap.csv.value] : void 0);
445
+ collect(tap.cltv !== void 0 ? [tap.cltv] : void 0);
446
+ collect(fn.arkadeScript?.asm);
447
+ collect(fn.arkadeScript?.witness);
448
+ }
449
+ return refs;
450
+ }
451
+ var TYPED_BYTE_LENGTHS = {
452
+ pubkey: 32,
453
+ signature: 64,
454
+ bytes20: 20,
455
+ bytes32: 32,
456
+ asset: 32
457
+ };
458
+ function validateParamValue(def, value) {
459
+ if (typeof def.type !== "string" || !Object.hasOwn(ARKADE_TYPE_ENCODINGS, def.type)) {
460
+ throw new Error(`program parameter '${def.name}': unknown type '${def.type}'`);
461
+ }
462
+ if (ARKADE_TYPE_ENCODINGS[def.type] === "scriptnum") {
463
+ if (typeof value !== "bigint" && typeof value !== "number") {
464
+ throw new Error(`program parameter '${def.name}' expects ${def.type}, got bytes`);
465
+ }
466
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
467
+ throw new Error(
468
+ `program parameter '${def.name}' expects a safe integer; use bigint for larger values`
469
+ );
470
+ }
471
+ if (def.type === "bool" && value !== 0 && value !== 1 && value !== 0n && value !== 1n) {
472
+ throw new Error(`program parameter '${def.name}' expects a boolean encoded as 0 or 1`);
473
+ }
474
+ return;
475
+ }
476
+ if (!(value instanceof Uint8Array)) {
477
+ throw new Error(
478
+ `program parameter '${def.name}' expects ${def.type} bytes, got ${typeof value}`
479
+ );
480
+ }
481
+ const length = TYPED_BYTE_LENGTHS[def.type];
482
+ if (length !== void 0 && value.length !== length) {
483
+ throw new Error(
484
+ `program parameter '${def.name}' expects a ${length}-byte ${def.type}, got ${value.length} bytes`
485
+ );
486
+ }
487
+ }
488
+ function validateProgram(program, args) {
489
+ const params = program.params ?? [];
490
+ const declared = new Set(params.map((p) => p.name));
491
+ for (const name of declared) {
492
+ if (!Object.hasOwn(args, name) || args[name] === void 0) {
493
+ throw new Error(`program parameter '${name}' is declared but not bound in args`);
494
+ }
495
+ }
496
+ for (const ref of collectParamRefs(program)) {
497
+ if (!declared.has(ref)) {
498
+ throw new Error(`'$${ref}' is referenced but not declared in program params`);
499
+ }
500
+ }
501
+ for (const p of params) {
502
+ validateParamValue(p, args[p.name]);
503
+ }
504
+ for (const name of Object.keys(args)) {
505
+ if (!declared.has(name)) throw new Error(`program: undeclared argument '${name}'`);
506
+ }
507
+ }
508
+ function isTweakedSigner(ref) {
509
+ if (typeof ref !== "object" || ref === null || ref instanceof Uint8Array) return false;
510
+ const { tweak, fn } = ref;
511
+ return typeof tweak === "string" && typeof fn === "string";
512
+ }
513
+ function resolveSigner(ref, args) {
514
+ if (ref instanceof Uint8Array) return ref;
515
+ if (typeof ref !== "string" || !ref.startsWith("$")) {
516
+ throw new Error(`unknown signer reference '${ref}' \u2014 use a '$param' or key bytes`);
517
+ }
518
+ const v = bindValue(args, ref.slice(1));
519
+ if (!(v instanceof Uint8Array)) {
520
+ throw new Error(`signer ${ref} must be a pubkey (bytes)`);
521
+ }
522
+ return v;
523
+ }
524
+ function encodeTapscriptSegment(seg, pubkeys, args) {
525
+ if (seg.csv) {
526
+ const timelock = resolveCsvTimelock(seg.csv, args);
527
+ if (seg.asm) {
528
+ return ConditionCSVMultisigTapscript.encode({
529
+ conditionScript: resolveAsm(seg.asm, args),
530
+ timelock,
531
+ pubkeys
532
+ });
533
+ }
534
+ return CSVMultisigTapscript.encode({ timelock, pubkeys });
535
+ }
536
+ if (seg.cltv !== void 0) {
537
+ return CLTVMultisigTapscript.encode({
538
+ absoluteTimelock: resolveTimelockValue(seg.cltv, args),
539
+ pubkeys
540
+ });
541
+ }
542
+ if (seg.asm) {
543
+ return ConditionMultisigTapscript.encode({
544
+ conditionScript: resolveAsm(seg.asm, args),
545
+ pubkeys
546
+ });
547
+ }
548
+ return MultisigTapscript.encode({ pubkeys });
549
+ }
550
+ function compileFunctions(program, args, keys) {
551
+ if (program.version !== SUPPORTED_PROGRAM_VERSION) {
552
+ throw new UnsupportedProgramVersionError(program.version, "ArkadeContract");
553
+ }
554
+ const functions = program.functions;
555
+ const names = Object.keys(functions);
556
+ if (names.length === 0) {
557
+ throw new Error("ArkadeContract: program has no functions");
558
+ }
559
+ validateProgram(program, args);
560
+ if (args.server !== void 0 && (!(args.server instanceof Uint8Array) || !equalBytes(args.server, keys.serverKey))) {
561
+ throw new Error(
562
+ "ArkadeContract: reserved server parameter must match the contract server key"
563
+ );
564
+ }
565
+ const defs = names.map((n) => functions[n]);
566
+ const covenants = /* @__PURE__ */ new Map();
567
+ for (const [name, def] of Object.entries(functions)) {
568
+ if (!def.arkadeScript) continue;
569
+ const script = resolveAsm(def.arkadeScript.asm, args);
570
+ for (const target of [name, ...def.group ? [def.group] : []]) {
571
+ const previous = covenants.get(target);
572
+ if (previous && !equalBytes(previous, script)) {
573
+ throw new Error(`ArkadeContract: ambiguous covenant '${target}'`);
574
+ }
575
+ covenants.set(target, script);
576
+ }
577
+ }
578
+ const covenant = names.find(
579
+ (_, i) => defs[i].arkadeScript && defs[i].tapscript.emulator !== null
580
+ );
581
+ if (covenant && !keys.emulatorKey) {
582
+ throw new Error(
583
+ `ArkadeContract: function '${covenant}' has an arkadeScript but no emulator is configured \u2014 pass an \`emulator\` to Arkade.connect`
584
+ );
585
+ }
586
+ return defs.map((def, i) => {
587
+ const pubkeys = def.tapscript.signers.map((signer) => {
588
+ if (!isTweakedSigner(signer)) return resolveSigner(signer, args);
589
+ const script = covenants.get(signer.fn);
590
+ if (!script) {
591
+ throw new Error(
592
+ `ArkadeContract: function '${names[i]}' tweaks '${signer.fn}', which has no arkade script`
593
+ );
594
+ }
595
+ return computeArkadeScriptPublicKey(resolveSigner(signer.tweak, args), script);
596
+ });
597
+ const arkadeScript = def.arkadeScript ? covenants.get(names[i]) : void 0;
598
+ const leafPubkeys = [...pubkeys];
599
+ if (arkadeScript && def.tapscript.emulator !== null) {
600
+ const position = def.tapscript.emulatorIndex ?? pubkeys.length;
601
+ if (!Number.isInteger(position) || position < 0 || position > pubkeys.length) {
602
+ throw new Error(
603
+ `ArkadeContract: function '${names[i]}' has an invalid emulator position ${position}`
604
+ );
605
+ }
606
+ const target = def.group ? covenants.get(def.tapscript.emulator ?? def.group) : arkadeScript;
607
+ if (!target || !equalBytes(target, arkadeScript)) {
608
+ throw new Error(
609
+ `ArkadeContract: function '${names[i]}' has an invalid emulator covenant '${def.tapscript.emulator}'`
610
+ );
611
+ }
612
+ leafPubkeys.splice(
613
+ position,
614
+ 0,
615
+ computeArkadeScriptPublicKey(keys.emulatorKey, target)
616
+ );
617
+ } else if (def.tapscript.emulatorIndex !== void 0) {
618
+ throw new Error(
619
+ `ArkadeContract: function '${names[i]}' specifies an emulator position without an emulator`
620
+ );
621
+ }
622
+ validateTapscript({ ...def.tapscript, signers: leafPubkeys });
623
+ const leafScript = encodeTapscriptSegment(def.tapscript, leafPubkeys, args).script;
624
+ return { name: names[i], def, leafScript, arkadeScript, signerKeys: pubkeys };
625
+ });
626
+ }
627
+ var ArkadeProgramScript = class extends VtxoScript {
628
+ constructor(program, args, keys) {
629
+ const partial = compileFunctions(program, args, keys);
630
+ super(partial.map((p) => p.leafScript));
631
+ this.program = program;
632
+ this.args = args;
633
+ this.keys = keys;
634
+ this.compiled = partial.map((p) => ({
635
+ ...p,
636
+ tapLeafScript: this.findLeaf(hex.encode(p.leafScript))
637
+ }));
638
+ }
639
+ program;
640
+ args;
641
+ keys;
642
+ /** Spending paths in declaration order. */
643
+ compiled;
644
+ /** The compiled spending path with the given function name, if any. */
645
+ functionByName(name) {
646
+ return this.compiled.find((f) => f.name === name);
647
+ }
648
+ };
649
+ function parseArtifact(artifact) {
650
+ if (Array.isArray(artifact.functions)) {
651
+ throw new Error(
652
+ "parseArtifact: `functions` is an array, which is the arkadec artifact shape, not an SDK program \u2014 read it with programFromArtifact instead"
653
+ );
654
+ }
655
+ if (typeof artifact.functions !== "object" || artifact.functions === null) {
656
+ throw new Error("parseArtifact: `functions` must be an object keyed by function name");
657
+ }
658
+ const hexToken = (t) => typeof t === "string" && t.startsWith("0x") ? hex.decode(t.slice(2)) : t;
659
+ const signerRef = (s) => {
660
+ if (s instanceof Uint8Array || typeof s === "string") return hexToken(s);
661
+ if (isTweakedSigner(s)) return { tweak: s.tweak, fn: s.fn };
662
+ throw new Error("parseArtifact: a tweaked signer needs string `tweak` and `fn`");
663
+ };
664
+ const timelockValue = (v) => typeof v === "string" && v.startsWith("$") ? v : BigInt(v);
665
+ if (artifact.version !== void 0 && artifact.version !== SUPPORTED_PROGRAM_VERSION) {
666
+ throw new UnsupportedProgramVersionError(artifact.version, "parseArtifact");
667
+ }
668
+ const declarations = [artifact.params];
669
+ for (const [name, fn] of Object.entries(artifact.functions)) {
670
+ if (!fn || typeof fn !== "object" || Array.isArray(fn)) {
671
+ throw new Error(`parseArtifact: function '${name}' must be an object`);
672
+ }
673
+ const tap = fn.tapscript;
674
+ if (tap !== void 0 && (!tap || typeof tap !== "object" || Array.isArray(tap))) {
675
+ throw new Error(`parseArtifact: function '${name}' tapscript must be an object`);
676
+ }
677
+ declarations.push(fn.inputs, tap?.signatures);
678
+ if (tap?.emulatorIndex !== void 0 && (!Number.isInteger(tap.emulatorIndex) || tap.emulatorIndex < 0)) {
679
+ throw new Error(`parseArtifact: function '${name}' has an invalid emulator position`);
680
+ }
681
+ }
682
+ for (const defs of declarations) {
683
+ if (defs === void 0) continue;
684
+ if (!Array.isArray(defs)) {
685
+ throw new Error(
686
+ "parseArtifact: parameters, inputs and signatures require arrays of typed declarations"
687
+ );
688
+ }
689
+ for (const def of defs) {
690
+ if (!def || typeof def.name !== "string" || def.name.length === 0 || typeof def.type !== "string" || !Object.hasOwn(ARKADE_TYPE_ENCODINGS, def.type)) {
691
+ throw new Error(
692
+ "parseArtifact: parameters, inputs and signatures require typed { name, type } declarations"
693
+ );
694
+ }
695
+ }
696
+ }
697
+ const functions = /* @__PURE__ */ Object.create(null);
698
+ for (const [name, fn] of Object.entries(artifact.functions)) {
699
+ const tap = fn.tapscript ?? {};
700
+ const tapscript = {
701
+ signers: (tap.signers ?? []).map(signerRef),
702
+ ...tap.signatures ? { signatures: tap.signatures } : {},
703
+ ...tap.asm ? { asm: tap.asm.map(hexToken) } : {},
704
+ ...tap.witness ? { witness: tap.witness.map(hexToken) } : {},
705
+ ...tap.csv ? { csv: { type: tap.csv.type, value: timelockValue(tap.csv.value) } } : {},
706
+ ...tap.cltv !== void 0 ? { cltv: timelockValue(tap.cltv) } : {},
707
+ ..."emulator" in tap ? { emulator: tap.emulator } : {},
708
+ ...tap.emulatorIndex !== void 0 ? { emulatorIndex: tap.emulatorIndex } : {}
709
+ };
710
+ const arkadeScript = fn.arkadeScript ? {
711
+ asm: fn.arkadeScript.asm.map(hexToken),
712
+ ...fn.arkadeScript.witness ? { witness: fn.arkadeScript.witness.map(hexToken) } : {}
713
+ } : void 0;
714
+ functions[name] = {
715
+ ...fn.group !== void 0 ? { group: fn.group } : {},
716
+ ...fn.inputs ? { inputs: fn.inputs } : {},
717
+ tapscript,
718
+ ...arkadeScript ? { arkadeScript } : {}
719
+ };
720
+ }
721
+ return {
722
+ version: artifact.version ?? SUPPORTED_PROGRAM_VERSION,
723
+ ...artifact.name !== void 0 ? { name: artifact.name } : {},
724
+ ...artifact.params ? { params: artifact.params } : {},
725
+ functions
726
+ };
727
+ }
728
+ function stringifyArtifact(program) {
729
+ const token = (t) => {
730
+ if (t instanceof Uint8Array) return "0x" + hex.encode(t);
731
+ if (typeof t === "bigint") {
732
+ if (t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER)) {
733
+ return Number(t);
734
+ }
735
+ return "0x" + hex.encode(MinimalScriptNum.encode(t));
736
+ }
737
+ return t;
738
+ };
739
+ const functions = /* @__PURE__ */ Object.create(null);
740
+ for (const [name, fn] of Object.entries(program.functions)) {
741
+ const tap = fn.tapscript;
742
+ functions[name] = {
743
+ ...fn.group !== void 0 ? { group: fn.group } : {},
744
+ ...fn.inputs ? { inputs: fn.inputs } : {},
745
+ tapscript: {
746
+ signers: tap.signers.map(token),
747
+ ...tap.signatures ? { signatures: tap.signatures } : {},
748
+ ...tap.asm ? { asm: tap.asm.map(token) } : {},
749
+ ...tap.witness ? { witness: tap.witness.map(token) } : {},
750
+ ...tap.csv ? { csv: { type: tap.csv.type, value: tap.csv.value.toString() } } : {},
751
+ ...tap.cltv !== void 0 ? { cltv: tap.cltv.toString() } : {},
752
+ ...tap.emulator !== void 0 ? { emulator: tap.emulator } : {},
753
+ ...tap.emulatorIndex !== void 0 ? { emulatorIndex: tap.emulatorIndex } : {}
754
+ },
755
+ ...fn.arkadeScript ? {
756
+ arkadeScript: {
757
+ asm: fn.arkadeScript.asm.map(token),
758
+ ...fn.arkadeScript.witness ? { witness: fn.arkadeScript.witness.map(token) } : {}
759
+ }
760
+ } : {}
761
+ };
762
+ }
763
+ return JSON.stringify({
764
+ version: program.version,
765
+ ...program.name !== void 0 ? { name: program.name } : {},
766
+ ...program.params ? { params: program.params } : {},
767
+ functions
768
+ });
769
+ }
770
+ function serializeArgValue(v) {
771
+ if (v instanceof Uint8Array) return "0x" + hex.encode(v);
772
+ if (typeof v === "bigint") return v.toString();
773
+ return v;
774
+ }
775
+ function parseTypedArgValue(name, type, v) {
776
+ if (ARKADE_TYPE_ENCODINGS[type] === "scriptnum") {
777
+ if (typeof v === "number") return v;
778
+ if (typeof v === "string") return BigInt(v);
779
+ throw new Error(
780
+ `arkade contract params: '${name}' expects ${type}, got ${JSON.stringify(v)}`
781
+ );
782
+ }
783
+ if (typeof v === "string" && v.startsWith("0x")) return hex.decode(v.slice(2));
784
+ throw new Error(
785
+ `arkade contract params: '${name}' expects ${type} as 0x-prefixed hex, got ${JSON.stringify(v)}`
786
+ );
787
+ }
788
+ function serializeArkadeContractParams(typed) {
789
+ const args = /* @__PURE__ */ Object.create(null);
790
+ for (const [k, v] of Object.entries(typed.args)) {
791
+ args[k] = serializeArgValue(v);
792
+ }
793
+ return {
794
+ program: stringifyArtifact(typed.program),
795
+ args: JSON.stringify(args),
796
+ serverKey: hex.encode(typed.serverKey),
797
+ ...typed.userKey ? { userKey: hex.encode(typed.userKey) } : {},
798
+ ...typed.emulatorKey ? { emulatorKey: hex.encode(typed.emulatorKey) } : {}
799
+ };
800
+ }
801
+ function deserializeArkadeContractParams(params) {
802
+ if (!params.program) {
803
+ throw new Error("arkade contract params: missing 'program'");
804
+ }
805
+ if (!params.serverKey) {
806
+ throw new Error("arkade contract params: missing 'serverKey'");
807
+ }
808
+ const program = parseArtifact(JSON.parse(params.program));
809
+ const paramTypes = new Map((program.params ?? []).map((p) => [p.name, p.type]));
810
+ const args = /* @__PURE__ */ Object.create(null);
811
+ if (params.args) {
812
+ for (const [k, v] of Object.entries(JSON.parse(params.args))) {
813
+ const type = paramTypes.get(k);
814
+ if (!type) throw new Error(`arkade contract params: undeclared argument '${k}'`);
815
+ args[k] = parseTypedArgValue(k, type, v);
816
+ }
817
+ }
818
+ return {
819
+ program,
820
+ args,
821
+ serverKey: hex.decode(params.serverKey),
822
+ ...params.userKey ? { userKey: hex.decode(params.userKey) } : {},
823
+ ...params.emulatorKey ? { emulatorKey: hex.decode(params.emulatorKey) } : {}
824
+ };
825
+ }
826
+
827
+ export { ARKADE_OP, ARKADE_OPCODES, ARKADE_OPCODE_NAMES, ARKADE_OPCODE_VALUES, ARKADE_OPS, ARKADE_TYPE_ENCODINGS, ArkadeProgramScript, ArkadeScript, OPCODE_NAMES, OPCODE_VALUES, SUPPORTED_PROGRAM_VERSION, UnsupportedProgramVersionError, arkadeScriptHash, arkadeWitnessHash, asmToBytes, bignum_exports, bytesToASM, computeArkadeScriptPublicKey, deserializeArkadeContractParams, fromASM, getOpcodeName, getOpcodeValue, parseArtifact, resolveAsm, resolveCsvTimelock, resolveTimelockValue, serializeArkadeContractParams, staticWitness, stringifyArtifact, toASM, toXOnly, validateParamValue, validateProgram, witnessRefToBytes };
828
+ //# sourceMappingURL=chunk-DNFTHG73.js.map
829
+ //# sourceMappingURL=chunk-DNFTHG73.js.map