@floorlaunchpad/sdk 0.4.1 → 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 (77) hide show
  1. package/CHANGELOG.md +83 -18
  2. package/README.md +0 -2
  3. package/dist/abi/functions.gen.js +1 -1
  4. package/dist/config/generated.js +77 -0
  5. package/dist/evm/chains.js +1 -24
  6. package/dist/evm/router.js +1 -25
  7. package/dist/evm/squid.js +3 -3
  8. package/dist/index.js +1 -0
  9. package/dist/indexer/bodies.js +4 -0
  10. package/dist/math/v2/book.js +40 -7
  11. package/dist/math/v2/create.js +1 -1
  12. package/dist/math/v2/relay.js +201 -1
  13. package/dist/math/v2/split.js +60 -15
  14. package/dist/math/v2/trade.js +16 -8
  15. package/dist/ton/addresses.js +36 -0
  16. package/dist/ton/book-check.js +23 -0
  17. package/dist/ton/book.js +119 -0
  18. package/dist/ton/cell.js +542 -0
  19. package/dist/ton/consts.generated.js +17 -0
  20. package/dist/ton/content.js +83 -0
  21. package/dist/ton/gas.js +198 -0
  22. package/dist/ton/governance.js +401 -0
  23. package/dist/ton/index.js +18 -0
  24. package/dist/ton/messages.js +340 -0
  25. package/dist/ton/ops.js +37 -0
  26. package/dist/ton/price.js +51 -0
  27. package/dist/ton/quote-entry.js +116 -0
  28. package/dist/ton/quote.js +25 -0
  29. package/dist/ton/reader.js +378 -0
  30. package/dist/ton/types.js +43 -0
  31. package/dist/ton/wallet.js +26 -0
  32. package/dist/v2/evm.js +3 -1
  33. package/dist/v2/layouts.js +5 -1
  34. package/dist/v2/router.js +2 -2
  35. package/dist/v2/solanaSettle.js +2 -0
  36. package/docs/aggregator.md +0 -22
  37. package/docs/bot.md +0 -8
  38. package/docs/cursor-pages.md +0 -2
  39. package/docs/frontend.md +0 -2
  40. package/docs/ton.md +107 -0
  41. package/docs/wallet.md +0 -2
  42. package/examples/floor-line.html +1 -1
  43. package/package.json +6 -1
  44. package/src/abi/functions.gen.ts +1 -1
  45. package/src/config/generated.ts +77 -0
  46. package/src/evm/chains.ts +3 -28
  47. package/src/evm/router.ts +1 -26
  48. package/src/evm/squid.ts +3 -3
  49. package/src/index.ts +1 -0
  50. package/src/indexer/bodies.ts +4 -0
  51. package/src/math/v2/book.ts +42 -7
  52. package/src/math/v2/create.ts +1 -1
  53. package/src/math/v2/relay.ts +208 -1
  54. package/src/math/v2/split.ts +70 -16
  55. package/src/math/v2/trade.ts +16 -8
  56. package/src/ton/addresses.ts +38 -0
  57. package/src/ton/book-check.ts +24 -0
  58. package/src/ton/book.ts +136 -0
  59. package/src/ton/cell.ts +547 -0
  60. package/src/ton/consts.generated.ts +17 -0
  61. package/src/ton/content.ts +97 -0
  62. package/src/ton/gas.ts +209 -0
  63. package/src/ton/governance.ts +452 -0
  64. package/src/ton/index.ts +18 -0
  65. package/src/ton/messages.ts +343 -0
  66. package/src/ton/ops.ts +37 -0
  67. package/src/ton/price.ts +54 -0
  68. package/src/ton/quote-entry.ts +138 -0
  69. package/src/ton/quote.ts +67 -0
  70. package/src/ton/reader.ts +420 -0
  71. package/src/ton/types.ts +201 -0
  72. package/src/ton/wallet.ts +30 -0
  73. package/src/v2/evm.ts +5 -1
  74. package/src/v2/layouts.ts +5 -1
  75. package/src/v2/router.ts +2 -2
  76. package/src/v2/solanaSettle.ts +2 -0
  77. package/src/v2/types.ts +4 -1
