@floorlaunchpad/sdk 0.4.0 → 0.6.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 (89) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/dist/abi/evm.gen.js +5 -0
  3. package/dist/abi/functions.gen.js +1 -1
  4. package/dist/client/solana/index.js +13 -8
  5. package/dist/config/generated.js +78 -1
  6. package/dist/config/registry.gen.js +1 -1
  7. package/dist/evm/chains.js +56 -18
  8. package/dist/evm/squid.js +10 -10
  9. package/dist/evm/zap.js +148 -35
  10. package/dist/index.js +1 -0
  11. package/dist/indexer/bodies.js +9 -0
  12. package/dist/indexer/client.js +2 -0
  13. package/dist/indexer/contract.js +48 -2
  14. package/dist/indexer/paths.js +26 -0
  15. package/dist/indexer/read.js +3 -0
  16. package/dist/math/v2/book.js +40 -7
  17. package/dist/math/v2/create.js +1 -1
  18. package/dist/math/v2/relay.js +201 -1
  19. package/dist/math/v2/split.js +60 -15
  20. package/dist/math/v2/trade.js +16 -8
  21. package/dist/ton/addresses.js +36 -0
  22. package/dist/ton/book-check.js +23 -0
  23. package/dist/ton/book.js +119 -0
  24. package/dist/ton/cell.js +542 -0
  25. package/dist/ton/consts.generated.js +17 -0
  26. package/dist/ton/content.js +83 -0
  27. package/dist/ton/gas.js +198 -0
  28. package/dist/ton/governance.js +401 -0
  29. package/dist/ton/index.js +18 -0
  30. package/dist/ton/messages.js +340 -0
  31. package/dist/ton/ops.js +37 -0
  32. package/dist/ton/price.js +51 -0
  33. package/dist/ton/quote-entry.js +116 -0
  34. package/dist/ton/quote.js +25 -0
  35. package/dist/ton/reader.js +378 -0
  36. package/dist/ton/types.js +43 -0
  37. package/dist/ton/wallet.js +26 -0
  38. package/dist/v2/devbuy.js +6 -4
  39. package/dist/v2/evm.js +3 -1
  40. package/dist/v2/layouts.js +5 -1
  41. package/dist/v2/presetRowEvm.js +21 -2
  42. package/dist/v2/router.js +2 -2
  43. package/dist/v2/solanaSettle.js +2 -0
  44. package/docs/ton.md +107 -0
  45. package/examples/floor-line.html +1 -1
  46. package/package.json +6 -1
  47. package/src/abi/evm.gen.ts +5 -0
  48. package/src/abi/functions.gen.ts +1 -1
  49. package/src/client/solana/index.ts +13 -8
  50. package/src/config/generated.ts +78 -1
  51. package/src/config/registry.gen.ts +1 -1
  52. package/src/evm/chains.ts +63 -17
  53. package/src/evm/squid.ts +10 -10
  54. package/src/evm/zap.ts +185 -36
  55. package/src/index.ts +1 -0
  56. package/src/indexer/bodies.ts +11 -0
  57. package/src/indexer/client.ts +5 -1
  58. package/src/indexer/contract.ts +48 -2
  59. package/src/indexer/paths.ts +47 -0
  60. package/src/indexer/read.ts +5 -2
  61. package/src/math/v2/book.ts +42 -7
  62. package/src/math/v2/create.ts +1 -1
  63. package/src/math/v2/relay.ts +208 -1
  64. package/src/math/v2/split.ts +70 -16
  65. package/src/math/v2/trade.ts +16 -8
  66. package/src/ton/addresses.ts +38 -0
  67. package/src/ton/book-check.ts +24 -0
  68. package/src/ton/book.ts +136 -0
  69. package/src/ton/cell.ts +547 -0
  70. package/src/ton/consts.generated.ts +17 -0
  71. package/src/ton/content.ts +97 -0
  72. package/src/ton/gas.ts +209 -0
  73. package/src/ton/governance.ts +452 -0
  74. package/src/ton/index.ts +18 -0
  75. package/src/ton/messages.ts +343 -0
  76. package/src/ton/ops.ts +37 -0
  77. package/src/ton/price.ts +54 -0
  78. package/src/ton/quote-entry.ts +138 -0
  79. package/src/ton/quote.ts +67 -0
  80. package/src/ton/reader.ts +420 -0
  81. package/src/ton/types.ts +201 -0
  82. package/src/ton/wallet.ts +30 -0
  83. package/src/v2/devbuy.ts +6 -4
  84. package/src/v2/evm.ts +5 -1
  85. package/src/v2/layouts.ts +5 -1
  86. package/src/v2/presetRowEvm.ts +21 -2
  87. package/src/v2/router.ts +2 -2
  88. package/src/v2/solanaSettle.ts +2 -0
  89. package/src/v2/types.ts +4 -1
