@anywalletkit/protocol-staking-liquid-near 0.0.0-stage → 0.1.1

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/dist/index.cjs ADDED
@@ -0,0 +1,1025 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ CONTRACT_MIN_RESERVE_BALANCE: () => CONTRACT_MIN_RESERVE_BALANCE,
24
+ DEFAULT_APR_WINDOW_EPOCHS: () => DEFAULT_APR_WINDOW_EPOCHS,
25
+ DEFAULT_ARCHIVAL_RPC: () => DEFAULT_ARCHIVAL_RPC,
26
+ DEFAULT_GAS: () => DEFAULT_GAS,
27
+ DEFAULT_RESERVE: () => DEFAULT_RESERVE,
28
+ EPOCH_LENGTH: () => EPOCH_LENGTH,
29
+ GAS_PRICE_MARGIN_DEN: () => GAS_PRICE_MARGIN_DEN,
30
+ GAS_PRICE_MARGIN_NUM: () => GAS_PRICE_MARGIN_NUM,
31
+ GasPricer: () => GasPricer,
32
+ LIQUID_PRESETS: () => LIQUID_PRESETS,
33
+ LIQUID_WRITE_METHODS: () => LIQUID_WRITE_METHODS,
34
+ LST_DECIMALS: () => LST_DECIMALS,
35
+ LiquidStakingError: () => LiquidStakingError,
36
+ LiquidStakingProtocolNear: () => LiquidStakingProtocolNear,
37
+ MIN_EPOCHS_TO_UNLOCK: () => MIN_EPOCHS_TO_UNLOCK,
38
+ MIN_GAS_PURCHASE_PRICE_FALLBACK: () => MIN_GAS_PURCHASE_PRICE_FALLBACK,
39
+ MIN_STAKE: () => MIN_STAKE,
40
+ MODULE_NAME: () => MODULE_NAME,
41
+ NEAR_MAINNET: () => NEAR_MAINNET,
42
+ NEAR_TESTNET: () => NEAR_TESTNET,
43
+ PAUSE_KEYS: () => PAUSE_KEYS,
44
+ PRICE_SCALE: () => PRICE_SCALE,
45
+ STORAGE_DEPOSIT: () => STORAGE_DEPOSIT,
46
+ TGAS: () => TGAS,
47
+ TYPICAL_EPOCH_MS: () => TYPICAL_EPOCH_MS,
48
+ UNSTAKED_DUST: () => UNSTAKED_DUST,
49
+ YOCTO_PER_NEAR: () => YOCTO_PER_NEAR,
50
+ aprFromPrices: () => aprFromPrices,
51
+ assertLiquidPlan: () => assertLiquidPlan,
52
+ blockAt: () => blockAt,
53
+ canSendBatch: () => canSendBatch,
54
+ costOf: () => costOf,
55
+ default: () => LiquidStakingProtocolNear,
56
+ describeLiquidNearStakingActivity: () => describeLiquidNearStakingActivity,
57
+ epochStartsAt: () => epochStartsAt,
58
+ fc: () => fc,
59
+ finalBlock: () => finalBlock,
60
+ gasOf: () => gasOf,
61
+ nearForShares: () => nearForShares,
62
+ poolRequestId: () => poolRequestId,
63
+ readEpoch: () => readEpoch,
64
+ readEpochNumbers: () => readEpochNumbers,
65
+ resolvePool: () => resolvePool,
66
+ resolveRpc: () => resolveRpc,
67
+ sameTransactions: () => sameTransactions,
68
+ sharesForNear: () => sharesForNear,
69
+ validatePoolConfig: () => validatePoolConfig,
70
+ valueAtPrice: () => valueAtPrice
71
+ });
72
+ module.exports = __toCommonJS(src_exports);
73
+
74
+ // src/protocol.ts
75
+ var import_core4 = require("@anywalletkit/core");
76
+ var import_wallet_near5 = require("@anywalletkit/wallet-near");
77
+
78
+ // src/activity.ts
79
+ var import_core = require("@anywalletkit/core");
80
+
81
+ // src/constants.ts
82
+ var NEAR_MAINNET = "near:mainnet";
83
+ var NEAR_TESTNET = "near:testnet";
84
+ var YOCTO_PER_NEAR = 10n ** 24n;
85
+ var TGAS = 10n ** 12n;
86
+ var LST_DECIMALS = 24;
87
+ var PRICE_SCALE = 10n ** 24n;
88
+ var MIN_EPOCHS_TO_UNLOCK = 4n;
89
+ var EPOCH_LENGTH = 43200n;
90
+ var TYPICAL_EPOCH_MS = 2484e4;
91
+ var UNSTAKED_DUST = 1000000n;
92
+ var CONTRACT_MIN_RESERVE_BALANCE = YOCTO_PER_NEAR;
93
+ var STORAGE_DEPOSIT = 1250000000000000000000n;
94
+ var DEFAULT_RESERVE = 2n * 10n ** 22n;
95
+ var MIN_STAKE = 10n ** 21n;
96
+ var PAUSE_KEYS = {
97
+ deposit_and_stake: ["internal_deposit", "internal_stake"],
98
+ unstake: ["internal_unstake"],
99
+ unstake_all: ["internal_unstake"],
100
+ withdraw_all: ["internal_withdraw"]
101
+ };
102
+ var DEFAULT_GAS = {
103
+ stake: 30n * TGAS,
104
+ unstake: 30n * TGAS,
105
+ withdraw: 30n * TGAS
106
+ };
107
+ var GAS_PRICE_MARGIN_NUM = 11n;
108
+ var GAS_PRICE_MARGIN_DEN = 10n;
109
+ var MIN_GAS_PURCHASE_PRICE_FALLBACK = 10n ** 9n;
110
+ var DEFAULT_APR_WINDOW_EPOCHS = 24;
111
+ var DEFAULT_ARCHIVAL_RPC = {
112
+ mainnet: "https://archival-rpc.mainnet.fastnear.com",
113
+ testnet: "https://archival-rpc.testnet.fastnear.com"
114
+ };
115
+ var LIQUID_PRESETS = {
116
+ linear: {
117
+ symbol: "LINEAR",
118
+ name: "LiNEAR",
119
+ firstStakePaysStorage: false,
120
+ // stake.rs: internal_deposit(attached); an unregistered implicit account staked 0.266 NEAR whole (fixture)
121
+ featurePauses: false,
122
+ // one `paused` flag (is_paused); pa_all_paused is MethodNotFound on mainnet
123
+ contracts: {
124
+ mainnet: { contract: "linear-protocol.near", codeHashes: ["5LiDVDd1gh7ofVNbiA9VXrWwkv2m8tw46jZqYeuoC3SG"] },
125
+ testnet: { contract: "linear-protocol.testnet", codeHashes: ["8Bby4ofnYGtudd3PinKZ1KyvmUKJVyxmfC99ZccRDVDv"] }
126
+ }
127
+ },
128
+ rnear: {
129
+ symbol: "rNEAR",
130
+ name: "Rhea Liquid Near Staking Token",
131
+ firstStakePaysStorage: true,
132
+ // stake_pool_itf.rs: internal_deposit(amount − storage_balance_bounds.min) when storage_balance_of is null
133
+ featurePauses: true,
134
+ // #[pause] on internal_deposit / internal_stake / internal_unstake / internal_withdraw; is_paused reads only 'ALL'
135
+ contracts: {
136
+ mainnet: { contract: "lst.rhealab.near", codeHashes: ["EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv"] }
137
+ // v1.0.2
138
+ }
139
+ }
140
+ };
141
+
142
+ // src/activity.ts
143
+ var MODULE_NAME = "@anywalletkit/protocol-staking-liquid-near";
144
+ var LABELS = { linear: "LiNEAR", rnear: "Rhea rNEAR" };
145
+ var NEAR = { symbol: "NEAR", decimals: 24 };
146
+ function knownContracts(network, extra) {
147
+ const out = [];
148
+ for (const [key, preset] of Object.entries(LIQUID_PRESETS)) {
149
+ const on = preset.contracts[network];
150
+ if (on) out.push({ contract: on.contract, symbol: preset.symbol, label: LABELS[key] });
151
+ }
152
+ for (const c of extra) out.push({ contract: c.contract, symbol: c.symbol, label: c.name ?? c.symbol });
153
+ return out;
154
+ }
155
+ function withdrawnFromLogs(tx, contract, me) {
156
+ const rpc = tx.raw?.rpc;
157
+ let sum = 0n;
158
+ for (const r of rpc?.receipts_outcome ?? []) {
159
+ if (r.outcome?.executor_id !== contract) continue;
160
+ for (const log of r.outcome.logs ?? []) {
161
+ if (!log.startsWith("EVENT_JSON:")) continue;
162
+ try {
163
+ const ev = JSON.parse(log.slice("EVENT_JSON:".length));
164
+ if (ev.event !== "withdraw") continue;
165
+ for (const d of ev.data ?? []) if (d.account_id === me && typeof d.amount === "string" && /^\d+$/.test(d.amount)) sum += BigInt(d.amount);
166
+ } catch {
167
+ }
168
+ }
169
+ }
170
+ return sum;
171
+ }
172
+ function describeLiquidNearStakingActivity(tx, ctx, options = {}) {
173
+ const network = tx.chain === NEAR_MAINNET ? "mainnet" : tx.chain === NEAR_TESTNET ? "testnet" : null;
174
+ const call = tx.call;
175
+ if (!network || !call) return null;
176
+ const known = knownContracts(network, options.contracts ?? []).find((c) => c.contract === call.to);
177
+ if (!known || !ctx.own.has(tx.from)) return null;
178
+ const methods = call.programs?.length ? call.programs : [call.method ?? ""];
179
+ const has = (...names) => names.some((n) => methods.includes(n));
180
+ let kind, title;
181
+ if (has("deposit_and_stake")) {
182
+ kind = "stake";
183
+ title = `Staked NEAR for ${known.symbol}`;
184
+ } else if (has("stake", "stake_all")) {
185
+ kind = "stake";
186
+ title = `Restaked NEAR for ${known.symbol}`;
187
+ } else if (has("unstake", "unstake_all")) {
188
+ kind = "unstake";
189
+ title = has("withdraw", "withdraw_all") ? "Withdrew and requested unstake" : "Requested unstake";
190
+ } else if (has("withdraw", "withdraw_all")) {
191
+ kind = "claim";
192
+ title = "Withdrew unstaked NEAR";
193
+ } else return null;
194
+ const meta = (token) => token === null ? NEAR : token === known.contract ? { symbol: known.symbol, decimals: LST_DECIMALS } : void 0;
195
+ const { assetsIn, assetsOut } = (0, import_core.splitNet)((0, import_core.netTransfers)(tx, ctx.own), meta);
196
+ if (kind === "stake" && !assetsOut.some((a) => a.token === null) && tx.nativeValue > 0n) {
197
+ assetsOut.push({ token: null, amount: tx.nativeValue, ...NEAR });
198
+ }
199
+ if (has("withdraw", "withdraw_all") && !assetsIn.some((a) => a.token === null)) {
200
+ const paid = withdrawnFromLogs(tx, known.contract, tx.from);
201
+ if (paid > 0n) assetsIn.push({ token: null, amount: paid, ...NEAR });
202
+ }
203
+ return (0, import_core.activityBase)(tx, kind, title, {
204
+ protocol: MODULE_NAME,
205
+ subtitle: `${known.label} liquid staking`,
206
+ counterparty: call.to,
207
+ assetsIn,
208
+ assetsOut
209
+ });
210
+ }
211
+
212
+ // src/epoch.ts
213
+ var import_core2 = require("@anywalletkit/core");
214
+ var import_wallet_near = require("@anywalletkit/wallet-near");
215
+ var SKIP_TRIES = 10;
216
+ function blockTimeOf(raw) {
217
+ const h = raw?.header;
218
+ if (!h || typeof h.height !== "number") throw new import_core2.NetworkError("block: no header in the response");
219
+ let ms;
220
+ if (typeof h.timestamp_nanosec === "string" && /^\d+$/.test(h.timestamp_nanosec)) ms = (0, import_core2.bigintToNumber)(BigInt(h.timestamp_nanosec) / 1000000n);
221
+ else if (typeof h.timestamp === "number") ms = Math.floor(h.timestamp / 1e6);
222
+ else throw new import_core2.NetworkError("block: no timestamp in the header");
223
+ return { height: BigInt(h.height), ms };
224
+ }
225
+ async function finalBlock(rpc) {
226
+ return blockTimeOf(await rpc.fetch("block", { finality: "final" }));
227
+ }
228
+ async function blockAt(rpc, height) {
229
+ let last;
230
+ for (let i = 0n; i <= BigInt(SKIP_TRIES); i++) {
231
+ try {
232
+ return blockTimeOf(await rpc.fetch("block", { block_id: (0, import_core2.bigintToNumber)(height + i) }));
233
+ } catch (e) {
234
+ if (!(e instanceof import_wallet_near.NearRpcError) || !/UNKNOWN_BLOCK/i.test(e.errorName ?? "")) throw e;
235
+ last = e;
236
+ }
237
+ }
238
+ throw last;
239
+ }
240
+ async function readEpochNumbers(rpc) {
241
+ const r = await rpc.fetch("validators", [null]);
242
+ if (typeof r?.epoch_height !== "number" || typeof r.epoch_start_height !== "number") throw new import_core2.NetworkError("validators: no epoch_height / epoch_start_height in the response");
243
+ return { epochHeight: BigInt(r.epoch_height), epochStartHeight: BigInt(r.epoch_start_height) };
244
+ }
245
+ async function readEpoch(rpc, options = {}) {
246
+ const [numbers, latest] = await Promise.all([(options.numbers ?? (() => readEpochNumbers(rpc)))(), finalBlock(rpc)]);
247
+ const times = options.blockTimes ?? /* @__PURE__ */ new Map();
248
+ const timeAt = async (height) => {
249
+ const known = times.get(height);
250
+ if (known !== void 0) return known;
251
+ try {
252
+ const ms = (await blockAt(rpc, height)).ms;
253
+ times.set(height, ms);
254
+ return ms;
255
+ } catch {
256
+ return null;
257
+ }
258
+ };
259
+ const length = EPOCH_LENGTH;
260
+ const startBlock = numbers.epochStartHeight;
261
+ const [started, prevStarted] = await Promise.all([timeAt(startBlock), timeAt(startBlock - length)]);
262
+ const epochMs = started !== null && prevStarted !== null && started > prevStarted ? started - prevStarted : TYPICAL_EPOCH_MS;
263
+ const msPerBlock = epochMs / (0, import_core2.bigintToNumber)(length);
264
+ const into = latest.height > startBlock ? latest.height - startBlock : 0n;
265
+ const startedAt = started ?? Math.round(latest.ms - (0, import_core2.bigintToNumber)(into) * msPerBlock);
266
+ const blocksLeft = startBlock + length > latest.height ? startBlock + length - latest.height : 0n;
267
+ return {
268
+ height: numbers.epochHeight,
269
+ startBlock,
270
+ length,
271
+ block: latest.height,
272
+ blocksLeft,
273
+ startedAt,
274
+ epochMs,
275
+ endsAt: Math.round(latest.ms + (0, import_core2.bigintToNumber)(blocksLeft) * msPerBlock)
276
+ };
277
+ }
278
+ function epochStartsAt(epoch, height) {
279
+ if (height <= epoch.height) return epoch.startedAt - (0, import_core2.bigintToNumber)(epoch.height - height) * epoch.epochMs;
280
+ return epoch.endsAt + (0, import_core2.bigintToNumber)(height - epoch.height - 1n) * epoch.epochMs;
281
+ }
282
+
283
+ // src/errors.ts
284
+ var LiquidStakingError = class extends Error {
285
+ code;
286
+ details;
287
+ constructor(code, message, extra = {}) {
288
+ super(message, extra.cause !== void 0 ? { cause: extra.cause } : void 0);
289
+ this.name = "LiquidStakingError";
290
+ this.code = code;
291
+ this.details = extra.details;
292
+ }
293
+ };
294
+
295
+ // src/fees.ts
296
+ var import_wallet_near2 = require("@anywalletkit/wallet-near");
297
+ var PROTOCOL_CONFIG_TTL_MS = 10 * 6e4;
298
+ var FALLBACK_TTL_MS = 6e4;
299
+ var GasPricer = class {
300
+ constructor(rpc) {
301
+ this.rpc = rpc;
302
+ }
303
+ rpc;
304
+ minPurchase;
305
+ async prices() {
306
+ const [price, min] = await Promise.all([this.rpc().gasPrice(), this.minPurchasePrice()]);
307
+ const gasPrice = price * GAS_PRICE_MARGIN_NUM / GAS_PRICE_MARGIN_DEN;
308
+ return { gasPrice, purchasePrice: gasPrice > min ? gasPrice : min };
309
+ }
310
+ /** `runtime_config.min_gas_purchase_price`; the mainnet value when the node cannot say (fails toward a larger balance check). */
311
+ minPurchasePrice() {
312
+ const hit = this.minPurchase;
313
+ if (hit && Date.now() - hit.at < hit.ttl) return hit.value;
314
+ const entry = { at: Date.now(), ttl: PROTOCOL_CONFIG_TTL_MS, value: Promise.resolve(MIN_GAS_PURCHASE_PRICE_FALLBACK) };
315
+ entry.value = this.rpc().fetch("EXPERIMENTAL_protocol_config", { finality: "final" }).then((r) => {
316
+ const v = r?.runtime_config?.min_gas_purchase_price;
317
+ if (typeof v === "string" && /^\d{1,30}$/.test(v)) return BigInt(v);
318
+ entry.ttl = FALLBACK_TTL_MS;
319
+ return MIN_GAS_PURCHASE_PRICE_FALLBACK;
320
+ }, () => {
321
+ entry.ttl = FALLBACK_TTL_MS;
322
+ return MIN_GAS_PURCHASE_PRICE_FALLBACK;
323
+ });
324
+ this.minPurchase = entry;
325
+ return entry.value;
326
+ }
327
+ };
328
+ var gasOf = (txs) => txs.reduce((s, tx) => s + import_wallet_near2.WalletAccountReadOnlyNear.gasOf(tx.actions, false), 0n);
329
+ function costOf(txs, prices) {
330
+ const gas = gasOf(txs);
331
+ return { fee: gas * prices.gasPrice, upfront: gas * prices.purchasePrice };
332
+ }
333
+
334
+ // src/math.ts
335
+ var import_core3 = require("@anywalletkit/core");
336
+ function sharesForNear(amount, totals) {
337
+ if (totals.totalStaked <= 0n) return 0n;
338
+ return amount * totals.totalShares / totals.totalStaked;
339
+ }
340
+ function nearForShares(shares, totals) {
341
+ if (totals.totalShares <= 0n) return 0n;
342
+ return shares * totals.totalStaked / totals.totalShares;
343
+ }
344
+ function valueAtPrice(shares, price) {
345
+ return shares * price / PRICE_SCALE;
346
+ }
347
+ var YEAR_MS = 31557600000n;
348
+ var FIXED = 10n ** 12n;
349
+ function aprFromPrices(p0, p1, t0Ms, t1Ms) {
350
+ const dt = BigInt(Math.round(t1Ms - t0Ms));
351
+ if (p0 <= 0n || p1 <= 0n || dt <= 0n) return 0;
352
+ const scaled = (p1 - p0) * YEAR_MS * 100n * FIXED / (p0 * dt);
353
+ return (0, import_core3.bigintToNumber)(scaled) / (0, import_core3.bigintToNumber)(FIXED);
354
+ }
355
+
356
+ // src/pool.ts
357
+ var import_sha2 = require("@noble/hashes/sha2.js");
358
+ var import_wallet_near3 = require("@anywalletkit/wallet-near");
359
+ function validatePoolConfig(pool) {
360
+ if (typeof pool === "string") {
361
+ if (!(pool in LIQUID_PRESETS)) throw new LiquidStakingError("invalid-config", `Unknown pool '${pool}': use ${Object.keys(LIQUID_PRESETS).map((k) => `'${k}'`).join(" or ")}, or a { contract, symbol, codeHashes } config.`);
362
+ return;
363
+ }
364
+ if (!pool || typeof pool !== "object" || typeof pool.contract !== "string" || !(0, import_wallet_near3.isValidAccountId)(pool.contract)) throw new LiquidStakingError("invalid-config", "pool.contract must be a NEAR account id.");
365
+ if (typeof pool.symbol !== "string" || pool.symbol.length === 0) throw new LiquidStakingError("invalid-config", "pool.symbol is required.");
366
+ if (!Array.isArray(pool.codeHashes) || pool.codeHashes.length === 0 || !pool.codeHashes.every((h) => typeof h === "string" && h.length > 0)) {
367
+ throw new LiquidStakingError("invalid-config", "pool.codeHashes must pin at least one code hash.");
368
+ }
369
+ if (pool.firstStakePaysStorage !== void 0 && typeof pool.firstStakePaysStorage !== "boolean") throw new LiquidStakingError("invalid-config", "pool.firstStakePaysStorage must be a boolean.");
370
+ }
371
+ function resolvePool(pool, network) {
372
+ if (typeof pool !== "string") {
373
+ const known = Object.values(LIQUID_PRESETS).find((p) => Object.values(p.contracts).some((c) => c?.contract === pool.contract));
374
+ const firstStakePaysStorage = pool.firstStakePaysStorage ?? known?.firstStakePaysStorage ?? true;
375
+ return { contract: pool.contract, symbol: pool.symbol, name: pool.name ?? pool.symbol, codeHashes: pool.codeHashes, firstStakePaysStorage, featurePauses: true, preset: null };
376
+ }
377
+ const preset = LIQUID_PRESETS[pool];
378
+ const on = preset.contracts[network];
379
+ if (!on) throw new LiquidStakingError("unsupported-network", `${preset.name} has no contract on NEAR ${network}.`);
380
+ return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, firstStakePaysStorage: preset.firstStakePaysStorage, featurePauses: preset.featurePauses, preset: pool };
381
+ }
382
+ function poolRequestId(contract) {
383
+ let id = 0n;
384
+ for (const b of (0, import_sha2.sha256)(new TextEncoder().encode(contract)).subarray(0, 8)) id = id << 8n | BigInt(b);
385
+ return id;
386
+ }
387
+
388
+ // src/rpc.ts
389
+ var import_wallet_near4 = require("@anywalletkit/wallet-near");
390
+ function resolveRpc(account, config) {
391
+ if (config.provider !== void 0) {
392
+ const fetch = (0, import_wallet_near4.createClient)({ provider: config.provider, ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {} });
393
+ return fetch ? new import_wallet_near4.NearRpc(fetch) : void 0;
394
+ }
395
+ const own = account;
396
+ if (typeof own._client === "function") return new import_wallet_near4.NearRpc(own._client);
397
+ if (own._config?.provider !== void 0) {
398
+ const fetch = (0, import_wallet_near4.createClient)({ provider: own._config.provider, ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {} });
399
+ return fetch ? new import_wallet_near4.NearRpc(fetch) : void 0;
400
+ }
401
+ return void 0;
402
+ }
403
+
404
+ // src/transactions.ts
405
+ function canSendBatch(account) {
406
+ return typeof account.sendTransactions === "function";
407
+ }
408
+ var canonicalArgs = (args) => args instanceof Uint8Array ? { bytes: Array.from(args) } : typeof args === "string" ? { text: args } : args;
409
+ var canonicalAction = (a) => {
410
+ if ("functionCall" in a) {
411
+ const f = a.functionCall;
412
+ return { functionCall: { methodName: f.methodName, args: canonicalArgs(f.args), gas: String(f.gas ?? 0n), deposit: String(f.deposit ?? 0n) } };
413
+ }
414
+ if ("transfer" in a) return { transfer: { deposit: String(a.transfer.deposit) } };
415
+ return { other: Object.keys(a)[0] };
416
+ };
417
+ var stable = (v) => {
418
+ if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
419
+ if (v && typeof v === "object") return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(",")}}`;
420
+ return JSON.stringify(typeof v === "bigint" ? String(v) : v);
421
+ };
422
+ function sameTransactions(a, b) {
423
+ if (a.length !== b.length) return false;
424
+ for (let i = 0; i < a.length; i++) {
425
+ const x = a[i], y = b[i];
426
+ if (x.receiverId !== y.receiverId || x.actions.length !== y.actions.length) return false;
427
+ for (let j = 0; j < x.actions.length; j++) {
428
+ const ca = canonicalAction(x.actions[j]), cb = canonicalAction(y.actions[j]);
429
+ if (ca.other !== void 0 || stable(ca) !== stable(cb)) return false;
430
+ }
431
+ }
432
+ return true;
433
+ }
434
+ function fc(methodName, args, gas, deposit) {
435
+ return { functionCall: { methodName, args, gas, deposit } };
436
+ }
437
+ var LIQUID_WRITE_METHODS = ["deposit_and_stake", "unstake", "unstake_all", "withdraw_all"];
438
+ function assertLiquidPlan(transactions, contract) {
439
+ for (const tx of transactions) {
440
+ if (tx.receiverId !== contract) throw new Error(`Refusing a transaction to ${tx.receiverId}: liquid staking only calls ${contract}.`);
441
+ if (tx.signerId !== void 0) throw new Error("Refusing a transaction with a signerId: the account signs as itself.");
442
+ for (const a of tx.actions) {
443
+ const method = "functionCall" in a ? a.functionCall.methodName : null;
444
+ if (method === null) throw new Error(`Refusing a ${Object.keys(a)[0]} action: liquid staking sends function calls only.`);
445
+ if (!LIQUID_WRITE_METHODS.includes(method)) throw new Error(`Refusing ${method} on ${contract}: liquid staking calls only ${LIQUID_WRITE_METHODS.join(", ")}${/^ft_transfer/.test(method) ? " (the contract has no ft_on_transfer: tokens sent with ft_transfer_call are lost)" : ""}.`);
446
+ }
447
+ }
448
+ }
449
+
450
+ // src/protocol.ts
451
+ var EPOCH_NUMBERS_TTL_MS = 6e4;
452
+ var APR_TTL_MS = 10 * 6e4;
453
+ var APR_FALLBACK_EPOCHS = 2n;
454
+ var SKIP_TRIES2 = 10;
455
+ var MAX_CALL_GAS = 300n * TGAS;
456
+ var FEATURE_WORDS = {
457
+ internal_deposit: "deposits",
458
+ internal_stake: "staking",
459
+ internal_unstake: "unstaking",
460
+ internal_withdraw: "withdrawals"
461
+ };
462
+ var near = (yocto) => {
463
+ const frac = (yocto % YOCTO_PER_NEAR).toString().padStart(24, "0").slice(0, 5).replace(/0+$/, "");
464
+ return `${yocto / YOCTO_PER_NEAR}${frac ? `.${frac}` : ""} NEAR`;
465
+ };
466
+ function amountOf(v, what) {
467
+ if (typeof v === "string" && /^\d+$/.test(v)) return BigInt(v);
468
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
469
+ throw new import_core4.NetworkError(`${what}: expected a non-negative integer, got ${String(JSON.stringify(v)).slice(0, 60)}`);
470
+ }
471
+ function methodMissing(e) {
472
+ if (/MethodNotFound/.test(e.message)) return true;
473
+ try {
474
+ return /MethodNotFound/.test(JSON.stringify(e.cause) ?? "");
475
+ } catch {
476
+ return false;
477
+ }
478
+ }
479
+ function positiveAmount(v, unit) {
480
+ if (typeof v !== "bigint" && !(typeof v === "number" && Number.isSafeInteger(v))) {
481
+ throw new LiquidStakingError("invalid-amount", `'amount' must be a bigint or a safe integer (${unit}).`);
482
+ }
483
+ const amount = BigInt(v);
484
+ if (amount <= 0n) throw new LiquidStakingError("invalid-amount", "'amount' must be greater than zero.");
485
+ return amount;
486
+ }
487
+ var MAX_U128_DIGITS = "9".repeat(39);
488
+ var copyTx = (tx) => ({
489
+ receiverId: tx.receiverId,
490
+ actions: tx.actions.map((a) => "functionCall" in a ? { functionCall: { ...a.functionCall, args: { ...a.functionCall.args } } } : a)
491
+ });
492
+ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_core4.StakingProtocol {
493
+ reserve;
494
+ gas;
495
+ aprWindowEpochs;
496
+ configuredNetwork;
497
+ rpc;
498
+ archival;
499
+ numbersCache;
500
+ blockTimes = /* @__PURE__ */ new Map();
501
+ aprCache;
502
+ pricer = new GasPricer(() => this.client());
503
+ constructor(account, config) {
504
+ super(account, config);
505
+ if (!config || typeof config !== "object") throw new LiquidStakingError("invalid-config", "LiquidStakingProtocolNear needs a config with `pool` ('linear', 'rnear' or a contract).");
506
+ validatePoolConfig(config.pool);
507
+ if (config.network !== void 0 && config.network !== "mainnet" && config.network !== "testnet") {
508
+ throw new LiquidStakingError("invalid-config", "network must be 'mainnet' or 'testnet'.");
509
+ }
510
+ this.configuredNetwork = config.network;
511
+ if (config.reserve !== void 0 && typeof config.reserve !== "bigint" && !(typeof config.reserve === "number" && Number.isSafeInteger(config.reserve))) {
512
+ throw new LiquidStakingError("invalid-config", "reserve must be a bigint or a safe integer (yoctoNEAR).");
513
+ }
514
+ this.reserve = BigInt(config.reserve ?? DEFAULT_RESERVE);
515
+ if (this.reserve < 0n) throw new LiquidStakingError("invalid-config", "reserve must not be negative.");
516
+ this.gas = { stake: config.gas?.stake ?? DEFAULT_GAS.stake, unstake: config.gas?.unstake ?? DEFAULT_GAS.unstake, withdraw: config.gas?.withdraw ?? DEFAULT_GAS.withdraw };
517
+ for (const [k, g] of Object.entries(this.gas)) {
518
+ if (typeof g !== "bigint" || g <= 0n || g > MAX_CALL_GAS) throw new LiquidStakingError("invalid-config", `gas.${k} must be a bigint above 0 and at most 300 Tgas.`);
519
+ }
520
+ if (this.gas.withdraw + this.gas.unstake > MAX_CALL_GAS) throw new LiquidStakingError("invalid-config", "gas.withdraw + gas.unstake must fit in one transaction (300 Tgas): an unstake may carry both.");
521
+ this.aprWindowEpochs = config.aprWindowEpochs ?? DEFAULT_APR_WINDOW_EPOCHS;
522
+ if (!Number.isInteger(this.aprWindowEpochs) || this.aprWindowEpochs < 1) throw new LiquidStakingError("invalid-config", "aprWindowEpochs must be a positive integer.");
523
+ if (config.apr !== void 0 && typeof config.apr !== "function") throw new LiquidStakingError("invalid-config", "apr must be a function returning the APR in percent.");
524
+ this.rpc = resolveRpc(account, config);
525
+ }
526
+ /** The configured network, else the account's (`near:testnet` → testnet, anything else → mainnet). */
527
+ get network() {
528
+ return this.configuredNetwork ?? (this._account.chain === NEAR_TESTNET ? "testnet" : "mainnet");
529
+ }
530
+ /** Contract, symbol and pinned code hashes on the current network (throws 'unsupported-network'). */
531
+ get pool() {
532
+ return resolvePool(this._config.pool, this.network);
533
+ }
534
+ // ── Plumbing ───────────────────────────────────────────────────────────────
535
+ client() {
536
+ if (!this.rpc) throw new LiquidStakingError("no-provider", "LiquidStakingProtocolNear needs a NEAR RPC: pass `provider`, or a wallet-near account configured with one.");
537
+ return this.rpc;
538
+ }
539
+ archivalClient() {
540
+ if (!this.archival) {
541
+ const fetch = (0, import_wallet_near5.createClient)({
542
+ provider: this._config.archivalProvider ?? DEFAULT_ARCHIVAL_RPC[this.network],
543
+ ...this._config.timeoutMs !== void 0 ? { timeoutMs: this._config.timeoutMs } : {}
544
+ });
545
+ if (!fetch) throw new LiquidStakingError("no-provider", "No archival RPC for the APR estimate: pass `archivalProvider` or an `apr` hook.");
546
+ this.archival = new import_wallet_near5.NearRpc(fetch);
547
+ }
548
+ return this.archival;
549
+ }
550
+ /** The account id, after checking the account is on the module's NEAR network. */
551
+ async me() {
552
+ const want = this.network === "testnet" ? NEAR_TESTNET : NEAR_MAINNET;
553
+ if (this._account.chain !== want) throw new LiquidStakingError("wrong-chain", `LiquidStakingProtocolNear works on ${want}; the account is on ${this._account.chain}.`);
554
+ return await this._account.getAddress();
555
+ }
556
+ view(method, args = {}) {
557
+ return this.client().callFunction(this.pool.contract, method, args);
558
+ }
559
+ epochNumbers() {
560
+ const hit = this.numbersCache;
561
+ if (hit && Date.now() - hit.at < EPOCH_NUMBERS_TTL_MS) return hit.value;
562
+ const value = readEpochNumbers(this.client());
563
+ this.numbersCache = { at: Date.now(), value };
564
+ value.catch(() => {
565
+ if (this.numbersCache?.value === value) this.numbersCache = void 0;
566
+ });
567
+ return value;
568
+ }
569
+ /** Spendable NEAR of the account: amount − max(0, storage − locked), never below 0 (0 for an account that does not exist yet). */
570
+ async available(me) {
571
+ const v = await this.client().viewAccount(me);
572
+ if (!v) return 0n;
573
+ const storage = amountOf(v.storage_usage, "view_account.storage_usage") * import_wallet_near5.STORAGE_PRICE_PER_BYTE;
574
+ const locked = amountOf(v.locked, "view_account.locked");
575
+ const free = amountOf(v.amount, "view_account.amount") - (storage > locked ? storage - locked : 0n);
576
+ return free > 0n ? free : 0n;
577
+ }
578
+ /** Fee (upper bound) and upfront charge of the transactions at the current prices (see fees.ts). */
579
+ async costs(transactions) {
580
+ const prices = await this.pricer.prices();
581
+ return { ...costOf(transactions, prices), prices };
582
+ }
583
+ /** What `stake` leaves on the account: `reserve`, but never less than the upfront gas of the exit it will need. */
584
+ reserveAt(prices) {
585
+ const gas = this.gas.unstake > this.gas.withdraw ? this.gas.unstake : this.gas.withdraw;
586
+ const exit = costOf([{ receiverId: this.pool.contract, actions: [fc("unstake", { amount: MAX_U128_DIGITS }, gas, 0n)] }], prices).upfront;
587
+ return exit > this.reserve ? exit : this.reserve;
588
+ }
589
+ tx(actions) {
590
+ const tx = { receiverId: this.pool.contract, actions };
591
+ assertLiquidPlan([tx], this.pool.contract);
592
+ return tx;
593
+ }
594
+ assertWritable(info) {
595
+ if (!info.codeHashKnown) {
596
+ throw new LiquidStakingError("unknown-contract-code", `${info.contract} runs code ${info.codeHash || "(none)"}, which is not pinned. A contract upgrade needs a new pin before the module writes to it again.`, { details: { codeHash: info.codeHash, pinned: [...this.pool.codeHashes] } });
597
+ }
598
+ if (info.paused) throw new LiquidStakingError("contract-paused", `${info.name} (${info.contract}) is paused: it rejects every call until it resumes.`);
599
+ }
600
+ /** The paused features a plan's calls check (see PAUSE_KEYS); empty when every call goes through. */
601
+ static pausedFor(info, methods) {
602
+ const keys = new Set(methods.flatMap((m) => PAUSE_KEYS[m] ?? []));
603
+ return info.pausedFeatures.filter((k) => keys.has(k));
604
+ }
605
+ /** Withdrawals are stopped: the whole contract or its withdraw feature is paused. */
606
+ static withdrawPaused(info) {
607
+ return info.paused || _LiquidStakingProtocolNear.pausedFor(info, ["withdraw_all"]).length > 0;
608
+ }
609
+ /** Refuses transactions that call a feature the contract has paused on its own (rNEAR's per-feature pause): they would fail and burn the gas. */
610
+ static assertNotPaused(info, transactions) {
611
+ const methods = transactions.flatMap((t) => t.actions.flatMap((a) => "functionCall" in a ? [a.functionCall.methodName] : []));
612
+ const paused = _LiquidStakingProtocolNear.pausedFor(info, methods);
613
+ if (paused.length === 0) return;
614
+ const what = [...new Set(paused.map((k) => FEATURE_WORDS[k] ?? k))].join(" and ");
615
+ throw new LiquidStakingError("contract-paused", `${info.name} (${info.contract}) has ${what} paused (${paused.join(", ")}): this transaction would fail until it resumes.`, { details: { pausedFeatures: paused } });
616
+ }
617
+ /**
618
+ * NEAR the contract keeps from a stake for the account's NEP-145 registration: storage_balance_bounds.min
619
+ * when the contract charges it (rNEAR) and the account is not registered yet, else 0. Read live.
620
+ */
621
+ async storageFee(me) {
622
+ if (!this.pool.firstStakePaysStorage) return 0n;
623
+ const [balance, bounds] = await Promise.all([
624
+ this.view("storage_balance_of", { account_id: me }),
625
+ this.view("storage_balance_bounds")
626
+ ]);
627
+ if (balance !== null && balance !== void 0) return 0n;
628
+ return amountOf(bounds?.min, "storage_balance_bounds.min");
629
+ }
630
+ async readAccount(me, price) {
631
+ const [balance, details, storage] = await Promise.all([
632
+ this.view("ft_balance_of", { account_id: me }),
633
+ this.view("get_account_details", { account_id: me }),
634
+ this.view("storage_balance_of", { account_id: me })
635
+ ]);
636
+ if (!details || typeof details !== "object") throw new import_core4.NetworkError(`${this.pool.contract}.get_account_details: no account details in the answer`);
637
+ if (typeof details.can_withdraw !== "boolean") throw new import_core4.NetworkError(`${this.pool.contract}.get_account_details: can_withdraw is not a boolean`);
638
+ const shares = amountOf(balance, "ft_balance_of");
639
+ return {
640
+ shares,
641
+ value: valueAtPrice(shares, price),
642
+ unstaked: amountOf(details.unstaked_balance, "get_account_details.unstaked_balance"),
643
+ unlockEpoch: amountOf(details.unstaked_available_epoch_height, "get_account_details.unstaked_available_epoch_height"),
644
+ canWithdraw: details.can_withdraw,
645
+ registered: storage !== null && storage !== void 0,
646
+ stakedNear: amountOf(details.staked_balance, "get_account_details.staked_balance")
647
+ };
648
+ }
649
+ contractUnlock(epoch, unlockEpoch) {
650
+ const at = epochStartsAt(epoch, unlockEpoch);
651
+ return { epoch: unlockEpoch, earliestEpoch: unlockEpoch, latestEpoch: unlockEpoch, at, earliestAt: at, latestAt: at, source: "contract" };
652
+ }
653
+ /**
654
+ * The contract can pay `amount` now: its liquid balance minus what it must keep covers it. It
655
+ * keeps 1 NEAR itself, and the runtime refuses a receipt that leaves it below its storage cost
656
+ * (the whole transaction would fail, on every retry).
657
+ */
658
+ static payable(info, amount) {
659
+ return info.liquidity - info.kept >= amount;
660
+ }
661
+ // ── Reads ──────────────────────────────────────────────────────────────────
662
+ /** The epoch clock: height, start, measured duration (~6.9 h on mainnet), estimated end. */
663
+ async getEpoch() {
664
+ return readEpoch(this.client(), { numbers: () => this.epochNumbers(), blockTimes: this.blockTimes });
665
+ }
666
+ /** Contract state: price, totals, pause flag, live code hash, liquidity, fee. Read fresh every time. */
667
+ async getPoolInfo() {
668
+ const pool = this.pool;
669
+ const rpc = this.client();
670
+ const [meta, summary, pausedFlag, pausedKeys, account, beneficiaries] = await Promise.all([
671
+ this.view("ft_metadata"),
672
+ this.view("get_summary"),
673
+ // A contract answer other than `false` (a missing method, a panic, a non-boolean) counts as paused; a transport failure is thrown.
674
+ this.view("is_paused").then((v) => v !== false, (e) => {
675
+ if (e instanceof import_wallet_near5.NearRpcError) return true;
676
+ throw e;
677
+ }),
678
+ // Per-feature pauses (near-plugins Pausable, rNEAR): null when none. LiNEAR has only `is_paused`
679
+ // and is not asked; a custom contract without the method has none. Any other contract answer (a
680
+ // panic, a non-list) counts as paused.
681
+ !pool.featurePauses ? Promise.resolve([]) : this.view("pa_all_paused").then((v) => {
682
+ if (v === null) return [];
683
+ return Array.isArray(v) && v.every((k) => typeof k === "string") ? [...v].sort() : "unreadable";
684
+ }, (e) => {
685
+ if (e instanceof import_wallet_near5.NearRpcError) return methodMissing(e) ? [] : "unreadable";
686
+ throw e;
687
+ }),
688
+ rpc.viewAccount(pool.contract),
689
+ this.view("get_beneficiaries").catch((e) => {
690
+ if (e instanceof import_wallet_near5.NearRpcError) return null;
691
+ throw e;
692
+ })
693
+ ]);
694
+ if (!summary || typeof summary !== "object") throw new import_core4.NetworkError(`${pool.contract}.get_summary: no summary in the answer`);
695
+ if (meta?.decimals !== 24) throw new import_core4.NetworkError(`${pool.contract}.ft_metadata: expected 24 decimals, got ${String(meta?.decimals)}`);
696
+ let feeBps = 0;
697
+ for (const bps of Object.values(beneficiaries ?? {})) if (typeof bps === "number" && Number.isInteger(bps) && bps >= 0) feeBps += bps;
698
+ const codeHash = typeof account?.code_hash === "string" ? account.code_hash : "";
699
+ const storageCost = account ? amountOf(account.storage_usage, "view_account.storage_usage") * import_wallet_near5.STORAGE_PRICE_PER_BYTE : 0n;
700
+ const paused = pausedFlag || pausedKeys === "unreadable" || pausedKeys.includes("ALL");
701
+ return {
702
+ contract: pool.contract,
703
+ symbol: typeof meta.symbol === "string" ? meta.symbol : pool.symbol,
704
+ name: pool.name,
705
+ decimals: 24,
706
+ price: amountOf(summary.ft_price, "get_summary.ft_price"),
707
+ totalStaked: amountOf(summary.total_staked_near_amount, "get_summary.total_staked_near_amount"),
708
+ totalShares: amountOf(summary.total_share_amount, "get_summary.total_share_amount"),
709
+ validators: typeof summary.validators_num === "number" ? summary.validators_num : 0,
710
+ paused,
711
+ pausedFeatures: pausedKeys === "unreadable" ? [] : pausedKeys,
712
+ codeHash,
713
+ codeHashKnown: codeHash !== "" && pool.codeHashes.includes(codeHash),
714
+ liquidity: account ? amountOf(account.amount, "view_account.amount") : 0n,
715
+ kept: storageCost > CONTRACT_MIN_RESERVE_BALANCE ? storageCost : CONTRACT_MIN_RESERVE_BALANCE,
716
+ feeBps
717
+ };
718
+ }
719
+ /** The account in the contract: tokens, their NEAR value, unstaked NEAR, exact unlock epoch, registration. */
720
+ async getAccountDetails() {
721
+ const me = await this.me();
722
+ const price = amountOf(await this.view("ft_price"), "ft_price");
723
+ const a = await this.readAccount(me, price);
724
+ return { shares: a.shares, value: a.value, unstaked: a.unstaked, unlockEpoch: a.unlockEpoch, canWithdraw: a.canWithdraw, registered: a.registered };
725
+ }
726
+ /** What `stake` can send now: available − reserve − the stake's upfront gas (never below 0). */
727
+ async getMaxStakeable() {
728
+ const me = await this.me();
729
+ const [available, cost] = await Promise.all([this.available(me), this.costs([this.tx([fc("deposit_and_stake", {}, this.gas.stake, MIN_STAKE)])])]);
730
+ return _LiquidStakingProtocolNear.maxStakeable(available, this.reserveAt(cost.prices), cost.upfront);
731
+ }
732
+ static maxStakeable(available, reserve, upfront) {
733
+ const max = available - reserve - upfront;
734
+ return max > 0n ? max : 0n;
735
+ }
736
+ /**
737
+ * APR in percent: the `apr` hook, else the token price's growth over `aprWindowEpochs` (default 24,
738
+ * ~7 days), annualized by the two blocks' timestamps. The past price comes from the archival RPC;
739
+ * when that fails, from a 2-epoch window on the regular RPC. Cached for 10 minutes.
740
+ */
741
+ async getApr() {
742
+ if (this._config.apr) return await this._config.apr();
743
+ const hit = this.aprCache;
744
+ if (hit && Date.now() - hit.at < APR_TTL_MS) return await hit.value;
745
+ const value = this.priceApr();
746
+ this.aprCache = { at: Date.now(), value };
747
+ value.catch(() => {
748
+ if (this.aprCache?.value === value) this.aprCache = void 0;
749
+ });
750
+ return await value;
751
+ }
752
+ async priceApr() {
753
+ const rpc = this.client();
754
+ const now = await this.priceAt(rpc);
755
+ try {
756
+ const past = await this.priceAt(this.archivalClient(), now.height - BigInt(this.aprWindowEpochs) * EPOCH_LENGTH);
757
+ return aprFromPrices(past.price, now.price, past.ms, now.ms);
758
+ } catch (archivalError) {
759
+ try {
760
+ const past = await this.priceAt(rpc, now.height - APR_FALLBACK_EPOCHS * EPOCH_LENGTH);
761
+ return aprFromPrices(past.price, now.price, past.ms, now.ms);
762
+ } catch {
763
+ throw archivalError;
764
+ }
765
+ }
766
+ }
767
+ /** `ft_price` at a height (the next produced block when it was skipped), or at the final block, with that block's time. */
768
+ async priceAt(rpc, height) {
769
+ const contract = this.pool.contract;
770
+ const args = (0, import_wallet_near5.toBase64)(new TextEncoder().encode("{}"));
771
+ const query = async (blockRef) => {
772
+ const r = await rpc.fetch("query", { request_type: "call_function", account_id: contract, method_name: "ft_price", args_base64: args, ...blockRef });
773
+ if (!r || r.error || !Array.isArray(r.result) || typeof r.block_height !== "number") throw new import_core4.NetworkError(`${contract}.ft_price: no result${r?.error ? ` (${r.error})` : ""}`);
774
+ return { price: amountOf(JSON.parse(new TextDecoder().decode(Uint8Array.from(r.result))), "ft_price"), height: BigInt(r.block_height) };
775
+ };
776
+ let read;
777
+ if (height === void 0) read = await query({ finality: "final" });
778
+ else {
779
+ let last;
780
+ for (let i = 0n; i <= BigInt(SKIP_TRIES2) && !read; i++) {
781
+ try {
782
+ read = await query({ block_id: (0, import_core4.bigintToNumber)(height + i) });
783
+ } catch (e) {
784
+ if (!(e instanceof import_wallet_near5.NearRpcError) || !/UNKNOWN_BLOCK/i.test(e.errorName ?? "")) throw e;
785
+ last = e;
786
+ }
787
+ }
788
+ if (!read) throw last;
789
+ }
790
+ const known = this.blockTimes.get(read.height);
791
+ const ms = known ?? (await blockAt(rpc, read.height)).ms;
792
+ this.blockTimes.set(read.height, ms);
793
+ return { ...read, ms };
794
+ }
795
+ /**
796
+ * The position, Tonstakers-style: `balance` = tokens held, `rate` = price (yoctoNEAR per token,
797
+ * 10^24 = 1:1), `total` = their NEAR value; `unstaked` and `withdrawable` (unlocked and payable
798
+ * from the contract's liquid balance now) beside.
799
+ */
800
+ async getStakedBalance() {
801
+ const me = await this.me();
802
+ const info = await this.getPoolInfo();
803
+ const a = await this.readAccount(me, info.price);
804
+ const unstaked = a.unstaked > UNSTAKED_DUST ? a.unstaked : 0n;
805
+ const withdrawable = unstaked > 0n && a.canWithdraw && _LiquidStakingProtocolNear.payable(info, unstaked) && !_LiquidStakingProtocolNear.withdrawPaused(info) ? unstaked : 0n;
806
+ return { balance: a.shares, wrappedBalance: 0n, rate: info.price, total: a.value, unstaked, withdrawable, price: info.price };
807
+ }
808
+ /**
809
+ * The account's unstaked NEAR as one request (a contract keeps one unstaked balance per account):
810
+ * id `poolRequestId(contract)`, `unlockEpoch` exact from the contract. `claimable` needs the epoch
811
+ * reached, the contract's liquid balance to cover it (`awaitingLiquidity` otherwise) and withdrawals
812
+ * not paused (`paused`). `timestamp` is 0: the contract does not keep the unstake time.
813
+ */
814
+ async getWithdrawalRequests() {
815
+ const me = await this.me();
816
+ const info = await this.getPoolInfo();
817
+ const a = await this.readAccount(me, info.price);
818
+ if (a.unstaked <= UNSTAKED_DUST) return { requests: [], pendingAmount: 0n, claimableAmount: 0n, claimableIds: [] };
819
+ const awaitingLiquidity = a.canWithdraw && !_LiquidStakingProtocolNear.payable(info, a.unstaked);
820
+ const paused = _LiquidStakingProtocolNear.withdrawPaused(info);
821
+ const claimable = a.canWithdraw && !awaitingLiquidity && !paused;
822
+ const id = poolRequestId(info.contract);
823
+ const request = {
824
+ id,
825
+ amount: a.unstaked,
826
+ timestamp: 0,
827
+ claimable,
828
+ contract: info.contract,
829
+ unlockEpoch: a.unlockEpoch,
830
+ awaitingLiquidity,
831
+ paused,
832
+ unlock: claimable ? null : this.contractUnlock(await this.getEpoch(), a.unlockEpoch)
833
+ };
834
+ return {
835
+ requests: [request],
836
+ pendingAmount: claimable ? 0n : a.unstaked,
837
+ claimableAmount: claimable ? a.unstaked : 0n,
838
+ claimableIds: claimable ? [id] : []
839
+ };
840
+ }
841
+ // ── Writes ─────────────────────────────────────────────────────────────────
842
+ /** Plans with fresh reads, compares with `expected`, then sends each transaction in order. */
843
+ async send(method, plan, o) {
844
+ const account = this.requireSigningAccount(method);
845
+ const quote = await plan();
846
+ assertLiquidPlan(quote.transactions, this.pool.contract);
847
+ if (o?.expected !== void 0 && !sameTransactions(o.expected, quote.transactions)) {
848
+ throw new LiquidStakingError("quote-changed", "The transactions changed since the quote (the contract or the account moved on): review the new ones and confirm again.", { details: { transactions: quote.transactions } });
849
+ }
850
+ if (o?.maxFee !== void 0 && quote.fee > BigInt(o.maxFee)) {
851
+ throw new LiquidStakingError("max-fee-exceeded", `The network fee may reach ${near(quote.fee)}, above the maximum of ${near(BigInt(o.maxFee))} for this write.`, { details: { fee: quote.fee, maxFee: BigInt(o.maxFee) } });
852
+ }
853
+ const options = o?.maxFee !== void 0 ? { maxFee: o.maxFee } : void 0;
854
+ const hashes = [];
855
+ let fee = 0n;
856
+ for (const tx of quote.transactions) {
857
+ let r;
858
+ try {
859
+ r = await account.sendTransaction(copyTx(tx), options);
860
+ } catch (e) {
861
+ throw Object.assign(e instanceof Error ? e : new Error(String(e)), { sent: [...hashes] });
862
+ }
863
+ hashes.push(r.hash);
864
+ fee += BigInt(r.fee ?? 0);
865
+ }
866
+ return { ...quote, fee, hash: hashes[0], hashes };
867
+ }
868
+ async planStake(o) {
869
+ const amount = positiveAmount(o?.amount, "yoctoNEAR");
870
+ if (amount < MIN_STAKE) throw new LiquidStakingError("below-minimum", `A stake must be at least ${near(MIN_STAKE)}.`);
871
+ const me = await this.me();
872
+ const info = await this.getPoolInfo();
873
+ this.assertWritable(info);
874
+ const transactions = [this.tx([fc("deposit_and_stake", {}, this.gas.stake, amount)])];
875
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
876
+ const storageFee = await this.storageFee(me);
877
+ if (storageFee > 0n && amount - storageFee < MIN_STAKE) {
878
+ throw new LiquidStakingError("below-minimum", `A first stake into ${info.name} must be at least ${near(storageFee + MIN_STAKE)}: the contract keeps ${near(storageFee)} of it for the account's registration.`, { details: { minimum: storageFee + MIN_STAKE, storageFee } });
879
+ }
880
+ const warnings = storageFee > 0n ? [{ code: "pays-storage", message: `First stake into ${info.name}: the contract keeps ${near(storageFee)} of the amount for the account's registration and stakes the rest.` }] : [];
881
+ const [available, { fee, upfront, prices }, apr] = await Promise.all([this.available(me), this.costs(transactions), this.getApr().catch(() => null)]);
882
+ const reserve = this.reserveAt(prices);
883
+ const required = amount + upfront + reserve;
884
+ if (required > available) throw new import_core4.InsufficientFundsError(required, available, "NEAR");
885
+ return {
886
+ fee,
887
+ upfront,
888
+ reserve,
889
+ amount,
890
+ storageFee,
891
+ shares: sharesForNear(amount - storageFee, info),
892
+ price: info.price,
893
+ apr,
894
+ maxStakeable: _LiquidStakingProtocolNear.maxStakeable(available, reserve, upfront),
895
+ transactions,
896
+ warnings
897
+ };
898
+ }
899
+ /** The stake's transaction, fee, tokens expected and APR; nothing is signed. */
900
+ async quoteStake(options) {
901
+ return this.planStake(options);
902
+ }
903
+ /**
904
+ * Stakes exactly `amount` yoctoNEAR (`deposit_and_stake`) for the token. There is no "stake
905
+ * everything": pass the amount (at most `getMaxStakeable()`).
906
+ */
907
+ async stake(options) {
908
+ return this.send("stake", () => this.planStake(options), options);
909
+ }
910
+ async planUnstake(o) {
911
+ const requested = o?.amount === "all" ? "all" : positiveAmount(o?.amount, "token base units");
912
+ const me = await this.me();
913
+ const info = await this.getPoolInfo();
914
+ this.assertWritable(info);
915
+ const [a, epoch] = await Promise.all([this.readAccount(me, info.price), this.getEpoch()]);
916
+ if (a.shares === 0n) throw new LiquidStakingError("nothing-staked", `${me} holds no ${info.symbol}.`);
917
+ if (requested !== "all" && requested > a.shares) {
918
+ throw new LiquidStakingError("exceeds-balance", `Asked to unstake ${requested} ${info.symbol} base units; the balance is ${a.shares}.`, { details: { balance: a.shares } });
919
+ }
920
+ const all = requested === "all" || requested === a.shares;
921
+ const shares = all ? a.shares : requested;
922
+ const amount = all ? a.stakedNear : nearForShares(shares, info);
923
+ if (amount === 0n) throw new LiquidStakingError("below-minimum", `${shares} ${info.symbol} base units are worth less than 1 yoctoNEAR.`);
924
+ const unstake = all ? fc("unstake_all", {}, this.gas.unstake, 0n) : fc("unstake", { amount: String(amount) }, this.gas.unstake, 0n);
925
+ _LiquidStakingProtocolNear.assertNotPaused(info, [this.tx([unstake])]);
926
+ const warnings = [];
927
+ const actions = [];
928
+ let withdrawsFirst = 0n, relocks = 0n, resetsTimer = false;
929
+ if (a.unstaked > UNSTAKED_DUST && a.canWithdraw) {
930
+ const withdrawPaused = _LiquidStakingProtocolNear.withdrawPaused(info);
931
+ if (_LiquidStakingProtocolNear.payable(info, a.unstaked) && !withdrawPaused) {
932
+ actions.push(fc("withdraw_all", {}, this.gas.withdraw, 0n));
933
+ withdrawsFirst = a.unstaked;
934
+ warnings.push({ code: "withdraws-unlocked-first", message: `${near(a.unstaked)} already unlocked is withdrawn to the account in the same transaction, so the new unstake does not lock it again.` });
935
+ } else if (!o.allowRelock || amount < MIN_STAKE) {
936
+ const why = withdrawPaused ? "has withdrawals paused" : "cannot pay it out yet (it is waiting for its payout)";
937
+ throw new LiquidStakingError("relock-refused", `${near(a.unstaked)} is unlocked, but ${info.name} ${why}. A new unstake now would lock it again for 4+ epochs: ${withdrawPaused ? "wait until withdrawals resume" : "claim it first"}${amount < MIN_STAKE ? "" : ", or pass allowRelock"}.`, { details: { unstaked: a.unstaked, liquidity: info.liquidity, kept: info.kept, withdrawPaused } });
938
+ } else {
939
+ relocks = a.unstaked;
940
+ warnings.push({ code: "relocks-unlocked", message: `${near(a.unstaked)} already unlocked locks again with this unstake (the contract ${withdrawPaused ? "has withdrawals paused" : "cannot pay it out yet"}): the whole unstaked balance waits 4+ more epochs.` });
941
+ }
942
+ } else if (a.unstaked > UNSTAKED_DUST) {
943
+ if (amount < MIN_STAKE || !o.allowTimerReset) {
944
+ throw new LiquidStakingError("timer-reset-refused", `${near(a.unstaked)} is still unbonding (unlocks at epoch ${a.unlockEpoch}). A new unstake restarts the wait for the whole unstaked balance: 4+ epochs from now${amount < MIN_STAKE ? "" : ". Wait until it unlocks and claim it, or pass allowTimerReset"}.`, { details: { unstaked: a.unstaked, unlockEpoch: a.unlockEpoch, amount } });
945
+ }
946
+ resetsTimer = true;
947
+ warnings.push({ code: "resets-unbonding-timer", message: `${near(a.unstaked)} is already unstaking (unlocks at epoch ${a.unlockEpoch}). A new unstake restarts the wait for the whole unstaked balance: 4+ epochs from now.` });
948
+ }
949
+ actions.push(unstake);
950
+ warnings.push({ code: "unlock-may-be-later", message: "Unstaking takes 4 or more epochs (~6.9 h each, about 21\u201335 h or more): the contract may add epochs for large amounts or after its epoch settlement. The exact epoch is known after the unstake." });
951
+ const transactions = [this.tx(actions)];
952
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
953
+ const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
954
+ if (upfront > available) throw new import_core4.InsufficientFundsError(upfront, available, "NEAR");
955
+ const earliestEpoch = epoch.height + MIN_EPOCHS_TO_UNLOCK;
956
+ return {
957
+ fee,
958
+ upfront,
959
+ shares,
960
+ amount,
961
+ id: poolRequestId(info.contract),
962
+ withdrawsFirst,
963
+ resetsTimer,
964
+ relocks,
965
+ unlock: { epoch: null, earliestEpoch, latestEpoch: null, at: null, earliestAt: epochStartsAt(epoch, earliestEpoch), latestAt: null, source: "estimate" },
966
+ transactions,
967
+ warnings
968
+ };
969
+ }
970
+ /** The unstake's transaction, fee and unlock estimate; nothing is signed. `amount` is in token base units. */
971
+ async quoteRequestWithdrawal(options) {
972
+ return this.planUnstake(options);
973
+ }
974
+ /**
975
+ * Unstakes `amount` token base units (`unstake` with their NEAR value), or `'all'` (`unstake_all`).
976
+ * An unlocked balance is withdrawn in the same transaction first. Once it is final,
977
+ * `getAccountDetails().unlockEpoch` is the exact epoch the NEAR unlocks at; reads use final blocks,
978
+ * so right after the send they still show the previous one (show the result's `unlock` meanwhile).
979
+ */
980
+ async requestWithdrawal(options) {
981
+ return { ...await this.send("requestWithdrawal", () => this.planUnstake(options), options), approveHash: null };
982
+ }
983
+ async planClaim(o = {}) {
984
+ const me = await this.me();
985
+ const info = await this.getPoolInfo();
986
+ this.assertWritable(info);
987
+ const a = await this.readAccount(me, info.price);
988
+ const id = poolRequestId(info.contract);
989
+ if (o.ids !== void 0) {
990
+ if (!Array.isArray(o.ids)) throw new LiquidStakingError("unknown-request", "`ids` must be a list of request ids.");
991
+ const ids = [...new Set(o.ids.map((x) => BigInt(x)))];
992
+ const unknown = ids.filter((x) => x !== id);
993
+ if (unknown.length > 0) throw new LiquidStakingError("unknown-request", `Unknown request id ${unknown.join(", ")}: ${info.contract} keeps one request per account, id ${id}.`, { details: { ids: unknown } });
994
+ if (ids.length === 0) throw new LiquidStakingError("nothing-to-claim", "No request ids were given.");
995
+ }
996
+ if (a.unstaked <= UNSTAKED_DUST) throw new LiquidStakingError("nothing-to-claim", `${me} has no unstaked NEAR in ${info.contract}.`);
997
+ if (!a.canWithdraw) {
998
+ const unlock = this.contractUnlock(await this.getEpoch(), a.unlockEpoch);
999
+ throw new LiquidStakingError("not-withdrawable", `${near(a.unstaked)} unlocks at epoch ${a.unlockEpoch}.`, { details: { unlock, amount: a.unstaked } });
1000
+ }
1001
+ if (!_LiquidStakingProtocolNear.payable(info, a.unstaked)) {
1002
+ throw new LiquidStakingError("awaiting-liquidity", `${near(a.unstaked)} is unlocked; ${info.name} is waiting for its payout from the validators before it can pay it (it holds ${near(info.liquidity)} and keeps ${near(info.kept)} for its own storage).`, { details: { amount: a.unstaked, liquidity: info.liquidity, kept: info.kept } });
1003
+ }
1004
+ const transactions = [this.tx([fc("withdraw_all", {}, this.gas.withdraw, 0n)])];
1005
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
1006
+ const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
1007
+ if (upfront > available) throw new import_core4.InsufficientFundsError(upfront, available, "NEAR");
1008
+ return { fee, upfront, amount: a.unstaked, transactions };
1009
+ }
1010
+ /** The claim's transaction (`withdraw_all`) and fee; nothing is signed. */
1011
+ async quoteClaimWithdrawals(options = {}) {
1012
+ return this.planClaim(options);
1013
+ }
1014
+ /** Withdraws the unstaked NEAR (`withdraw_all`) once unlocked and payable. */
1015
+ async claimWithdrawals(options = {}) {
1016
+ return this.send("claimWithdrawals", () => this.planClaim(options), options);
1017
+ }
1018
+ // ── Activity ───────────────────────────────────────────────────────────────
1019
+ /** Labels LiNEAR-family staking transactions offline; see `activity.ts`. */
1020
+ describeActivity(tx, ctx) {
1021
+ const pool = typeof this._config.pool === "string" ? void 0 : this._config.pool;
1022
+ return describeLiquidNearStakingActivity(tx, ctx, pool ? { contracts: [{ contract: pool.contract, symbol: pool.symbol, ...pool.name ? { name: pool.name } : {} }] } : {});
1023
+ }
1024
+ };
1025
+ //# sourceMappingURL=index.cjs.map