@@ -0,0 +1,198 @@
1
+
2
+
3
+ export const TON_MAINNET_GAS_CONFIG = {
4
+ gasPrice: 400n,
5
+ flatGasLimit: 100n,
6
+ flatGasPrice: 40_000n,
7
+ lumpPrice: 400_000n,
8
+ bitPrice: 26_214_400n,
9
+ cellPrice: 2_621_440_000n,
10
+ storageBitPs: 1n,
11
+ storageCellPs: 500n,
12
+ };
13
+
14
+ export const TON_CLAIM_COST_CONSTS = {
15
+ CLAIM_UNITS: 30000n,
16
+ LAUNCH_CLAIM_UNITS: 200000n,
17
+ QUOTE_HOP_UNITS: 60000n,
18
+ BOOK_UNITS: 15000n,
19
+ PAYOUT_NOTIFY_UNITS: 20000n,
20
+ HOP_MSG_BITS: 1400n,
21
+ HOP_MSG_CELLS: 4n,
22
+ ACCOUNT_STATE_BITS: 33200n,
23
+ ACCOUNT_STATE_CELLS: 68n,
24
+ LAUNCH_STATE_BITS: 843700n,
25
+ LAUNCH_STATE_CELLS: 1303n,
26
+ QUOTE_STATE_BITS: 20000n,
27
+ QUOTE_STATE_CELLS: 50n,
28
+ RENT_SECONDS: 31536000n,
29
+ QUOTE_RENT_SECONDS: 157680000n,
30
+ WALLET_SEND_GAS: 22100n,
31
+ WALLET_RECEIVE_GAS: 20800n,
32
+ WALLET_INDEX_GAS: 9300n,
33
+ LAUNCH_DELTA_GAS: 13600n,
34
+ DELTA_MSG_BITS: 800n,
35
+ DELTA_MSG_CELLS: 2n,
36
+ INDEX_MSG_BITS: 1100n,
37
+ INDEX_MSG_CELLS: 2n,
38
+ INIT_STATE_BITS: 29000n,
39
+ INIT_STATE_CELLS: 58n,
40
+ WALLET_STORAGE_BITS: 29000n,
41
+ WALLET_STORAGE_CELLS: 58n,
42
+ MIN_STORAGE_SECONDS: 157680000n,
43
+ TRADER_UNITS: 17300n,
44
+ LAUNCH_BURN_GAS: 163100n,
45
+ LAUNCH_SELL_RETURN_GAS: 80000n,
46
+ SELL_MSG_BITS: 3200n,
47
+ SELL_MSG_CELLS: 8n,
48
+ CREATE_UNITS: 325400n,
49
+ SETUP_UNITS: 1500000n,
50
+ UPGRADE_UNITS: 150000n,
51
+ CHILD_UPGRADE_UNITS: 40000n,
52
+ FACTORY_OP_UNITS: 60000n,
53
+ FAN_UNITS: 200000n,
54
+ GAS_PAYOUT_FWD_MIN: 60_000_000n,
55
+ GAS_BUY_FWD_MIN: 120000000n,
56
+ TRADE_UNITS: 1000000n,
57
+ TEAM_SHARE_BOOKS: 8n,
58
+ TEAM_SHARE_REF_BOOKS: 11n,
59
+ } ;
60
+ const K = TON_CLAIM_COST_CONSTS;
61
+
62
+ const ceilDiv = (a , b ) => (a + b - 1n) / b;
63
+ const max = (a , b ) => (a > b ? a : b);
64
+
65
+ export const CLAIM_GAS_MARGIN_NUM = 3n;
66
+ export const CLAIM_GAS_MARGIN_DEN = 2n;
67
+
68
+ const gasCost = (c , units ) => (units <= c.flatGasLimit ? c.flatGasPrice : c.flatGasPrice + (units - c.flatGasLimit) * c.gasPrice);
69
+ const fwdNoLump = (c , bits , cells ) => ceilDiv(c.bitPrice * bits + c.cellPrice * cells, 65536n);
70
+ const fwdCost = (c , bits , cells ) => c.lumpPrice + fwdNoLump(c, bits, cells);
71
+ const rentCost = (c , seconds , bits , cells ) => ceilDiv((bits * c.storageBitPs + cells * c.storageCellPs) * seconds, 65536n);
72
+
73
+ export function hopFwd(c = TON_MAINNET_GAS_CONFIG) { return fwdCost(c, K.HOP_MSG_BITS, K.HOP_MSG_CELLS); }
74
+ export function bookValue(c = TON_MAINNET_GAS_CONFIG) {
75
+ return gasCost(c, K.BOOK_UNITS) + rentCost(c, K.RENT_SECONDS, K.ACCOUNT_STATE_BITS, K.ACCOUNT_STATE_CELLS);
76
+ }
77
+ export function deltaCost(c = TON_MAINNET_GAS_CONFIG) {
78
+ return fwdCost(c, K.DELTA_MSG_BITS, K.DELTA_MSG_CELLS) + gasCost(c, K.LAUNCH_DELTA_GAS) + fwdCost(c, K.INDEX_MSG_BITS, K.INDEX_MSG_CELLS) + gasCost(c, K.WALLET_INDEX_GAS);
79
+ }
80
+ export function jettonValue(c = TON_MAINNET_GAS_CONFIG) {
81
+ return gasCost(c, K.QUOTE_HOP_UNITS) + 3n * hopFwd(c) + fwdCost(c, K.QUOTE_STATE_BITS, K.QUOTE_STATE_CELLS)
82
+ + rentCost(c, K.QUOTE_RENT_SECONDS, K.QUOTE_STATE_BITS, K.QUOTE_STATE_CELLS);
83
+ }
84
+ export function tokensValue(c = TON_MAINNET_GAS_CONFIG) {
85
+ return 3n * hopFwd(c) + fwdNoLump(c, K.INIT_STATE_BITS, K.INIT_STATE_CELLS) + gasCost(c, K.WALLET_SEND_GAS) + gasCost(c, K.WALLET_RECEIVE_GAS)
86
+ + 2n * deltaCost(c) + rentCost(c, K.MIN_STORAGE_SECONDS, K.WALLET_STORAGE_BITS, K.WALLET_STORAGE_CELLS);
87
+ }
88
+ export function onwardValue(c = TON_MAINNET_GAS_CONFIG) { return max(jettonValue(c), tokensValue(c)); }
89
+ export function claimFwdValue(c = TON_MAINNET_GAS_CONFIG) {
90
+ const onward = onwardValue(c);
91
+ const payoutFwd = gasCost(c, K.PAYOUT_NOTIFY_UNITS) + hopFwd(c) + onward;
92
+ return gasCost(c, K.LAUNCH_CLAIM_UNITS) + onward + hopFwd(c) + max(payoutFwd, K.GAS_PAYOUT_FWD_MIN) + bookValue(c);
93
+ }
94
+ export function claimMinValue(c = TON_MAINNET_GAS_CONFIG) {
95
+ return gasCost(c, K.CLAIM_UNITS) + 2n * hopFwd(c) + claimFwdValue(c);
96
+ }
97
+
98
+ export function claimMinValueOf(relay , pays , c = TON_MAINNET_GAS_CONFIG) {
99
+ return relay && pays ? claimMinValue(c) + claimFwdValue(c) + hopFwd(c) : claimMinValue(c);
100
+ }
101
+
102
+ export function accountReserve(c = TON_MAINNET_GAS_CONFIG) {
103
+ return rentCost(c, K.RENT_SECONDS, K.ACCOUNT_STATE_BITS, K.ACCOUNT_STATE_CELLS);
104
+ }
105
+
106
+ export function bookSendValue(c = TON_MAINNET_GAS_CONFIG) {
107
+ return bookValue(c) + fwdCost(c, K.HOP_MSG_BITS + K.ACCOUNT_STATE_BITS, K.HOP_MSG_CELLS + K.ACCOUNT_STATE_CELLS);
108
+ }
109
+
110
+ export function reclaimMinValue(c = TON_MAINNET_GAS_CONFIG) {
111
+ return gasCost(c, K.CLAIM_UNITS) + 2n * hopFwd(c) + gasCost(c, K.QUOTE_HOP_UNITS)
112
+ + max(onwardValue(c) + hopFwd(c), gasCost(c, K.LAUNCH_CLAIM_UNITS) + hopFwd(c) + bookSendValue(c)) + accountReserve(c);
113
+ }
114
+
115
+ const HOLDER_BIT = 512;
116
+ const withMargin = (v ) => ceilDiv(v * CLAIM_GAS_MARGIN_NUM, CLAIM_GAS_MARGIN_DEN);
117
+
118
+ export function defaultClaimValue(types , c = TON_MAINNET_GAS_CONFIG) {
119
+ return withMargin(claimMinValueOf((types & HOLDER_BIT) !== 0, (types & ~HOLDER_BIT) !== 0, c));
120
+ }
121
+
122
+ export function defaultReclaimValue(c = TON_MAINNET_GAS_CONFIG) { return withMargin(reclaimMinValue(c)); }
123
+
124
+ export function teamShareBuyMinValue(referred , thenClaim , c = TON_MAINNET_GAS_CONFIG) {
125
+ const books = referred ? K.TEAM_SHARE_REF_BOOKS : K.TEAM_SHARE_BOOKS;
126
+ const need = gasCost(c, K.TRADE_UNITS) + books * bookSendValue(c) + hopFwd(c) + (thenClaim ? tokensValue(c) : 0n);
127
+ return max(need, K.GAS_BUY_FWD_MIN) + (referred ? traderMinValue(c) : 0n);
128
+ }
129
+
130
+ export function defaultTeamShareBuyValue(referred , thenClaim , c = TON_MAINNET_GAS_CONFIG) {
131
+ return withMargin(teamShareBuyMinValue(referred, thenClaim, c));
132
+ }
133
+
134
+ export function traderMinValue(c = TON_MAINNET_GAS_CONFIG) { return gasCost(c, K.TRADER_UNITS) + hopFwd(c); }
135
+
136
+ export function traderDeployValue(c = TON_MAINNET_GAS_CONFIG) { return gasCost(c, K.TRADER_UNITS) + accountReserve(c); }
137
+
138
+ export function traderDeploySend(c = TON_MAINNET_GAS_CONFIG) {
139
+ return traderDeployValue(c) + fwdCost(c, K.HOP_MSG_BITS + K.ACCOUNT_STATE_BITS, K.HOP_MSG_CELLS + K.ACCOUNT_STATE_CELLS);
140
+ }
141
+
142
+ export function fallbackMinValue(c = TON_MAINNET_GAS_CONFIG) { return 2n * traderMinValue(c) + traderDeploySend(c); }
143
+
144
+ export function refChainValue(c = TON_MAINNET_GAS_CONFIG) { return 2n * traderMinValue(c); }
145
+
146
+ export function burnNeed(origFwd , c = TON_MAINNET_GAS_CONFIG) {
147
+ return gasCost(c, K.WALLET_SEND_GAS) + origFwd + gasCost(c, K.LAUNCH_BURN_GAS) + deltaCost(c);
148
+ }
149
+
150
+ export function transferBase(c = TON_MAINNET_GAS_CONFIG) { return tokensValue(c) - 3n * hopFwd(c); }
151
+
152
+ export function transferNeed(forwardTon , fwdCount , origFwd , c = TON_MAINNET_GAS_CONFIG) {
153
+ return forwardTon + fwdCount * origFwd + transferBase(c);
154
+ }
155
+
156
+ export function sellReturnMinFrom(origFwd , c = TON_MAINNET_GAS_CONFIG) {
157
+ return gasCost(c, K.LAUNCH_SELL_RETURN_GAS) + 3n * origFwd + transferBase(c);
158
+ }
159
+
160
+ export function sellReturnMin(c = TON_MAINNET_GAS_CONFIG) {
161
+ return sellReturnMinFrom(fwdCost(c, K.SELL_MSG_BITS, K.SELL_MSG_CELLS), c);
162
+ }
163
+
164
+ export function teamBurnValue(c = TON_MAINNET_GAS_CONFIG) {
165
+ return gasCost(c, K.WALLET_SEND_GAS + K.LAUNCH_BURN_GAS) + 2n * hopFwd(c);
166
+ }
167
+
168
+ export function launchReserve(c = TON_MAINNET_GAS_CONFIG) {
169
+ return rentCost(c, K.RENT_SECONDS, K.LAUNCH_STATE_BITS, K.LAUNCH_STATE_CELLS);
170
+ }
171
+
172
+ export function createGas(c = TON_MAINNET_GAS_CONFIG) {
173
+ return gasCost(c, K.CREATE_UNITS) + 2n * fwdCost(c, K.LAUNCH_STATE_BITS, K.LAUNCH_STATE_CELLS);
174
+ }
175
+
176
+ export function launchSetupMin(c = TON_MAINNET_GAS_CONFIG) {
177
+ return gasCost(c, K.SETUP_UNITS) + 2n * jettonValue(c) + launchReserve(c);
178
+ }
179
+
180
+ export function createMinValue(createFee , teamBuyMoney , c = TON_MAINNET_GAS_CONFIG) {
181
+ return createFee + teamBuyMoney + createGas(c) + launchSetupMin(c);
182
+ }
183
+
184
+ export function pushEach(c = TON_MAINNET_GAS_CONFIG) {
185
+ return gasCost(c, K.UPGRADE_UNITS) + hopFwd(c) + fwdCost(c, K.LAUNCH_STATE_BITS, K.LAUNCH_STATE_CELLS);
186
+ }
187
+
188
+ export function childEach(c = TON_MAINNET_GAS_CONFIG) {
189
+ return gasCost(c, K.CHILD_UPGRADE_UNITS) + hopFwd(c) + fwdCost(c, K.ACCOUNT_STATE_BITS, K.ACCOUNT_STATE_CELLS);
190
+ }
191
+
192
+ export function pushChildMin(family , n , c = TON_MAINNET_GAS_CONFIG) {
193
+ if (family !== 3 && family !== 4) throw new RangeError("family: 3 (account) or 4 (trader)");
194
+ if (!Number.isInteger(n) || n < 1 || n > 32) throw new RangeError("owners: 1..32");
195
+ const factoryGas = gasCost(c, K.FACTORY_OP_UNITS) + hopFwd(c);
196
+ const each = BigInt(n) * childEach(c);
197
+ return family === 4 ? each + factoryGas : each + gasCost(c, K.FAN_UNITS) + pushEach(c) + factoryGas;
198
+ }
@@ -0,0 +1,401 @@
1
+
2
+
3
+ import { Address, beginCell, bytesOfBase64, bytesOfHex, Cell, fromBoc, hexOf, snakeCell } from "./cell.js";
4
+
5
+ import { addr } from "./addresses.js";
6
+ import { op as opcodeOf } from "./ops.js";
7
+ import { decodeRowV2 } from "../math/v2/preset.js";
8
+
9
+ export class TonGovDecodeError extends Error {
10
+ constructor(m ) {
11
+ super(m);
12
+ this.name = "TonGovDecodeError";
13
+ }
14
+ }
15
+
16
+ const AUTH = "authority";
17
+ const TL = "timelock";
18
+ const GOV = "timelock / governance";
19
+
20
+ export const TON_GOV_SPEC = {
21
+ transfer_authority: { to: "FloorFactory", from: AUTH, fields: [["new_authority", "MsgAddressInt", "addrInt"]] },
22
+ accept_authority: { to: "FloorFactory", from: "pending authority", fields: [] },
23
+ set_timelock: { to: "FloorFactory", from: AUTH, fields: [["timelock", "MsgAddressInt", "addrInt"]] },
24
+ set_create_paused: { to: "FloorFactory", from: "governance multisig (short delay)", fields: [["paused", "Bool", "bool"]] },
25
+ set_treasury: { to: "FloorFactory", from: TL, fields: [["treasury", "MsgAddressInt", "addrInt"]] },
26
+ set_native_create_fee: { to: "FloorFactory", from: AUTH, fields: [["fee", "Coins", "gram"]] },
27
+ set_metadata_base: { to: "FloorFactory", from: AUTH, fields: [["base", "^SnakeString", "snake"]] },
28
+ set_referral_authority: { to: "FloorFactory", from: AUTH, fields: [["pubkey", "uint256", "pubkey"]] },
29
+ set_holder_dest: { to: "FloorFactory", from: AUTH, fields: [["dest", "MsgAddressInt", "addrInt"]] },
30
+ add_preset: { to: "FloorFactory", from: AUTH, fields: [["id", "uint32", "u32"], ["row", "^PresetRow", "presetRow"]] },
31
+ update_preset: { to: "FloorFactory", from: AUTH, fields: [["id", "uint32", "u32"], ["row", "^PresetRow", "presetRow"]] },
32
+ set_preset_enabled: { to: "FloorFactory", from: AUTH, fields: [["id", "uint32", "u32"], ["enabled", "Bool", "bool"]] },
33
+ delete_preset: { to: "FloorFactory", from: AUTH, fields: [["id", "uint32", "u32"]] },
34
+ add_quote: { to: "FloorFactory", from: AUTH, fields: [["row", "^QuoteEntry", "quoteEntry"]] },
35
+ set_quote_cap: { to: "FloorFactory", from: AUTH, fields: [["quote", "MsgAddress", "addr"], ["cap", "Coins", "quoteCoins"]] },
36
+ update_quote: { to: "FloorFactory", from: AUTH, fields: [["row", "^QuoteEntry", "quoteEntry"]] },
37
+ set_quote_creates: {
38
+ to: "FloorFactory", from: "governance multisig (short delay)", fields: [["quote", "MsgAddress", "addr"], ["enabled", "Bool", "bool"]],
39
+ },
40
+ set_price_updater: { to: "FloorFactory", from: AUTH, fields: [["pubkey", "uint256", "pubkey"]] },
41
+ withdraw_platform: { to: "FloorFactory", from: GOV, fields: [["launch_ids", "^Cell", "launchIds"]] },
42
+ withdraw_holder: { to: "FloorFactory", from: GOV, fields: [["launch_ids", "^Cell", "launchIds"]] },
43
+ pull_bucket: {
44
+ to: "FloorLaunch", from: "FloorFactory only", fields: [["bucket", "uint8", "u8"], ["to", "MsgAddressInt", "addrInt"]],
45
+ },
46
+ push_upgrade: { to: "FloorFactory", from: "any", fields: [["from_id", "uint64", "u64"], ["count", "uint16", "u16"]] },
47
+ upgrade_code: {
48
+ to: "FloorLaunch | FloorAccount | FloorTrader",
49
+ from: "FloorLaunch, FloorTrader: FloorFactory only; FloorAccount: its launch only (relay_code); only the scheduled code (code_hash = cell_hash(code), else NotAuthority)",
50
+ fields: [["version", "uint32", "u32"], ["code_hash", "uint256", "hash"], ["code", "^Cell", "code"], ["migrate", "(Maybe ^Cell)", "maybeCell"]],
51
+ },
52
+ schedule: { to: "FloorTimelock", from: "the multisig v2 admin", fields: [["action", "^Cell", "action"], ["eta", "uint32", "u32"]] },
53
+ execute: { to: "FloorTimelock", from: "any after eta", fields: [["action_hash", "uint256", "hash"]] },
54
+ cancel: { to: "FloorTimelock", from: "the multisig v2 admin", fields: [["action_hash", "uint256", "hash"]] },
55
+ set_code: {
56
+ to: "FloorFactory", from: TL, fields: [["family", "uint8", "u8"], ["version", "uint32", "u32"], ["code", "^Cell", "code"]],
57
+ },
58
+ update_delay: { to: "FloorTimelock", from: "the timelock itself (a scheduled self action)", fields: [["delay", "uint32", "u32"]] },
59
+ set_admin: { to: "FloorTimelock", from: "the timelock itself (a scheduled self action)", fields: [["admin", "MsgAddressInt", "addrInt"]] },
60
+ accept_admin: { to: "FloorTimelock", from: "the pending admin (set by a scheduled set_admin)", fields: [] },
61
+ push_child_code: {
62
+ to: "FloorFactory", from: "any",
63
+ fields: [["family", "uint8", "u8"], ["launch_id", "uint64", "u64"], ["owners", "^AddrList", "addrList"]],
64
+ },
65
+ relay_code: {
66
+ to: "FloorLaunch", from: "FloorFactory only",
67
+ fields: [["version", "uint32", "u32"], ["code_hash", "uint256", "hash"], ["code", "^Cell", "code"], ["owners", "^AddrList", "addrList"]],
68
+ },
69
+ } ;
70
+
71
+ export const TON_GOV_OPS = Object.keys(TON_GOV_SPEC) ;
72
+
73
+ export const TON_GRAM_DECIMALS = 9;
74
+ const FAMILY = ["factory", "launch", "launch-token wallet", "account", "trader"] ;
75
+ const BUCKET = ["platform → treasury", "holder → holder_dest"] ;
76
+
77
+ export function tonFormatUnits(v , decimals ) {
78
+ if (decimals === 0) return v.toString();
79
+ const s = v.toString().padStart(decimals + 1, "0");
80
+ const int = s.slice(0, -decimals);
81
+ const frac = s.slice(-decimals).replace(/0+$/, "");
82
+ return frac ? `${int}.${frac}` : int;
83
+ }
84
+ const hex64 = (v ) => v.toString(16).padStart(64, "0");
85
+ const cellHash = (c ) => hexOf(c.hash());
86
+ const addrText = (a ) => (a ? a.toString({ bounceable: true }) : "addr_none");
87
+
88
+ const MAX = { u8: 0xffn, u16: 0xffffn, u32: 0xffffffffn, u64: (1n << 64n) - 1n, u256: (1n << 256n) - 1n } ;
89
+ function uint(v , bits , what ) {
90
+ const b = BigInt(v);
91
+ const max = { 8: MAX.u8, 16: MAX.u16, 32: MAX.u32, 64: MAX.u64, 256: MAX.u256 }[bits];
92
+ if (b < 0n || b > max) throw new RangeError(`${what} out of uint${bits} range`);
93
+ return b;
94
+ }
95
+ function coins(v , what ) {
96
+ if (v < 0n || v >= 1n << 120n) throw new RangeError(`${what} out of Coins range`);
97
+ return v;
98
+ }
99
+
100
+ export function tonPresetRowCell(bytes ) {
101
+ let next = null;
102
+ for (let off = Math.floor(Math.max(bytes.length - 1, 0) / 127) * 127; off >= 0; off -= 127) {
103
+ const b = beginCell().storeBytes(bytes.subarray(off, off + 127));
104
+ if (next) b.storeRef(next);
105
+ next = b.endCell();
106
+ }
107
+ return next ;
108
+ }
109
+
110
+ export function tonQuoteEntryCell(e ) {
111
+ if (e.kind !== 0 && e.kind !== 1) throw new RangeError("quote kind is 0 (native) or 1 (jetton)");
112
+ return beginCell()
113
+ .storeUint(e.kind, 1)
114
+ .storeAddress(e.master)
115
+ .storeUint(uint(e.decimals, 8, "decimals"), 8)
116
+ .storeUint(uint(e.walletKind, 8, "wallet_kind"), 8)
117
+ .storeUint(uint(e.walletCodeHash, 256, "wallet_code_hash"), 256)
118
+ .storeMaybeRef(e.walletCode)
119
+ .storeCoins(coins(e.createFee, "create_fee"))
120
+ .storeBit(e.issuerCanFreeze)
121
+ .storeBit(e.createsEnabled)
122
+ .storeCoins(coins(e.cap, "cap"))
123
+ .endCell();
124
+ }
125
+
126
+ export function tonLaunchIdsCell(ids ) {
127
+ if (ids.length === 0) throw new RangeError("launch_ids is empty");
128
+ if (ids.length > 250) throw new RangeError("launch_ids holds at most 250 ids (PUSH_BATCH_MAX)");
129
+ let next = null;
130
+ for (let off = Math.floor((ids.length - 1) / 15) * 15; off >= 0; off -= 15) {
131
+ const b = beginCell();
132
+ for (const id of ids.slice(off, off + 15)) b.storeUint(uint(id, 64, "launch id"), 64);
133
+ if (next) b.storeRef(next);
134
+ next = b.endCell();
135
+ }
136
+ return next ;
137
+ }
138
+
139
+ export function tonAddrListCell(list ) {
140
+ if (list.length === 0) throw new RangeError("owners is empty");
141
+ if (list.length > 32) throw new RangeError("owners holds at most 32 addresses");
142
+ let next = null;
143
+ for (let off = Math.floor((list.length - 1) / 3) * 3; off >= 0; off -= 3) {
144
+ const part = list.slice(off, off + 3).map(addr);
145
+ const b = beginCell().storeUint(part.length, 2).storeAddress(part[0] );
146
+ b.storeMaybeAddress(part[1] ?? null).storeMaybeAddress(part[2] ?? null);
147
+ b.storeMaybeRef(next);
148
+ next = b.endCell();
149
+ }
150
+ return next ;
151
+ }
152
+
153
+ function storeField(b , k , v , name ) {
154
+ switch (k) {
155
+ case "u8": b.storeUint(uint(v , 8, name), 8); return;
156
+ case "u16": b.storeUint(uint(v , 16, name), 16); return;
157
+ case "u32": b.storeUint(uint(v , 32, name), 32); return;
158
+ case "u64": b.storeUint(uint(v , 64, name), 64); return;
159
+ case "u256": case "hash": case "pubkey": b.storeUint(uint(v , 256, name), 256); return;
160
+ case "bool": b.storeBit(v ); return;
161
+ case "addrInt": b.storeAddress(addr(v )); return;
162
+ case "addr": b.storeAddress(v == null ? null : addr(v )); return;
163
+ case "gram": case "quoteCoins": b.storeCoins(coins(v , name)); return;
164
+ case "snake": b.storeRef(snakeCell(v )); return;
165
+ case "presetRow": decodeRowV2(v ); b.storeRef(tonPresetRowCell(v )); return;
166
+ case "quoteEntry": b.storeRef(tonQuoteEntryCell(v )); return;
167
+ case "launchIds": b.storeRef(tonLaunchIdsCell(v )); return;
168
+ case "addrList": b.storeRef(tonAddrListCell(v )); return;
169
+ case "code": case "action": b.storeRef(v ); return;
170
+ case "maybeCell": b.storeMaybeRef(v ); return;
171
+ }
172
+ }
173
+
174
+ export function buildTonGovBody (name , fields , queryId = 0n) {
175
+ const spec = (TON_GOV_SPEC )[name];
176
+ if (!spec) throw new RangeError(`${name} is not a governance op`);
177
+ const b = beginCell().storeUint(opcodeOf(name), 32).storeUint(uint(queryId, 64, "query_id"), 64);
178
+ const f = fields ;
179
+ for (const [n, , k] of spec.fields) {
180
+ if (!(n in f)) throw new RangeError(`${name}: field ${n} missing`);
181
+ if (name === "withdraw_holder" && k === "launchIds" && (f[n] ).some((x) => x === 0n)) {
182
+ throw new RangeError("withdraw_holder: launch id 0 is the factory's own platform bucket; the factory refuses it for the holder bucket");
183
+ }
184
+ storeField(b, k, f[n], `${name}.${n}`);
185
+ }
186
+ for (const n of Object.keys(f)) if (!spec.fields.some((x) => x[0] === n)) throw new RangeError(`${name}: unknown field ${n}`);
187
+ return b.endCell();
188
+ }
189
+
190
+ export function buildTonGovSchedule (inner , fields , eta , queryId = 0n, innerQueryId = 0n) {
191
+ const action = buildTonGovBody(inner, fields, innerQueryId);
192
+ decodeTonGovAction(action, {}, true);
193
+ return buildTonGovBody("schedule", { action, eta } , queryId);
194
+ }
195
+
196
+ const BY_OPCODE = new Map ();
197
+ function byOpcode() {
198
+ if (BY_OPCODE.size === 0) for (const n of TON_GOV_OPS) BY_OPCODE.set(opcodeOf(n), n);
199
+ return BY_OPCODE;
200
+ }
201
+
202
+ function guard (what , f ) {
203
+ try {
204
+ return f();
205
+ } catch (e) {
206
+ if (e instanceof TonGovDecodeError) throw e;
207
+ throw new TonGovDecodeError(`${what}: ${(e ).message}`);
208
+ }
209
+ }
210
+ function done(s , what ) {
211
+ if (s.remainingBits !== 0) throw new TonGovDecodeError(`${what}: ${s.remainingBits} bits left over`);
212
+ if (s.remainingRefs !== 0) throw new TonGovDecodeError(`${what}: ${s.remainingRefs} refs left over`);
213
+ }
214
+ function addrInt(s , what ) {
215
+ const a = guard(what, () => s.loadAddress());
216
+ if (!a) throw new TonGovDecodeError(`${what}: addr_none where MsgAddressInt is required`);
217
+ return a;
218
+ }
219
+ function maybeAddrInt(s , what ) {
220
+ return guard(what, () => s.loadBit()) ? addrInt(s, what) : null;
221
+ }
222
+
223
+ function readPresetRow(c , what ) {
224
+ const parts = [];
225
+ for (let cur = c, i = 0; cur; i++) {
226
+ const s = cur.beginParse();
227
+ if (s.remainingBits % 8 !== 0) throw new TonGovDecodeError(`${what}: cell ${i} is not whole bytes`);
228
+ if (s.remainingRefs > 1) throw new TonGovDecodeError(`${what}: cell ${i} has ${s.remainingRefs} refs`);
229
+ parts.push(guard(what, () => s.loadBytes(s.remainingBits / 8)));
230
+ cur = s.remainingRefs ? s.loadRef() : null;
231
+ }
232
+ const all = new Uint8Array(parts.reduce((a, p) => a + p.length, 0));
233
+ let o = 0;
234
+ for (const p of parts) (all.set(p, o), (o += p.length));
235
+ guard(what, () => decodeRowV2(all));
236
+ return all;
237
+ }
238
+ function readSnakeStrict(c , what ) {
239
+ const parts = [];
240
+ for (let cur = c, i = 0; cur; cur = cur.refs[0], i++) {
241
+ if (cur.len % 8 !== 0) throw new TonGovDecodeError(`${what}: cell ${i} is not whole bytes`);
242
+ if (cur.refs.length > 1) throw new TonGovDecodeError(`${what}: cell ${i} has ${cur.refs.length} refs`);
243
+ parts.push(cur.bits.subarray(0, cur.len >> 3));
244
+ }
245
+ const all = new Uint8Array(parts.reduce((a, p) => a + p.length, 0));
246
+ let o = 0;
247
+ for (const p of parts) (all.set(p, o), (o += p.length));
248
+ return guard(what, () => new TextDecoder("utf-8", { fatal: true }).decode(all));
249
+ }
250
+ function readQuoteEntry(c , what ) {
251
+ const s = c.beginParse();
252
+ const e = guard(what, () => {
253
+ const kind = Number(s.loadUint(1)) ;
254
+ const master = s.loadAddress();
255
+ const decimals = Number(s.loadUint(8));
256
+ const walletKind = Number(s.loadUint(8));
257
+ const walletCodeHash = s.loadUint(256);
258
+ const walletCode = s.loadMaybeRef();
259
+ const createFee = s.loadCoins();
260
+ const issuerCanFreeze = s.loadBit();
261
+ const createsEnabled = s.loadBit();
262
+ const cap = s.loadCoins();
263
+ return { kind, master, decimals, walletKind, walletCodeHash, walletCode, createFee, issuerCanFreeze, createsEnabled, cap };
264
+ });
265
+ done(s, what);
266
+ return e;
267
+ }
268
+ function readLaunchIds(c , what ) {
269
+ const ids = [];
270
+ for (let cur = c, i = 0; cur; i++) {
271
+ const s = cur.beginParse();
272
+ if (s.remainingBits % 64 !== 0 || s.remainingBits === 0) throw new TonGovDecodeError(`${what}: cell ${i} is not whole uint64 ids`);
273
+ if (s.remainingRefs > 1) throw new TonGovDecodeError(`${what}: cell ${i} has ${s.remainingRefs} refs`);
274
+ while (s.remainingBits >= 64) ids.push(s.loadUint(64));
275
+ cur = s.remainingRefs ? s.loadRef() : null;
276
+ }
277
+ if (ids.length > 250) throw new TonGovDecodeError(`${what}: ${ids.length} ids, at most 250`);
278
+ return ids;
279
+ }
280
+ function readAddrList(c , what ) {
281
+ const out = [];
282
+ for (let cur = c, i = 0; cur; i++) {
283
+ const s = cur.beginParse();
284
+ const w = `${what} cell ${i}`;
285
+ const n = Number(guard(w, () => s.loadUint(2)));
286
+ const got = [addrInt(s, w), maybeAddrInt(s, w), maybeAddrInt(s, w)].filter((a) => a !== null);
287
+ if (n !== got.length || n === 0) throw new TonGovDecodeError(`${w}: n = ${n} but ${got.length} addresses`);
288
+ out.push(...got);
289
+ cur = guard(w, () => s.loadMaybeRef());
290
+ done(s, w);
291
+ }
292
+ if (out.length > 32) throw new TonGovDecodeError(`${what}: ${out.length} addresses, at most 32`);
293
+ return out;
294
+ }
295
+
296
+ function readField(s , k , what , opts ) {
297
+ void opts;
298
+ switch (k) {
299
+ case "u8": return Number(guard(what, () => s.loadUint(8)));
300
+ case "u16": return Number(guard(what, () => s.loadUint(16)));
301
+ case "u32": return Number(guard(what, () => s.loadUint(32)));
302
+ case "u64": return guard(what, () => s.loadUint(64));
303
+ case "u256": case "hash": case "pubkey": return guard(what, () => s.loadUint(256));
304
+ case "bool": return guard(what, () => s.loadBit());
305
+ case "addrInt": return addrInt(s, what);
306
+ case "addr": return guard(what, () => s.loadAddress());
307
+ case "gram": case "quoteCoins": return guard(what, () => s.loadCoins());
308
+ case "snake": return readSnakeStrict(guard(what, () => s.loadRef()), what);
309
+ case "presetRow": return readPresetRow(guard(what, () => s.loadRef()), what);
310
+ case "quoteEntry": return readQuoteEntry(guard(what, () => s.loadRef()), what);
311
+ case "launchIds": return readLaunchIds(guard(what, () => s.loadRef()), what);
312
+ case "addrList": return readAddrList(guard(what, () => s.loadRef()), what);
313
+ case "code": case "action": return guard(what, () => s.loadRef());
314
+ case "maybeCell": return guard(what, () => s.loadMaybeRef());
315
+ }
316
+ }
317
+
318
+ function fieldText(name , k , v , opts , quote , op = "") {
319
+ void name;
320
+ switch (k) {
321
+ case "u8": case "u16": case "u32": case "u64": case "bool": return String(v);
322
+ case "hash": return `0x${hex64(v )}`;
323
+ case "pubkey": return `ed25519 0x${hex64(v )}`;
324
+ case "u256": return `0x${hex64(v )}`;
325
+ case "addrInt": case "addr": return addrText(v );
326
+ case "gram": return `${tonFormatUnits(v , TON_GRAM_DECIMALS)} GRAM (${v} nanogram)`;
327
+ case "quoteCoins": {
328
+ const d = quote === null ? TON_GRAM_DECIMALS : quote ? opts.quoteDecimals?.(quote) : undefined;
329
+ return d === undefined ? `${v} raw units (the quote's decimals unknown)` : `${tonFormatUnits(v , d)} (${v} units, ${d} decimals)`;
330
+ }
331
+ case "snake": return JSON.stringify(v);
332
+ case "presetRow": return `${(v ).length} bytes, canonical RowV2`;
333
+ case "quoteEntry": {
334
+ const e = v ;
335
+ return [
336
+ `kind ${e.kind === 0 ? "native (GRAM)" : "jetton"}`, `master ${addrText(e.master)}`, `decimals ${e.decimals}`,
337
+ `wallet_kind ${e.walletKind}`, `wallet_code_hash 0x${hex64(e.walletCodeHash)}`,
338
+ `wallet_code ${e.walletCode ? `0x${cellHash(e.walletCode)}` : "none"}`,
339
+ `create_fee ${tonFormatUnits(e.createFee, e.decimals)}`, `issuer_can_freeze ${e.issuerCanFreeze}`,
340
+ `creates_enabled ${e.createsEnabled}`, `cap ${tonFormatUnits(e.cap, e.decimals)}`,
341
+ ].join(", ");
342
+ }
343
+ case "launchIds": return (v ).map((x) => (x === 0n ? (op === "withdraw_holder" ? "0 (REFUSED: the factory's own bucket is platform only)" : "0 (the factory's own platform bucket)") : String(x))).join(", ");
344
+ case "addrList": return (v ).map(addrText).join(", ");
345
+ case "code": case "action": return `cell 0x${cellHash(v )}`;
346
+ case "maybeCell": return v ? `cell 0x${cellHash(v )}` : "none";
347
+ }
348
+ }
349
+
350
+ function toCell(body ) {
351
+ if (body instanceof Cell) return body;
352
+ return guard("BoC", () => {
353
+ if (body instanceof Uint8Array) return fromBoc(body);
354
+ const t = body.trim();
355
+ return fromBoc(/^(0x)?[0-9a-fA-F]+$/.test(t) ? bytesOfHex(t.replace(/^0x/, "")) : bytesOfBase64(t));
356
+ });
357
+ }
358
+
359
+ export function decodeTonGovAction(body , opts = {}, asAction = false) {
360
+ const c = toCell(body);
361
+ const s = c.beginParse();
362
+ const opcode = Number(guard("op", () => s.loadUint(32)));
363
+ const name = byOpcode().get(opcode);
364
+ if (!name) throw new TonGovDecodeError(`unknown op 0x${opcode.toString(16).padStart(8, "0")}: not a governance op, refused`);
365
+ const spec = TON_GOV_SPEC[name];
366
+ if (asAction && !(spec.to === "FloorFactory" || name === "update_delay" || name === "set_admin")) {
367
+ throw new TonGovDecodeError(`${name} cannot be a timelock action (the timelock sends its actions to the factory)`);
368
+ }
369
+ const queryId = guard(`${name}.query_id`, () => s.loadUint(64));
370
+ const fields = {};
371
+ for (const [n, , k] of spec.fields) fields[n] = readField(s, k, `${name}.${n}`, opts);
372
+ done(s, name);
373
+
374
+ const derived = {};
375
+ let inner ;
376
+ for (const [n, , k] of spec.fields) {
377
+ const v = fields[n];
378
+ if (k === "code") derived[`${n}_hash`] = `0x${cellHash(v )}`;
379
+ if (k === "presetRow") derived[`${n}_hash`] = `0x${cellHash(tonPresetRowCell(v ))}`;
380
+ if (k === "action") {
381
+ inner = decodeTonGovAction(v , opts, true);
382
+ derived.action_hash = `0x${cellHash(v )}`;
383
+ }
384
+ }
385
+ if ("code_hash" in fields && "code" in fields) {
386
+ const ok = hex64(fields.code_hash ) === cellHash(fields.code );
387
+ derived.code_hash_matches = ok ? "yes" : "NO: the contract refuses this code (code_hash ≠ cell_hash(code))";
388
+ }
389
+ if (name === "set_code" || name === "push_child_code") derived.family_name = FAMILY[fields.family ] ?? "unknown family (refused)";
390
+ if (name === "pull_bucket") derived.bucket_name = BUCKET[fields.bucket ] ?? "unknown bucket (refused)";
391
+ if (name === "set_create_paused") derived.scope = "new creates only; buys and sells can never be paused";
392
+
393
+ const quote = "quote" in fields ? (fields.quote ) : undefined;
394
+ const lines = [`${name} → ${spec.to} (query_id ${queryId})`];
395
+ for (const [n, , k] of spec.fields) lines.push(` ${n}: ${fieldText(n, k, fields[n], opts, quote, name)}`);
396
+ for (const [k, v] of Object.entries(derived)) lines.push(` [${k}] ${v}`);
397
+ if (inner) lines.push(" action decodes as:", ...inner.lines.map((l) => ` ${l}`));
398
+ return { op: name, opcode, target: spec.to, from: spec.from, queryId, fields: fields , derived, inner, lines };
399
+ }
400
+
401
+ export const tonGovPresetRow = (bytes ) => decodeRowV2(bytes);
@@ -0,0 +1,18 @@
1
+
2
+ export * from "./types.js";
3
+ export * from "./cell.js";
4
+ export * from "./ops.js";
5
+ export * from "./addresses.js";
6
+ export * from "./messages.js";
7
+ export * from "./reader.js";
8
+ export * from "./quote.js";
9
+ export * from "./governance.js";
10
+ export * from "./quote-entry.js";
11
+ export * from "./price.js";
12
+
13
+ export { defaultClaimValue, pushChildMin, pushEach, childEach } from "./gas.js";
14
+ export * from "./book.js";
15
+ export * from "./book-check.js";
16
+ export * from "./wallet.js";
17
+ export { TON_MAINNET, TON_INIT_CODES_BASE64 } from "./consts.generated.js";
18
+ export * from "./content.js";