@@ -0,0 +1,136 @@
1
+
2
+
3
+ import { Address, bytesOfBase64, fromBoc, hexOf } from "./cell.ts";
4
+ import type { Cell } from "./cell.ts";
5
+ import type { TonChain } from "./types.ts";
6
+ import { TON_MAINNET, TON_INIT_CODES_BASE64, TON_PINNED_CODE_HASHES as GEN_HASHES } from "./consts.generated.ts";
7
+
8
+ export interface TonBook {
9
+ network: "mainnet" | "testnet";
10
+ globalId: -239 | -3;
11
+ factory: Address;
12
+ timelock: Address;
13
+ deploySeqno?: number;
14
+
15
+ codeHashes: Readonly<Record<"factory" | "timelock" | "launch" | "wallet" | "account" | "trader", string>>;
16
+
17
+ initHashes: Readonly<Record<"launch" | "wallet" | "account" | "trader", string>>;
18
+ codes: Readonly<{ wallet: Cell; account: Cell; trader: Cell }>;
19
+
20
+ readAt: string;
21
+ }
22
+ export type TonCodePins = Readonly<{ wallet: string; account: string; trader: string }>;
23
+
24
+ export { TON_PINNED_CODE_HASHES } from "./consts.generated.ts";
25
+
26
+ export class TonBookError extends Error {
27
+ readonly field: string;
28
+ readonly file: string;
29
+ constructor(file: string, field: string, what: string) {
30
+ super(`ton book ${file}: ${field}: ${what}`);
31
+ this.name = "TonBookError";
32
+ this.field = field;
33
+ this.file = file;
34
+ }
35
+ }
36
+
37
+ const HEX64 = /^[0-9a-fA-F]{64}$/;
38
+ const isObj = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
39
+ const HASH_NAMES = ["factory", "timelock", "launch", "wallet", "account", "trader"] as const;
40
+ const INIT_NAMES = ["launch", "account", "trader"] as const;
41
+ const CODE_NAMES = ["wallet", "account", "trader"] as const;
42
+
43
+ export function parseTonBook(json: unknown, opts: { file?: string; pins?: TonCodePins } = {}): TonBook {
44
+ const file = opts.file ?? "<memory>";
45
+ const pins: TonCodePins = opts.pins ?? GEN_HASHES;
46
+ const fail = (field: string, what: string): never => {
47
+ throw new TonBookError(file, field, what);
48
+ };
49
+ if (!isObj(json)) return fail("(root)", "not a JSON object");
50
+ if (json.chain !== "ton") fail("chain", 'must be "ton"');
51
+ const network = json.network;
52
+ if (network !== "mainnet" && network !== "testnet") fail("network", `must be "mainnet" or "testnet", got "${String(network)}"`);
53
+ const wantId = network === "mainnet" ? -239 : -3;
54
+ if (json.globalId !== wantId) fail("globalId", `${wantId} expected for ${String(network)}, got ${String(json.globalId)}`);
55
+ const rawAddr = (field: "factory" | "timelock"): Address => {
56
+ const v = json[field];
57
+ if (typeof v !== "string" || !/^0:[0-9a-fA-F]{64}$/.test(v)) return fail(field, 'not a workchain-0 raw address "0:<64 hex>"');
58
+ return Address.parse(v);
59
+ };
60
+ const factory = rawAddr("factory");
61
+ const timelock = rawAddr("timelock");
62
+ let deploySeqno: number | undefined;
63
+ if (json.deploySeqno !== undefined) {
64
+ const d = json.deploySeqno;
65
+ if (typeof d !== "number" || !Number.isInteger(d) || d < 1) fail("deploySeqno", "must be an integer of at least 1");
66
+ deploySeqno = d as number;
67
+ }
68
+ const ra = json.readAt;
69
+ const readAt = typeof ra === "string" ? ra : isObj(ra) && typeof ra.time === "string" ? ra.time : undefined;
70
+ if (readAt === undefined || !Number.isFinite(Date.parse(readAt))) fail("readAt", 'not an ISO timestamp (a string, or an object with "time")');
71
+ const ch = json.codeHashes;
72
+ const codeHashes: Record<string, string> = {};
73
+ for (const n of HASH_NAMES) {
74
+ const v = isObj(ch) ? ch[n] : undefined;
75
+ if (typeof v !== "string" || !HEX64.test(v)) fail(`codeHashes.${n}`, "not 64 hex");
76
+ codeHashes[n] = (v as string).toLowerCase();
77
+ }
78
+ const init: Record<string, string> = {};
79
+ const fi = json.familyInit;
80
+ if (fi !== undefined) {
81
+ for (const n of INIT_NAMES) {
82
+ const v = isObj(fi) ? fi[n] : undefined;
83
+ if (typeof v !== "string" || !HEX64.test(v)) fail(`familyInit.${n}`, "not 64 hex");
84
+ init[n] = (v as string).toLowerCase();
85
+ }
86
+ }
87
+ const initHashes = {
88
+ launch: init.launch ?? codeHashes.launch!,
89
+ wallet: codeHashes.wallet!,
90
+ account: init.account ?? codeHashes.account!,
91
+ trader: init.trader ?? codeHashes.trader!,
92
+ };
93
+ const rawCodes = json.codes;
94
+ if (rawCodes === undefined || rawCodes === null) fail("codes", "missing (a read-back book carries hashes only: add the three init code cells)");
95
+ const cells: Record<string, Cell> = {};
96
+ for (const n of CODE_NAMES) {
97
+ const v = isObj(rawCodes) ? rawCodes[n] : undefined;
98
+ let c: Cell | undefined;
99
+ if (typeof v === "string") {
100
+ try {
101
+ c = fromBoc(bytesOfBase64(v));
102
+ } catch {
103
+ c = undefined;
104
+ }
105
+ }
106
+ if (!c) return fail(`codes.${n}`, "not a base64 BoC with one root");
107
+ cells[n] = c;
108
+ }
109
+ for (const n of CODE_NAMES) {
110
+ const got = hexOf(cells[n]!.hash());
111
+ if (got !== initHashes[n]) fail(`codes.${n}`, `cell hash ${got} is not the book's ${n} init hash ${initHashes[n]}`);
112
+ }
113
+ for (const n of CODE_NAMES) {
114
+ const got = hexOf(cells[n]!.hash());
115
+ if (got !== pins[n].toLowerCase()) fail(`codes.${n}`, `${got} is not the pinned ${n} init code hash ${pins[n]} (a child address would move)`);
116
+ }
117
+ return {
118
+ network: network as "mainnet" | "testnet",
119
+ globalId: wantId as -239 | -3,
120
+ factory,
121
+ timelock,
122
+ ...(deploySeqno !== undefined ? { deploySeqno } : {}),
123
+ codeHashes: codeHashes as TonBook["codeHashes"],
124
+ initHashes,
125
+ codes: { wallet: cells.wallet!, account: cells.account!, trader: cells.trader! },
126
+ readAt: readAt as string,
127
+ };
128
+ }
129
+
130
+ export function tonChainOf(book?: TonBook): TonChain {
131
+ if (book) return { family: "ton", factory: book.factory, codes: { wallet: book.codes.wallet, account: book.codes.account, trader: book.codes.trader }, workchain: 0 };
132
+ const m = TON_MAINNET;
133
+ if (m.factory === null || m.timelock === null) throw new TonBookError("<built-in>", "factory", "TON mainnet factory is a placeholder (no deploy yet): pass a book, or regenerate the constants from the deploy output");
134
+ const code = (n: "wallet" | "account" | "trader"): Cell => fromBoc(bytesOfBase64(TON_INIT_CODES_BASE64[n]));
135
+ return { family: "ton", factory: Address.parse(m.factory), codes: { wallet: code("wallet"), account: code("account"), trader: code("trader") }, workchain: 0 };
136
+ }
@@ -0,0 +1,547 @@
1
+
2
+
3
+ import { sha256 } from "../sha256.ts";
4
+
5
+ function crcTable(poly: number, reflected: boolean): Uint32Array {
6
+ const t = new Uint32Array(256);
7
+ for (let i = 0; i < 256; i++) {
8
+ let c = reflected ? i : i << 24;
9
+ for (let k = 0; k < 8; k++) {
10
+ if (reflected) c = c & 1 ? (c >>> 1) ^ poly : c >>> 1;
11
+ else c = c & 0x80000000 ? (c << 1) ^ poly : c << 1;
12
+ }
13
+ t[i] = c >>> 0;
14
+ }
15
+ return t;
16
+ }
17
+ let T32: Uint32Array | undefined;
18
+ let T32C: Uint32Array | undefined;
19
+
20
+ export function crc32(data: Uint8Array | string): number {
21
+ const b = typeof data === "string" ? new TextEncoder().encode(data) : data;
22
+ const t = (T32 ??= crcTable(0xedb88320, true));
23
+ let c = 0xffffffff;
24
+ for (const x of b) c = t[(c ^ x) & 0xff]! ^ (c >>> 8);
25
+ return (c ^ 0xffffffff) >>> 0;
26
+ }
27
+
28
+ export function crc32c(data: Uint8Array): number {
29
+ const t = (T32C ??= crcTable(0x82f63b78, true));
30
+ let c = 0xffffffff;
31
+ for (const x of data) c = t[(c ^ x) & 0xff]! ^ (c >>> 8);
32
+ return (c ^ 0xffffffff) >>> 0;
33
+ }
34
+
35
+ export function crc16(data: Uint8Array | string): number {
36
+ const b = typeof data === "string" ? new TextEncoder().encode(data) : data;
37
+ let c = 0;
38
+ for (const x of b) {
39
+ c ^= x << 8;
40
+ for (let k = 0; k < 8; k++) c = c & 0x8000 ? ((c << 1) ^ 0x1021) & 0xffff : (c << 1) & 0xffff;
41
+ }
42
+ return c;
43
+ }
44
+
45
+ export const methodId = (name: string): number => (crc16(name) & 0xffff) | 0x10000;
46
+
47
+ export function hexOf(b: Uint8Array): string {
48
+ let s = "";
49
+ for (const x of b) s += x.toString(16).padStart(2, "0");
50
+ return s;
51
+ }
52
+ export function bytesOfHex(h: string): Uint8Array {
53
+ const s = h.startsWith("0x") ? h.slice(2) : h;
54
+ if (s.length % 2 !== 0 || /[^0-9a-fA-F]/.test(s)) throw new RangeError("bad hex");
55
+ const o = new Uint8Array(s.length / 2);
56
+ for (let i = 0; i < o.length; i++) o[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
57
+ return o;
58
+ }
59
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
60
+ export function base64Of(b: Uint8Array, urlSafe = false): string {
61
+ let s = "";
62
+ for (let i = 0; i < b.length; i += 3) {
63
+ const n = (b[i]! << 16) | ((b[i + 1] ?? 0) << 8) | (b[i + 2] ?? 0);
64
+ s += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + (i + 1 < b.length ? B64[(n >> 6) & 63]! : "=") + (i + 2 < b.length ? B64[n & 63]! : "=");
65
+ }
66
+ return urlSafe ? s.replace(/\+/g, "-").replace(/\//g, "_") : s;
67
+ }
68
+ export function bytesOfBase64(s: string): Uint8Array {
69
+ const t = s.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
70
+ const out: number[] = [];
71
+ let acc = 0;
72
+ let bits = 0;
73
+ for (const ch of t) {
74
+ const v = B64.indexOf(ch);
75
+ if (v < 0) throw new RangeError("bad base64");
76
+ acc = (acc << 6) | v;
77
+ bits += 6;
78
+ if (bits >= 8) {
79
+ bits -= 8;
80
+ out.push((acc >> bits) & 0xff);
81
+ }
82
+ }
83
+ return Uint8Array.from(out);
84
+ }
85
+
86
+ export class Address {
87
+ readonly workchain: number;
88
+ readonly hash: Uint8Array;
89
+ constructor(workchain: number, hash: Uint8Array) {
90
+ if (!Number.isInteger(workchain) || workchain < -128 || workchain > 127) throw new RangeError("workchain out of range");
91
+ if (hash.length !== 32) throw new RangeError("address hash must be 32 bytes");
92
+ this.workchain = workchain;
93
+ this.hash = hash.slice();
94
+ }
95
+ equals(o: Address): boolean {
96
+ return this.workchain === o.workchain && hexOf(this.hash) === hexOf(o.hash);
97
+ }
98
+
99
+ toRaw(): string {
100
+ return `${this.workchain}:${hexOf(this.hash)}`;
101
+ }
102
+
103
+ toString(o: { bounceable?: boolean; testOnly?: boolean; urlSafe?: boolean } = {}): string {
104
+ const tag = (o.testOnly ? 0x80 : 0) | (o.bounceable === false ? 0x51 : 0x11);
105
+ const b = new Uint8Array(36);
106
+ b[0] = tag;
107
+ b[1] = this.workchain & 0xff;
108
+ b.set(this.hash, 2);
109
+ const c = crc16(b.subarray(0, 34));
110
+ b[34] = c >> 8;
111
+ b[35] = c & 0xff;
112
+ return base64Of(b, o.urlSafe ?? true);
113
+ }
114
+ static parse(s: string): Address {
115
+ if (/^-?\d+:[0-9a-fA-F]{64}$/.test(s)) {
116
+ const [w, h] = s.split(":") as [string, string];
117
+ return new Address(Number(w), bytesOfHex(h));
118
+ }
119
+ if (s.length !== 48) throw new RangeError("bad address length");
120
+ const b = bytesOfBase64(s);
121
+ if (b.length !== 36) throw new RangeError("bad address length");
122
+ const c = crc16(b.subarray(0, 34));
123
+ if (b[34] !== c >> 8 || b[35] !== (c & 0xff)) throw new RangeError("bad address checksum");
124
+ const tag = b[0]! & ~0x80;
125
+ if (tag !== 0x11 && tag !== 0x51) throw new RangeError("bad address tag");
126
+ return new Address(b[1]! > 127 ? b[1]! - 256 : b[1]!, b.subarray(2, 34));
127
+ }
128
+ }
129
+
130
+ export const MAX_CELL_BITS = 1023;
131
+ export const MAX_CELL_REFS = 4;
132
+
133
+ export class Cell {
134
+ readonly bits: Uint8Array;
135
+ readonly len: number;
136
+ readonly refs: readonly Cell[];
137
+
138
+ readonly exotic: boolean;
139
+ #hash?: Uint8Array;
140
+ #depth?: number;
141
+ constructor(bits: Uint8Array, len: number, refs: readonly Cell[] = [], exotic = false) {
142
+ if (exotic && (len !== 264 || refs.length !== 0 || bits.length !== 33 || bits[0] !== 2)) {
143
+ throw new RangeError("exotic cell: only a library cell (type 2: 0x02 + 32-byte hash, no refs) is allowed");
144
+ }
145
+ if (len < 0 || len > MAX_CELL_BITS) throw new RangeError("cell over 1023 bits");
146
+ if (refs.length > MAX_CELL_REFS) throw new RangeError("cell over 4 refs");
147
+ if (bits.length !== Math.ceil(len / 8)) throw new RangeError("bits length mismatch");
148
+ this.bits = bits;
149
+ this.len = len;
150
+ this.refs = refs;
151
+ this.exotic = exotic;
152
+ }
153
+
154
+ #repr(): Uint8Array {
155
+ const dataBytes = Math.ceil(this.len / 8);
156
+ const out = new Uint8Array(2 + dataBytes);
157
+ out[0] = this.refs.length | (this.exotic ? 8 : 0);
158
+ out[1] = Math.ceil(this.len / 8) + Math.floor(this.len / 8);
159
+ out.set(this.bits, 2);
160
+ if (this.len % 8 !== 0) out[2 + dataBytes - 1] = out[2 + dataBytes - 1]! | (0x80 >> this.len % 8);
161
+ return out;
162
+ }
163
+ depth(): number {
164
+ if (this.#depth === undefined) this.#depth = this.refs.length === 0 ? 0 : 1 + Math.max(...this.refs.map((r) => r.depth()));
165
+ return this.#depth;
166
+ }
167
+ hash(): Uint8Array {
168
+ if (!this.#hash) {
169
+ const r = this.#repr();
170
+ const buf = new Uint8Array(r.length + this.refs.length * 34);
171
+ buf.set(r, 0);
172
+ let o = r.length;
173
+ for (const c of this.refs) {
174
+ const d = c.depth();
175
+ buf[o++] = d >> 8;
176
+ buf[o++] = d & 0xff;
177
+ }
178
+ for (const c of this.refs) {
179
+ buf.set(c.hash(), o);
180
+ o += 32;
181
+ }
182
+ this.#hash = sha256(buf);
183
+ }
184
+ return this.#hash.slice();
185
+ }
186
+ beginParse(): Slice {
187
+ if (this.exotic) throw new RangeError("a library cell has no readable data here: resolve the library (libraryHashOf gives its hash)");
188
+ return new Slice(this);
189
+ }
190
+ toBoc(o: { crc32?: boolean } = {}): Uint8Array {
191
+ return toBoc(this, o);
192
+ }
193
+ }
194
+
195
+ export const EMPTY_CELL = new Cell(new Uint8Array(0), 0);
196
+
197
+ export function libraryCell(hash: Uint8Array | string): Cell {
198
+ const h = typeof hash === "string" ? bytesOfHex(hash) : hash;
199
+ if (h.length !== 32) throw new RangeError("library hash must be 32 bytes");
200
+ const bits = new Uint8Array(33);
201
+ bits[0] = 2;
202
+ bits.set(h, 1);
203
+ return new Cell(bits, 264, [], true);
204
+ }
205
+ export const isLibraryCell = (c: Cell): boolean => c.exotic;
206
+
207
+ export function libraryHashOf(c: Cell): Uint8Array {
208
+ if (!c.exotic) throw new RangeError("not a library cell");
209
+ return c.bits.slice(1, 33);
210
+ }
211
+
212
+ export class Builder {
213
+ #bits: number[] = [];
214
+ #refs: Cell[] = [];
215
+ get bitLength(): number {
216
+ return this.#bits.length;
217
+ }
218
+ get refCount(): number {
219
+ return this.#refs.length;
220
+ }
221
+ #push(v: bigint, n: number): void {
222
+ if (this.#bits.length + n > MAX_CELL_BITS) throw new RangeError("cell over 1023 bits");
223
+ for (let i = n - 1; i >= 0; i--) this.#bits.push(Number((v >> BigInt(i)) & 1n));
224
+ }
225
+ storeBit(b: boolean | number | bigint): this {
226
+ this.#push(b ? 1n : 0n, 1);
227
+ return this;
228
+ }
229
+ storeUint(v: bigint | number, n: number): this {
230
+ const x = BigInt(v);
231
+ if (x < 0n || x >= 1n << BigInt(n)) throw new RangeError(`value ${x} does not fit uint${n}`);
232
+ this.#push(x, n);
233
+ return this;
234
+ }
235
+ storeInt(v: bigint | number, n: number): this {
236
+ const x = BigInt(v);
237
+ const lim = 1n << BigInt(n - 1);
238
+ if (x < -lim || x >= lim) throw new RangeError(`value ${x} does not fit int${n}`);
239
+ this.#push(BigInt.asUintN(n, x), n);
240
+ return this;
241
+ }
242
+ storeBytes(b: Uint8Array): this {
243
+ for (const x of b) this.storeUint(x, 8);
244
+ return this;
245
+ }
246
+
247
+ storeCoins(v: bigint | number): this {
248
+ const x = BigInt(v);
249
+ if (x < 0n || x >= 1n << 120n) throw new RangeError("coins out of range");
250
+ if (x === 0n) return this.storeUint(0, 4);
251
+ let n = 0;
252
+ for (let t = x; t > 0n; t >>= 8n) n++;
253
+ this.storeUint(n, 4);
254
+ return this.storeUint(x, n * 8);
255
+ }
256
+
257
+ storeAddress(a: Address | null | undefined): this {
258
+ if (!a) return this.storeUint(0, 2);
259
+ this.storeUint(2, 2).storeUint(0, 1).storeInt(a.workchain, 8);
260
+ return this.storeBytes(a.hash);
261
+ }
262
+ storeRef(c: Cell): this {
263
+ if (this.#refs.length >= MAX_CELL_REFS) throw new RangeError("cell over 4 refs");
264
+ this.#refs.push(c);
265
+ return this;
266
+ }
267
+
268
+ storeMaybeRef(c: Cell | null | undefined): this {
269
+ if (c) return this.storeBit(1).storeRef(c);
270
+ return this.storeBit(0);
271
+ }
272
+
273
+ storeMaybeAddress(a: Address | null | undefined): this {
274
+ if (a) return this.storeBit(1).storeAddress(a);
275
+ return this.storeBit(0);
276
+ }
277
+ storeBuilder(b: Builder): this {
278
+ for (const x of b.#bits) this.#push(BigInt(x), 1);
279
+ for (const r of b.#refs) this.storeRef(r);
280
+ return this;
281
+ }
282
+ endCell(): Cell {
283
+ const len = this.#bits.length;
284
+ const out = new Uint8Array(Math.ceil(len / 8));
285
+ for (let i = 0; i < len; i++) if (this.#bits[i]) out[i >> 3] = out[i >> 3]! | (0x80 >> (i & 7));
286
+ return new Cell(out, len, this.#refs.slice());
287
+ }
288
+ }
289
+
290
+ export const beginCell = (): Builder => new Builder();
291
+
292
+ export class Slice {
293
+ #cell: Cell;
294
+ #bit = 0;
295
+ #ref = 0;
296
+ constructor(c: Cell) {
297
+ this.#cell = c;
298
+ }
299
+ get remainingBits(): number {
300
+ return this.#cell.len - this.#bit;
301
+ }
302
+ get remainingRefs(): number {
303
+ return this.#cell.refs.length - this.#ref;
304
+ }
305
+ #take(n: number): bigint {
306
+ if (this.#bit + n > this.#cell.len) throw new RangeError("cell underflow");
307
+ let v = 0n;
308
+ for (let i = 0; i < n; i++) {
309
+ const p = this.#bit + i;
310
+ v = (v << 1n) | BigInt((this.#cell.bits[p >> 3]! >> (7 - (p & 7))) & 1);
311
+ }
312
+ this.#bit += n;
313
+ return v;
314
+ }
315
+ loadBit(): boolean {
316
+ return this.#take(1) === 1n;
317
+ }
318
+ loadUint(n: number): bigint {
319
+ return this.#take(n);
320
+ }
321
+ loadInt(n: number): bigint {
322
+ return BigInt.asIntN(n, this.#take(n));
323
+ }
324
+ loadBytes(n: number): Uint8Array {
325
+ const o = new Uint8Array(n);
326
+ for (let i = 0; i < n; i++) o[i] = Number(this.#take(8));
327
+ return o;
328
+ }
329
+ loadCoins(): bigint {
330
+ const n = Number(this.#take(4));
331
+ return n === 0 ? 0n : this.#take(n * 8);
332
+ }
333
+
334
+ loadAddress(): Address | null {
335
+ const t = Number(this.#take(2));
336
+ if (t === 0) return null;
337
+ if (t !== 2) throw new RangeError("unsupported address kind");
338
+ if (this.#take(1) === 1n) throw new RangeError("anycast not supported");
339
+ const wc = Number(this.loadInt(8));
340
+ return new Address(wc, this.loadBytes(32));
341
+ }
342
+ loadMaybeAddress(): Address | null {
343
+ return this.loadBit() ? this.loadAddress() : null;
344
+ }
345
+ loadRef(): Cell {
346
+ const c = this.#cell.refs[this.#ref++];
347
+ if (!c) throw new RangeError("ref underflow");
348
+ return c;
349
+ }
350
+ loadMaybeRef(): Cell | null {
351
+ return this.loadBit() ? this.loadRef() : null;
352
+ }
353
+
354
+ endParse(): void {
355
+ if (this.remainingBits !== 0 || this.remainingRefs !== 0) throw new RangeError("slice not fully read");
356
+ }
357
+ }
358
+
359
+ export function snakeCell(text: string): Cell {
360
+ const bytes = new TextEncoder().encode(text);
361
+ const chunks: Uint8Array[] = [];
362
+ for (let i = 0; i < bytes.length; i += 127) chunks.push(bytes.subarray(i, i + 127));
363
+ if (chunks.length === 0) chunks.push(new Uint8Array(0));
364
+ let next: Cell | null = null;
365
+ for (let i = chunks.length - 1; i >= 0; i--) {
366
+ const b = beginCell().storeBytes(chunks[i]!);
367
+ if (next) b.storeRef(next);
368
+ next = b.endCell();
369
+ }
370
+ return next!;
371
+ }
372
+ export function readSnake(c: Cell): string {
373
+ const parts: Uint8Array[] = [];
374
+ for (let cur: Cell | undefined = c; cur; cur = cur.refs[0]) parts.push(cur.bits.subarray(0, cur.len >> 3));
375
+ const all = new Uint8Array(parts.reduce((a, p) => a + p.length, 0));
376
+ let o = 0;
377
+ for (const p of parts) {
378
+ all.set(p, o);
379
+ o += p.length;
380
+ }
381
+ return new TextDecoder().decode(all);
382
+ }
383
+
384
+ interface Sorted {
385
+ cell: Cell;
386
+ refs: number[];
387
+ }
388
+
389
+ function sortCells(root: Cell): Sorted[] {
390
+ let pending: Cell[] = [root];
391
+ const all = new Map<string, { cell: Cell; refs: string[] }>();
392
+ const notPerm = new Set<string>();
393
+ const sorted: string[] = [];
394
+ while (pending.length > 0) {
395
+ const cells = pending;
396
+ pending = [];
397
+ for (const cell of cells) {
398
+ const h = hexOf(cell.hash());
399
+ if (all.has(h)) continue;
400
+ notPerm.add(h);
401
+ all.set(h, { cell, refs: cell.refs.map((r) => hexOf(r.hash())) });
402
+ for (const r of cell.refs) pending.push(r);
403
+ }
404
+ }
405
+ const visit = (h: string): void => {
406
+ if (!notPerm.has(h)) return;
407
+ const refs = all.get(h)!.refs;
408
+ for (let i = refs.length - 1; i >= 0; i--) visit(refs[i]!);
409
+ sorted.push(h);
410
+ notPerm.delete(h);
411
+ };
412
+ while (notPerm.size > 0) visit(notPerm.values().next().value as string);
413
+ const idx = new Map<string, number>();
414
+ for (let i = 0; i < sorted.length; i++) idx.set(sorted[sorted.length - i - 1]!, i);
415
+ const out: Sorted[] = [];
416
+ for (let i = sorted.length - 1; i >= 0; i--) {
417
+ const e = all.get(sorted[i]!)!;
418
+ out.push({ cell: e.cell, refs: e.refs.map((r) => idx.get(r)!) });
419
+ }
420
+ return out;
421
+ }
422
+
423
+ const bytesFor = (n: number): number => Math.max(Math.ceil(n.toString(2).length / 8), 1);
424
+
425
+ export function toBoc(root: Cell, o: { crc32?: boolean } = {}): Uint8Array {
426
+ const crc = o.crc32 ?? true;
427
+ const cells = sortCells(root);
428
+ const size = bytesFor(cells.length);
429
+ let total = 0;
430
+ for (const c of cells) total += 2 + c.cell.bits.length + c.refs.length * size;
431
+ const off = bytesFor(total);
432
+ const head = 4 + 1 + 1 + 3 * size + off + size;
433
+ const out = new Uint8Array(head + total + (crc ? 4 : 0));
434
+ let p = 0;
435
+ const put = (v: number, n: number): void => {
436
+ for (let i = n - 1; i >= 0; i--) out[p++] = Math.floor(v / 2 ** (8 * i)) & 0xff;
437
+ };
438
+ put(0xb5ee9c72, 4);
439
+ put((crc ? 0x40 : 0) | size, 1);
440
+ put(off, 1);
441
+ put(cells.length, size);
442
+ put(1, size);
443
+ put(0, size);
444
+ put(total, off);
445
+ put(0, size);
446
+ for (const { cell, refs } of cells) {
447
+ out[p++] = cell.refs.length | (cell.exotic ? 8 : 0);
448
+ out[p++] = Math.ceil(cell.len / 8) + Math.floor(cell.len / 8);
449
+ const data = cell.bits.slice();
450
+ if (cell.len % 8 !== 0) data[data.length - 1] = data[data.length - 1]! | (0x80 >> cell.len % 8);
451
+ out.set(data, p);
452
+ p += data.length;
453
+ for (const r of refs) put(r, size);
454
+ }
455
+ if (crc) {
456
+ const c = crc32c(out.subarray(0, p));
457
+
458
+ out[p++] = c & 0xff;
459
+ out[p++] = (c >>> 8) & 0xff;
460
+ out[p++] = (c >>> 16) & 0xff;
461
+ out[p++] = (c >>> 24) & 0xff;
462
+ }
463
+ return out;
464
+ }
465
+
466
+ export function fromBoc(b: Uint8Array): Cell {
467
+ let p = 0;
468
+ const get = (n: number): number => {
469
+ if (p + n > b.length) throw new RangeError("BoC truncated");
470
+ let v = 0;
471
+ for (let i = 0; i < n; i++) v = v * 256 + b[p++]!;
472
+ return v;
473
+ };
474
+ if (get(4) !== 0xb5ee9c72) throw new RangeError("bad BoC magic");
475
+ const flags = get(1);
476
+ const hasIdx = (flags & 0x80) !== 0;
477
+ const hasCrc = (flags & 0x40) !== 0;
478
+ const size = flags & 7;
479
+ if (size < 1 || size > 4) throw new RangeError("BoC bad size");
480
+ const off = get(1);
481
+ if (off < 1 || off > 6) throw new RangeError("BoC bad offset size");
482
+ const n = get(size);
483
+ const roots = get(size);
484
+ get(size);
485
+ const total = get(off);
486
+ if (roots !== 1) throw new RangeError("BoC must have one root");
487
+ if (n < 1 || n > b.length) throw new RangeError("BoC bad cell count");
488
+ const rootIdx = get(size);
489
+ if (rootIdx >= n) throw new RangeError("BoC bad root");
490
+ if (hasIdx) {
491
+ if (p + n * off > b.length) throw new RangeError("BoC truncated");
492
+ p += n * off;
493
+ }
494
+ const end = p + total;
495
+ if (end > b.length) throw new RangeError("BoC truncated");
496
+ const raw: { bits: Uint8Array; len: number; refs: number[]; exotic: boolean }[] = [];
497
+ while (p < end) {
498
+ const d1 = get(1);
499
+ const d2 = get(1);
500
+ const exotic = (d1 & 8) !== 0;
501
+ if (exotic && ((d1 & 7) !== 0 || d1 >> 5 !== 0 || d2 !== 66)) {
502
+ throw new RangeError("exotic cell type " + (p < end ? b[p]! : "?") + " is refused: only a library cell (type 2) is allowed");
503
+ }
504
+ if ((d1 & 7) > 4) throw new RangeError("BoC bad ref count");
505
+ const nb = Math.ceil(d2 / 2);
506
+ if (p + nb > end) throw new RangeError("BoC truncated");
507
+ const data = b.slice(p, p + nb);
508
+ p += nb;
509
+ let len = nb * 8;
510
+ if (d2 & 1) {
511
+ const last = data[nb - 1]!;
512
+ if (last === 0) throw new RangeError("BoC bad completion tag");
513
+ let t = 0;
514
+ while (((last >> t) & 1) === 0) t++;
515
+ len = nb * 8 - t - 1;
516
+ data[nb - 1] = last & ~(1 << t) & 0xff;
517
+ }
518
+ const refs: number[] = [];
519
+ for (let i = 0; i < (d1 & 7); i++) refs.push(get(size));
520
+ if (p > end) throw new RangeError("BoC truncated");
521
+ if (exotic && (len !== 264 || data[0] !== 2)) throw new RangeError(`exotic cell type ${data[0]} is refused: only a library cell (type 2) is allowed`);
522
+ raw.push({ bits: data.subarray(0, Math.ceil(len / 8)), len, refs, exotic });
523
+ }
524
+ if (raw.length !== n) throw new RangeError("BoC cell count mismatch");
525
+ if (hasCrc) {
526
+ if (p + 4 > b.length) throw new RangeError("BoC truncated");
527
+ const want = (b[p]! | (b[p + 1]! << 8) | (b[p + 2]! << 16) | (b[p + 3]! << 24)) >>> 0;
528
+ if (crc32c(b.subarray(0, p)) !== want) throw new RangeError("BoC crc32c mismatch");
529
+ }
530
+ const built: Cell[] = new Array(n);
531
+ for (let i = n - 1; i >= 0; i--) {
532
+ const r = raw[i]!;
533
+ built[i] = new Cell(r.bits.slice(), r.len, r.refs.map((x) => {
534
+ if (x <= i || x >= n) throw new RangeError("BoC refs not forward");
535
+ return built[x]!;
536
+ }), r.exotic);
537
+ }
538
+ return built[rootIdx]!;
539
+ }
540
+
541
+ export function stateInitCell(code: Cell, data: Cell): Cell {
542
+ return beginCell().storeBit(0).storeBit(0).storeBit(1).storeRef(code).storeBit(1).storeRef(data).storeBit(0).endCell();
543
+ }
544
+
545
+ export function contractAddress(code: Cell, data: Cell, workchain = 0): Address {
546
+ return new Address(workchain, stateInitCell(code, data).hash());
547
+ }