utils.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { Cell, beginCell } from "@ton/core";
  2. export function createCellChain(buffer: Buffer): Cell {
  3. let chunks = bufferToChunks(buffer, 127);
  4. let lastCell: Cell | null = null;
  5. // Iterate through chunks in reverse order
  6. for (let i = chunks.length - 1; i >= 0; i--) {
  7. const chunk = chunks[i];
  8. const cellBuilder = beginCell();
  9. const buffer = Buffer.from(chunk);
  10. cellBuilder.storeBuffer(buffer);
  11. if (lastCell) {
  12. cellBuilder.storeRef(lastCell);
  13. }
  14. lastCell = cellBuilder.endCell();
  15. }
  16. // lastCell will be the root cell of our chain
  17. if (!lastCell) {
  18. throw new Error("Failed to create cell chain");
  19. }
  20. return lastCell;
  21. }
  22. function bufferToChunks(
  23. buff: Buffer,
  24. chunkSizeBytes: number = 127
  25. ): Uint8Array[] {
  26. const chunks: Uint8Array[] = [];
  27. const uint8Array = new Uint8Array(
  28. buff.buffer,
  29. buff.byteOffset,
  30. buff.byteLength
  31. );
  32. for (let offset = 0; offset < uint8Array.length; offset += chunkSizeBytes) {
  33. const remainingBytes = Math.min(chunkSizeBytes, uint8Array.length - offset);
  34. const chunk = uint8Array.subarray(offset, offset + remainingBytes);
  35. chunks.push(chunk);
  36. }
  37. return chunks;
  38. }