@btc-vision/btc-runtime 1.3.17 → 1.3.18

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@btc-vision/btc-runtime",
3
- "version": "1.3.17",
3
+ "version": "1.3.18",
4
4
  "description": "Bitcoin Smart Contract Runtime",
5
5
  "main": "btc/index.ts",
6
6
  "scripts": {
@@ -18,6 +18,7 @@ export function onDeploy(data: Uint8Array): void {
18
18
  const calldata: Calldata = new BytesReader(data);
19
19
 
20
20
  Blockchain.contract.onDeployment(calldata);
21
+ Blockchain.contract.onExecutionCompleted();
21
22
  }
22
23
 
23
24
  export function setEnvironment(data: Uint8Array): void {
package/runtime/index.ts CHANGED
@@ -63,6 +63,7 @@ export * from './memory/Uint8ArrayMerger';
63
63
  export * from './storage/StoredU256';
64
64
  export * from './storage/StoredU64';
65
65
  export * from './storage/StoredU16Array';
66
+ export * from './storage/StoredU32Array';
66
67
  export * from './storage/StoredBooleanArray';
67
68
  export * from './storage/StoredU128Array';
68
69
  export * from './storage/StoredU256Array';
@@ -363,11 +363,9 @@ export class StoredU128Array {
363
363
  throw new Revert('SetLength operation failed: Length exceeds maximum allowed value.');
364
364
  }
365
365
 
366
- if (newLength < this._length) {
367
- // Truncate the array if newLength is smaller
368
- for (let i: u64 = newLength; i < this._length; i++) {
369
- this.delete(i);
370
- }
366
+ if (newLength > this._startIndex) {
367
+ this._startIndex = newLength;
368
+ this._isChangedStartIndex = true;
371
369
  }
372
370
 
373
371
  this._length = newLength;
@@ -108,7 +108,7 @@ export class StoredU16Array {
108
108
  const newIndex: u64 = this._length;
109
109
  const wrappedIndex: u64 =
110
110
  newIndex < this.MAX_LENGTH ? newIndex : newIndex % this.MAX_LENGTH;
111
-
111
+
112
112
  const slotIndex: u64 = wrappedIndex / 16;
113
113
  const subIndex: u8 = <u8>(wrappedIndex % 16);
114
114
 
@@ -354,11 +354,9 @@ export class StoredU16Array {
354
354
  throw new Revert('SetLength operation failed: Length exceeds maximum allowed value.');
355
355
  }
356
356
 
357
- if (newLength < this._length) {
358
- // Truncate the array if newLength is smaller
359
- for (let i: u64 = newLength; i < this._length; i++) {
360
- this.delete(i);
361
- }
357
+ if (newLength > this._startIndex) {
358
+ this._startIndex = newLength;
359
+ this._isChangedStartIndex = true;
362
360
  }
363
361
 
364
362
  this._length = newLength;
@@ -364,11 +364,9 @@ export class StoredU256Array {
364
364
  throw new Revert('SetLength operation failed: Length exceeds maximum allowed value.');
365
365
  }
366
366
 
367
- if (newLength < this._length) {
368
- // Truncate the array if newLength is smaller
369
- for (let i: u64 = newLength; i < this._length; i++) {
370
- this.delete(i);
371
- }
367
+ if (newLength > this._startIndex) {
368
+ this._startIndex = newLength;
369
+ this._isChangedStartIndex = true;
372
370
  }
373
371
 
374
372
  this._length = newLength;
@@ -0,0 +1,470 @@
1
+ import { u256 } from '@btc-vision/as-bignum/assembly';
2
+ import { Blockchain } from '../env';
3
+ import { BytesWriter } from '../buffer/BytesWriter';
4
+ import { SafeMath } from '../types/SafeMath';
5
+ import { Revert } from '../types/Revert';
6
+
7
+ /**
8
+ * @class StoredU32Array
9
+ * @description Manages an array of u32 values across multiple storage slots.
10
+ * Each slot holds **eight** u32 values packed into a single u256.
11
+ */
12
+ @final
13
+ export class StoredU32Array {
14
+ private readonly baseU256Pointer: u256;
15
+ private readonly lengthPointer: u256;
16
+
17
+ // Internal cache for storage slots
18
+ private _values: Map<u64, u32[]> = new Map(); // Map from slotIndex to array of eight u32s
19
+ private _isLoaded: Set<u64> = new Set(); // Set of slotIndexes that are loaded
20
+ private _isChanged: Set<u64> = new Set(); // Set of slotIndexes that are modified
21
+
22
+ // Internal variables for length and startIndex management
23
+ private _length: u64 = 0; // Current length of the array
24
+ private _startIndex: u64 = 0; // Starting index of the array
25
+ private _isChangedLength: bool = false; // Indicates if the length has been modified
26
+ private _isChangedStartIndex: bool = false; // Indicates if the startIndex has been modified
27
+
28
+ // Define a maximum allowed length to prevent excessive storage usage
29
+ private readonly MAX_LENGTH: u64 = u64(u32.MAX_VALUE - 1);
30
+
31
+ /**
32
+ * @constructor
33
+ * @param {u16} pointer - The primary pointer identifier.
34
+ * @param {Uint8Array} subPointer - The sub-pointer for memory slot addressing.
35
+ * @param {u256} defaultValue - The default u256 value if storage is uninitialized.
36
+ */
37
+ constructor(
38
+ public pointer: u16,
39
+ public subPointer: Uint8Array,
40
+ private defaultValue: u256,
41
+ ) {
42
+ // Initialize the base pointer using the primary pointer and subPointer
43
+ const writer = new BytesWriter(32);
44
+ writer.writeU16(pointer);
45
+ writer.writeBytes(subPointer);
46
+
47
+ const baseU256Pointer = u256.fromBytes(writer.getBuffer(), true);
48
+ this.baseU256Pointer = baseU256Pointer;
49
+
50
+ // We’ll reuse the same pointer for length & startIndex
51
+ const lengthPointer = baseU256Pointer.clone();
52
+ this.lengthPointer = lengthPointer;
53
+
54
+ // Load current length + startIndex from storage
55
+ const storedLengthAndStartIndex: u256 = Blockchain.getStorageAt(lengthPointer, u256.Zero);
56
+ this._length = storedLengthAndStartIndex.lo1; // Bytes 0-7: length (u64)
57
+ this._startIndex = storedLengthAndStartIndex.lo2; // Bytes 8-15: startIndex (u64)
58
+ }
59
+
60
+ /**
61
+ * @method get
62
+ * @description Retrieves the u32 value at the specified global index.
63
+ * @param {u64} index - The global index (0 to ∞) of the u32 value to retrieve.
64
+ * @returns {u32} - The u32 value at the specified index.
65
+ */
66
+ @inline
67
+ public get(index: u64): u32 {
68
+ assert(index < this._length, 'Index out of bounds');
69
+
70
+ const slotIndex: u64 = index / 8; // Each slot holds 8 u32s
71
+ const subIndex: u8 = <u8>(index % 8); // 0..7
72
+ this.ensureValues(slotIndex);
73
+ const slotValues = this._values.get(slotIndex);
74
+ return slotValues ? slotValues[subIndex] : 0;
75
+ }
76
+
77
+ /**
78
+ * @method set
79
+ * @description Sets the u32 value at the specified global index.
80
+ * @param {u64} index - The global index (0 to ∞) of the u32 value to set.
81
+ * @param {u32} value - The u32 value to assign.
82
+ */
83
+ @inline
84
+ public set(index: u64, value: u32): void {
85
+ assert(index < this._length, 'Index exceeds current array length');
86
+ const slotIndex: u64 = index / 8;
87
+ const subIndex: u8 = <u8>(index % 8);
88
+
89
+ this.ensureValues(slotIndex);
90
+ const slotValues = this._values.get(slotIndex);
91
+ if (slotValues && slotValues[subIndex] !== value) {
92
+ slotValues[subIndex] = value;
93
+ this._isChanged.add(slotIndex);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * @method push
99
+ * @description Appends a new u32 value to the end of the array.
100
+ * @param {u32} value - The u32 value to append.
101
+ */
102
+ public push(value: u32): void {
103
+ if (this._length >= this.MAX_LENGTH) {
104
+ throw new Revert(
105
+ 'Push operation failed: Array has reached its maximum allowed length.',
106
+ );
107
+ }
108
+
109
+ const newIndex: u64 = this._length;
110
+ const wrappedIndex: u64 =
111
+ newIndex < this.MAX_LENGTH ? newIndex : newIndex % this.MAX_LENGTH;
112
+
113
+ const slotIndex: u64 = wrappedIndex / 8;
114
+ const subIndex: u8 = <u8>(wrappedIndex % 8);
115
+
116
+ // Ensure the slot is loaded
117
+ this.ensureValues(slotIndex);
118
+
119
+ // Set the new value
120
+ const slotValues = this._values.get(slotIndex);
121
+ if (slotValues) {
122
+ slotValues[subIndex] = value;
123
+ this._isChanged.add(slotIndex);
124
+ }
125
+
126
+ // Increment the length
127
+ this._length += 1;
128
+ this._isChangedLength = true;
129
+ }
130
+
131
+ /**
132
+ * @method delete
133
+ * @description Deletes the u32 value at the specified index by setting it to zero (does not reorder).
134
+ * @param {u64} index - The global index of the u32 value to delete.
135
+ */
136
+ public delete(index: u64): void {
137
+ if (index >= this._length) {
138
+ throw new Revert('Delete operation failed: Index out of bounds.');
139
+ }
140
+
141
+ const slotIndex: u64 = index / 8;
142
+ const subIndex: u8 = <u8>(index % 8);
143
+ this.ensureValues(slotIndex);
144
+
145
+ const slotValues = this._values.get(slotIndex);
146
+ if (slotValues && slotValues[subIndex] !== 0) {
147
+ slotValues[subIndex] = 0;
148
+ this._isChanged.add(slotIndex);
149
+ }
150
+ }
151
+
152
+ /**
153
+ * @method shift
154
+ * @description Removes the first element of the array by zeroing it out, decrementing length,
155
+ * and incrementing the startIndex (with wrap-around).
156
+ */
157
+ public shift(): void {
158
+ if (this._length === 0) {
159
+ throw new Revert('Shift operation failed: Array is empty.');
160
+ }
161
+
162
+ const currentStartIndex: u64 = this._startIndex;
163
+ const slotIndex: u64 = currentStartIndex / 8;
164
+ const subIndex: u8 = <u8>(currentStartIndex % 8);
165
+
166
+ this.ensureValues(slotIndex);
167
+ const slotValues = this._values.get(slotIndex);
168
+ if (slotValues && slotValues[subIndex] !== 0) {
169
+ slotValues[subIndex] = 0;
170
+ this._isChanged.add(slotIndex);
171
+ }
172
+
173
+ // Decrement length
174
+ this._length -= 1;
175
+ this._isChangedLength = true;
176
+
177
+ // Increment startIndex with wrap-around
178
+ if (this._startIndex < this.MAX_LENGTH - 1) {
179
+ this._startIndex += 1;
180
+ } else {
181
+ this._startIndex = 0;
182
+ }
183
+ this._isChangedStartIndex = true;
184
+ }
185
+
186
+ /**
187
+ * @method save
188
+ * @description Persists all modified slots and the current length/startIndex into storage.
189
+ */
190
+ public save(): void {
191
+ // Save changed slots
192
+ const changedSlots = this._isChanged.values();
193
+ for (let i = 0; i < changedSlots.length; i++) {
194
+ const slotIndex = changedSlots[i];
195
+ const packed = this.packValues(slotIndex);
196
+ const storagePointer = this.calculateStoragePointer(slotIndex);
197
+ Blockchain.setStorageAt(storagePointer, packed);
198
+ }
199
+ this._isChanged.clear();
200
+
201
+ // Save length + startIndex if changed
202
+ if (this._isChangedLength || this._isChangedStartIndex) {
203
+ const packedLengthAndStartIndex = new u256();
204
+ packedLengthAndStartIndex.lo1 = this._length;
205
+ packedLengthAndStartIndex.lo2 = this._startIndex;
206
+
207
+ Blockchain.setStorageAt(this.lengthPointer, packedLengthAndStartIndex);
208
+ this._isChangedLength = false;
209
+ this._isChangedStartIndex = false;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * @method deleteAll
215
+ * @description Deletes all storage slots and resets length/startIndex to zero.
216
+ */
217
+ public deleteAll(): void {
218
+ // Clear loaded slots from storage
219
+ const keys = this._values.keys();
220
+ for (let i = 0; i < keys.length; i++) {
221
+ const slotIndex = keys[i];
222
+ const storagePointer = this.calculateStoragePointer(slotIndex);
223
+ Blockchain.setStorageAt(storagePointer, u256.Zero);
224
+ }
225
+
226
+ // Reset length + startIndex
227
+ Blockchain.setStorageAt(this.lengthPointer, u256.Zero);
228
+ this._length = 0;
229
+ this._startIndex = 0;
230
+ this._isChangedLength = false;
231
+ this._isChangedStartIndex = false;
232
+
233
+ // Clear caches
234
+ this._values.clear();
235
+ this._isLoaded.clear();
236
+ this._isChanged.clear();
237
+ }
238
+
239
+ /**
240
+ * @method setMultiple
241
+ * @description Sets multiple u32 values starting at a given global index.
242
+ * @param {u64} startIndex - The starting global index.
243
+ * @param {u32[]} values - The array of u32 values to set.
244
+ */
245
+ @inline
246
+ public setMultiple(startIndex: u64, values: u32[]): void {
247
+ for (let i: u64 = 0; i < values.length; i++) {
248
+ this.set(startIndex + i, values[i]);
249
+ }
250
+ }
251
+
252
+ /**
253
+ * @method getAll
254
+ * @description Retrieves a consecutive range of u32 values starting at a given global index.
255
+ * @param {u64} startIndex - The starting global index.
256
+ * @param {u64} count - The number of u32 values to retrieve.
257
+ * @returns {u32[]} - The requested slice of the array.
258
+ */
259
+ @inline
260
+ public getAll(startIndex: u64, count: u64): u32[] {
261
+ assert(startIndex + count <= this._length, 'Requested range exceeds array length');
262
+
263
+ if (u32.MAX_VALUE < count) {
264
+ throw new Revert('Requested range exceeds maximum allowed value.');
265
+ }
266
+
267
+ const result: u32[] = new Array<u32>(count as u32);
268
+ for (let i: u64 = 0; i < count; i++) {
269
+ result[i as u32] = this.get(startIndex + i);
270
+ }
271
+ return result;
272
+ }
273
+
274
+ /**
275
+ * @method toString
276
+ * @description Returns a string representation of all cached u32 values.
277
+ * @returns {string} - A string in the format "[val0, val1, ..., valN]".
278
+ */
279
+ @inline
280
+ public toString(): string {
281
+ let str = '[';
282
+ for (let i: u64 = 0; i < this._length; i++) {
283
+ const value = this.get(i);
284
+ str += value.toString();
285
+ if (i !== this._length - 1) {
286
+ str += ', ';
287
+ }
288
+ }
289
+ str += ']';
290
+ return str;
291
+ }
292
+
293
+ /**
294
+ * @method toBytes
295
+ * @description Packs all cached slots into u256 and returns them as a byte array.
296
+ * @returns {u8[]} - The packed u256 values in byte form.
297
+ */
298
+ @inline
299
+ public toBytes(): u8[] {
300
+ const bytes: u8[] = new Array<u8>();
301
+ const slotCount: u64 = (this._length + 7) / 8; // each slot has 8 values
302
+
303
+ for (let slotIndex: u64 = 0; slotIndex < slotCount; slotIndex++) {
304
+ this.ensureValues(slotIndex);
305
+ const packed = this.packValues(slotIndex);
306
+ const slotBytes = packed.toBytes();
307
+ for (let i: u32 = 0; i < slotBytes.length; i++) {
308
+ bytes.push(slotBytes[i]);
309
+ }
310
+ }
311
+ return bytes;
312
+ }
313
+
314
+ /**
315
+ * @method reset
316
+ * @description Zeros out the entire array and resets length/startIndex to zero, persisting changes immediately.
317
+ */
318
+ @inline
319
+ public reset(): void {
320
+ this._length = 0;
321
+ this._startIndex = 0;
322
+ this._isChangedLength = true;
323
+ this._isChangedStartIndex = true;
324
+ this.save();
325
+ }
326
+
327
+ /**
328
+ * @method getLength
329
+ * @description Returns the current length of the array.
330
+ * @returns {u64} - The length.
331
+ */
332
+ @inline
333
+ public getLength(): u64 {
334
+ return this._length;
335
+ }
336
+
337
+ /**
338
+ * @method startingIndex
339
+ * @description Returns the current starting index of the array.
340
+ * @returns {u64} - The startIndex.
341
+ */
342
+ @inline
343
+ public startingIndex(): u64 {
344
+ return this._startIndex;
345
+ }
346
+
347
+ /**
348
+ * @method setLength
349
+ * @description Adjusts the length of the array (may truncate if newLength < currentLength).
350
+ * @param {u64} newLength - The new length to set.
351
+ */
352
+ public setLength(newLength: u64): void {
353
+ if (newLength > this.MAX_LENGTH) {
354
+ throw new Revert('SetLength operation failed: Length exceeds maximum allowed value.');
355
+ }
356
+
357
+ if (newLength > this._startIndex) {
358
+ this._startIndex = newLength;
359
+ this._isChangedStartIndex = true;
360
+ }
361
+
362
+ this._length = newLength;
363
+ this._isChangedLength = true;
364
+ }
365
+
366
+ /**
367
+ * @method deleteLast
368
+ * @description Deletes the last element of the array by setting it to zero and decrementing the length.
369
+ */
370
+ public deleteLast(): void {
371
+ if (this._length === 0) {
372
+ throw new Revert('DeleteLast operation failed: Array is empty.');
373
+ }
374
+
375
+ const index = this._length - 1;
376
+ this.delete(index);
377
+
378
+ this._length -= 1;
379
+ this._isChangedLength = true;
380
+ }
381
+
382
+ /**
383
+ * @private
384
+ * @method ensureValues
385
+ * @description Loads the slot data from storage if not already in cache.
386
+ * @param {u64} slotIndex - The slot index.
387
+ */
388
+ private ensureValues(slotIndex: u64): void {
389
+ if (!this._isLoaded.has(slotIndex)) {
390
+ const storagePointer = this.calculateStoragePointer(slotIndex);
391
+ const storedU256: u256 = Blockchain.getStorageAt(storagePointer, this.defaultValue);
392
+ const slotValues = this.unpackU256(storedU256);
393
+ this._values.set(slotIndex, slotValues);
394
+ this._isLoaded.add(slotIndex);
395
+ }
396
+ }
397
+
398
+ /**
399
+ * @private
400
+ * @method packValues
401
+ * @description Packs eight u32 values into a single u256 (lo1, lo2, hi1, hi2).
402
+ * @param {u64} slotIndex - The slot index.
403
+ * @returns {u256} - The packed u256.
404
+ */
405
+ private packValues(slotIndex: u64): u256 {
406
+ const values = this._values.get(slotIndex);
407
+ if (!values) {
408
+ return u256.Zero;
409
+ }
410
+ const packed = new u256();
411
+
412
+ // Each 64 bits can store two u32:
413
+ // lo1 = (values[0], values[1])
414
+ // lo2 = (values[2], values[3])
415
+ // hi1 = (values[4], values[5])
416
+ // hi2 = (values[6], values[7])
417
+
418
+ // Pack into lo1
419
+ packed.lo1 = (u64(values[0]) << 32) | (u64(values[1]) & 0xffffffff);
420
+
421
+ // Pack into lo2
422
+ packed.lo2 = (u64(values[2]) << 32) | (u64(values[3]) & 0xffffffff);
423
+
424
+ // Pack into hi1
425
+ packed.hi1 = (u64(values[4]) << 32) | (u64(values[5]) & 0xffffffff);
426
+
427
+ // Pack into hi2
428
+ packed.hi2 = (u64(values[6]) << 32) | (u64(values[7]) & 0xffffffff);
429
+
430
+ return packed;
431
+ }
432
+
433
+ /**
434
+ * @private
435
+ * @method unpackU256
436
+ * @description Unpacks a u256 into an array of eight u32 values.
437
+ * @param {u256} storedU256 - The stored u256 data.
438
+ * @returns {u32[]} - The array of eight u32s.
439
+ */
440
+ private unpackU256(storedU256: u256): u32[] {
441
+ const values: u32[] = new Array<u32>(8);
442
+
443
+ // Extract each pair of u32 from lo1, lo2, hi1, hi2
444
+ values[0] = u32(storedU256.lo1 >> 32);
445
+ values[1] = u32(storedU256.lo1 & 0xffffffff);
446
+
447
+ values[2] = u32(storedU256.lo2 >> 32);
448
+ values[3] = u32(storedU256.lo2 & 0xffffffff);
449
+
450
+ values[4] = u32(storedU256.hi1 >> 32);
451
+ values[5] = u32(storedU256.hi1 & 0xffffffff);
452
+
453
+ values[6] = u32(storedU256.hi2 >> 32);
454
+ values[7] = u32(storedU256.hi2 & 0xffffffff);
455
+
456
+ return values;
457
+ }
458
+
459
+ /**
460
+ * @private
461
+ * @method calculateStoragePointer
462
+ * @description Derives the storage pointer for a slot index by adding (slotIndex + 1) to the base pointer.
463
+ * @param {u64} slotIndex - The slot index.
464
+ * @returns {u256} - The resulting storage pointer.
465
+ */
466
+ private calculateStoragePointer(slotIndex: u64): u256 {
467
+ // We offset by +1 so we don't collide with the length pointer (stored at basePointer itself).
468
+ return SafeMath.add(this.baseU256Pointer, u256.fromU64(slotIndex + 1));
469
+ }
470
+ }