@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.
@@ -0,0 +1,622 @@
1
+ import { ClaimWithdrawalsOptions, WriteOptions, StakeOptions, StakedBalance, WithdrawalRequestsView, WithdrawalRequest, WithdrawalRequestOptions, TransferResult, StakingProtocol, IWalletAccountReadOnly, IWalletAccount, ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
2
+ import { NearTransaction, NearProvider, NearRpc, NearAction } from '@anywalletkit/wallet-near';
3
+
4
+ /** The NEAR network the module works on. */
5
+ type NearNetwork = 'mainnet' | 'testnet';
6
+ /** A LiNEAR-family contract the app vouches for (same interface as linear-protocol.near). */
7
+ interface LiquidPoolConfig {
8
+ contract: string;
9
+ symbol: string;
10
+ name?: string;
11
+ /** code_hash values accepted for writes. Required: a contract upgrade is refused until the app pins the new build. */
12
+ codeHashes: readonly string[];
13
+ /**
14
+ * `deposit_and_stake` keeps storage_balance_bounds.min (0.00125 NEAR) of an unregistered account's
15
+ * first deposit, as rNEAR does (LiNEAR does not). Default: the built-in preset's value when
16
+ * `contract` is a preset's account (a re-pin after an upgrade), else true: quotes then never show
17
+ * more tokens than the contract mints, and a first stake that leaves less than MIN_STAKE after the
18
+ * fee is refused (at or below the fee the contract itself would fail it).
19
+ */
20
+ firstStakePaysStorage?: boolean;
21
+ }
22
+ /** Configuration of {@link LiquidStakingProtocolNear}. Only `pool` is required. */
23
+ interface LiquidStakingNearConfig {
24
+ /** `'linear'` (LiNEAR), `'rnear'` (Rhea rNEAR, mainnet only), or a family contract. Required. */
25
+ pool: LiquidPresetName | LiquidPoolConfig;
26
+ /** Default: from the account's chain (`near:testnet` → testnet, else mainnet). */
27
+ network?: NearNetwork;
28
+ /** RPC url(s) or transport(s); a list fails over. Default: the wallet-near account's own provider. */
29
+ provider?: NearProvider | NearProvider[];
30
+ /** Archival RPC for the APR's past price (default fastnear's archival endpoint for the network). */
31
+ archivalProvider?: NearProvider | NearProvider[];
32
+ /** Per-request timeout for url providers, ms (default 15 000). */
33
+ timeoutMs?: number;
34
+ /** yoctoNEAR `stake` leaves on the account (default 0.02 NEAR); never less than one unstake's upfront gas. */
35
+ reserve?: bigint | number;
36
+ /** Prepaid gas overrides (defaults: 30 Tgas each). All of it is bought upfront at min_gas_purchase_price: keep it small. */
37
+ gas?: {
38
+ stake?: bigint;
39
+ unstake?: bigint;
40
+ withdraw?: bigint;
41
+ };
42
+ /** Replaces the price-based APR estimate (an app's or an indexer's figure), percent. */
43
+ apr?: () => Promise<number> | number;
44
+ /** Epochs the APR estimate looks back over (default 24, ~7 days). */
45
+ aprWindowEpochs?: number;
46
+ }
47
+ /** The contract's state. Amounts in yoctoNEAR / token base units (24 decimals). */
48
+ interface LiquidPoolInfo {
49
+ contract: string;
50
+ symbol: string;
51
+ name: string;
52
+ decimals: 24;
53
+ /** yoctoNEAR per 1 whole token (`ft_price`, 10^24 = 1:1). */
54
+ price: bigint;
55
+ /** NEAR staked by the contract (`get_summary.total_staked_near_amount`). */
56
+ totalStaked: bigint;
57
+ /** Token supply (`get_summary.total_share_amount`). */
58
+ totalShares: bigint;
59
+ validators: number;
60
+ /** `is_paused`, or 'ALL' in `pa_all_paused`; a missing `is_paused` counts as paused. */
61
+ paused: boolean;
62
+ /**
63
+ * Features the contract has paused on their own (`pa_all_paused` of a near-plugins contract such as
64
+ * rNEAR: 'internal_deposit', 'internal_stake', 'internal_unstake', 'internal_withdraw'). A write
65
+ * that calls one is refused with 'contract-paused'. Empty when nothing is paused or the contract has
66
+ * no per-feature pause (LiNEAR).
67
+ */
68
+ pausedFeatures: string[];
69
+ codeHash: string;
70
+ /** The live code hash is one the module (or the app's config) pins. */
71
+ codeHashKnown: boolean;
72
+ /** The contract's liquid balance (view_account.amount): what withdrawals are paid from. */
73
+ liquidity: bigint;
74
+ /** What the contract cannot pay out: max(1 NEAR, its storage cost). A withdrawal needs liquidity − kept ≥ amount. */
75
+ kept: bigint;
76
+ /** Protocol fee on rewards, basis points (sum of `get_beneficiaries`). */
77
+ feeBps: number;
78
+ }
79
+ /** The account in the contract (`get_account_details` + `ft_balance_of` + `storage_balance_of`). */
80
+ interface LiquidAccountDetails {
81
+ /** LST held, token base units. */
82
+ shares: bigint;
83
+ /** `shares` valued in NEAR at the current price. */
84
+ value: bigint;
85
+ /** NEAR unstaked and waiting (or ready) in the contract. */
86
+ unstaked: bigint;
87
+ /** Epoch the unstaked balance unlocks at (exact, from the contract). */
88
+ unlockEpoch: bigint;
89
+ /** The contract's own flag: unlock epoch reached. */
90
+ canWithdraw: boolean;
91
+ /** NEP-145 registered (can receive the token by transfer). */
92
+ registered: boolean;
93
+ }
94
+ /** The epoch clock. Heights are block heights; times are unix ms estimates. */
95
+ interface NearEpoch {
96
+ height: bigint;
97
+ startBlock: bigint;
98
+ length: bigint;
99
+ block: bigint;
100
+ blocksLeft: bigint;
101
+ startedAt: number;
102
+ epochMs: number;
103
+ endsAt: number;
104
+ }
105
+ /** When an unstaked balance becomes withdrawable (same shape as the native module's). */
106
+ interface UnlockEstimate {
107
+ epoch: bigint | null;
108
+ earliestEpoch: bigint;
109
+ latestEpoch: bigint | null;
110
+ at: number | null;
111
+ earliestAt: number;
112
+ latestAt: number | null;
113
+ source: 'history' | 'contract' | 'estimate';
114
+ }
115
+ /** Tonstakers-style balance: `balance` = token, `rate` = price (1e24), `total` = NEAR value. */
116
+ interface LiquidStakedBalance extends StakedBalance {
117
+ unstaked: bigint;
118
+ /** Unstaked, unlocked and payable now (contract liquidity checked). */
119
+ withdrawable: bigint;
120
+ price: bigint;
121
+ }
122
+ type LiquidStakingWarningCode = 'resets-unbonding-timer' | 'withdraws-unlocked-first' | 'relocks-unlocked' | 'unlock-may-be-later' | 'pays-storage';
123
+ interface LiquidStakingWarning {
124
+ code: LiquidStakingWarningCode;
125
+ message: string;
126
+ }
127
+ /** Options every write shares. */
128
+ interface LiquidWriteOptions extends WriteOptions {
129
+ /** The `transactions` of the confirmed quote; the write refuses with `quote-changed` when the fresh plan differs. */
130
+ expected?: NearTransaction[];
131
+ }
132
+ interface LiquidStakeOptions extends StakeOptions, LiquidWriteOptions {
133
+ }
134
+ interface LiquidStakeQuote {
135
+ /** Upper bound of the network fee, yoctoNEAR (all gas burnt, at the gas price + 10 %). Passes as `maxFee`. */
136
+ fee: bigint;
137
+ /**
138
+ * NEAR the node holds back when it accepts the transaction, beside the deposit: the prepaid gas,
139
+ * bought at min_gas_purchase_price. The unburnt part comes back a few blocks later.
140
+ */
141
+ upfront: bigint;
142
+ /** NEAR the stake leaves on the account: the configured reserve, but at least one unstake's `upfront`. */
143
+ reserve: bigint;
144
+ amount: bigint;
145
+ /**
146
+ * NEAR the contract keeps from `amount` for the account's NEP-145 registration: storage_balance_bounds.min
147
+ * (0.00125 NEAR) on a first stake into rNEAR, else 0. Warning 'pays-storage' when above 0.
148
+ */
149
+ storageFee: bigint;
150
+ /** Tokens expected for `amount − storageFee` at the current price (rounded down). */
151
+ shares: bigint;
152
+ price: bigint;
153
+ apr: number | null;
154
+ /** available − reserve − upfront (never below 0). */
155
+ maxStakeable: bigint;
156
+ /** One transaction: a single `deposit_and_stake` (it registers the account itself; no storage_deposit). */
157
+ transactions: NearTransaction[];
158
+ warnings: LiquidStakingWarning[];
159
+ }
160
+ interface LiquidStakeResult extends LiquidStakeQuote {
161
+ hash: string;
162
+ hashes: string[];
163
+ }
164
+ interface LiquidUnstakeOptions extends Omit<WithdrawalRequestOptions, 'amount' | 'token'>, LiquidWriteOptions {
165
+ /** Token base units to unstake, or `'all'` (`unstake_all`). */
166
+ amount: bigint | number | 'all';
167
+ /** Accept that an unlocked balance the contract cannot pay now locks again (default false: refused). */
168
+ allowRelock?: boolean;
169
+ /**
170
+ * Accept that an unstaked balance still unbonding restarts its wait (4+ epochs) together with this
171
+ * amount (default false: refused with 'timer-reset-refused'). Never accepted below MIN_STAKE.
172
+ */
173
+ allowTimerReset?: boolean;
174
+ }
175
+ interface LiquidUnstakeQuote {
176
+ fee: bigint;
177
+ /** See {@link LiquidStakeQuote.upfront}: the account must hold this much NEAR to send the unstake. */
178
+ upfront: bigint;
179
+ /** Tokens burnt (for 'all': the whole balance). */
180
+ shares: bigint;
181
+ /** NEAR moving to unstaked: what `unstake(amount)` is called with (shares × price, rounded down). */
182
+ amount: bigint;
183
+ /** The request id: `poolRequestId(contract)`. */
184
+ id: bigint;
185
+ withdrawsFirst: bigint;
186
+ resetsTimer: boolean;
187
+ /** Unlocked NEAR that locks again because the contract cannot pay it now (only with allowRelock). */
188
+ relocks: bigint;
189
+ /** earliest = current + 4; latestEpoch null (the contract decides); exact via getAccountDetails once the unstake is final. */
190
+ unlock: UnlockEstimate;
191
+ transactions: NearTransaction[];
192
+ warnings: LiquidStakingWarning[];
193
+ }
194
+ interface LiquidUnstakeResult extends LiquidUnstakeQuote {
195
+ hash: string;
196
+ hashes: string[];
197
+ approveHash: null;
198
+ }
199
+ /** The account's unstaked balance as one request. */
200
+ interface LiquidWithdrawalRequest extends WithdrawalRequest {
201
+ contract: string;
202
+ unlockEpoch: bigint;
203
+ /** Unlocked, but the contract's liquidity is below amount + `kept`: waiting for the epoch_withdraw bot. */
204
+ awaitingLiquidity: boolean;
205
+ /** The contract has withdrawals paused (`is_paused`, or 'internal_withdraw' in `pa_all_paused`): not claimable until it resumes. */
206
+ paused: boolean;
207
+ unlock: UnlockEstimate | null;
208
+ }
209
+ type LiquidWithdrawalRequestsView = Omit<WithdrawalRequestsView, 'requests'> & {
210
+ requests: LiquidWithdrawalRequest[];
211
+ };
212
+ interface LiquidClaimOptions extends ClaimWithdrawalsOptions, LiquidWriteOptions {
213
+ }
214
+ interface LiquidClaimQuote {
215
+ fee: bigint;
216
+ /** See {@link LiquidStakeQuote.upfront}. */
217
+ upfront: bigint;
218
+ amount: bigint;
219
+ /** One `withdraw_all` transaction. */
220
+ transactions: NearTransaction[];
221
+ }
222
+ interface LiquidClaimResult extends LiquidClaimQuote {
223
+ hash: string;
224
+ hashes: string[];
225
+ }
226
+ /** Optional account hook: several transactions with one approval (wallet-selector's signAndSendTransactions). */
227
+ interface NearTransactionsSender {
228
+ sendTransactions(transactions: NearTransaction[], options?: WriteOptions): Promise<TransferResult[]>;
229
+ }
230
+
231
+ declare const NEAR_MAINNET = "near:mainnet";
232
+ declare const NEAR_TESTNET = "near:testnet";
233
+ declare const YOCTO_PER_NEAR: bigint;
234
+ declare const TGAS: bigint;
235
+ /** LST decimals for the whole family (LINEAR, rNEAR). */
236
+ declare const LST_DECIMALS = 24;
237
+ /** `ft_price` scale: yoctoNEAR per 1 whole token (10^24 = 1 NEAR per token). */
238
+ declare const PRICE_SCALE: bigint;
239
+ /** Epochs an unstake waits at least (the contract may add more: big amounts, after the epoch's settlement). */
240
+ declare const MIN_EPOCHS_TO_UNLOCK = 4n;
241
+ /** Block heights per epoch, mainnet and testnet. */
242
+ declare const EPOCH_LENGTH = 43200n;
243
+ /** Fallback epoch duration when the chain cannot be read: ~6.9 h (measured 6.9–7.1 h on mainnet in November 2026). */
244
+ declare const TYPICAL_EPOCH_MS = 24840000;
245
+ /**
246
+ * Unstaked balances at or below this many yoctoNEAR are treated as empty. `deposit_and_stake` charges
247
+ * the share price rounded down and leaves the remainder (a yocto or two) unstaked; offering to
248
+ * withdraw it would cost more gas than it is worth.
249
+ */
250
+ declare const UNSTAKED_DUST = 1000000n;
251
+ /**
252
+ * Liquid NEAR the contract keeps for itself: a withdrawal needs contract balance − 1 NEAR ≥ amount
253
+ * (assert_can_withdraw). The runtime also keeps the contract's storage cost (storage_usage × 10^19:
254
+ * ~52 NEAR for rNEAR, ~133 NEAR for LiNEAR), so what it can pay is balance − max(1 NEAR, storage).
255
+ */
256
+ declare const CONTRACT_MIN_RESERVE_BALANCE: bigint;
257
+ /**
258
+ * NEP-145 registration, the same on every family contract (storage_balance_bounds.min, 0.00125 NEAR).
259
+ * `deposit_and_stake` registers an unregistered staker itself; rNEAR keeps this much of that first
260
+ * deposit for it (it stakes `amount − min`), LiNEAR stakes the whole amount. The module reads the
261
+ * live bound; this is the value on 2026-11-08.
262
+ */
263
+ declare const STORAGE_DEPOSIT = 1250000000000000000000n;
264
+ /**
265
+ * NEAR left on the account by `stake`: 0.02 NEAR. `stake` never leaves less than the upfront gas of
266
+ * one unstake (about 0.035 NEAR at today's prices, see fees.ts), so the stake can always be left.
267
+ */
268
+ declare const DEFAULT_RESERVE: bigint;
269
+ /** Smallest stake the module sends: 0.001 NEAR, staked after any storage fee (an rNEAR first stake needs 0.00225 NEAR). */
270
+ declare const MIN_STAKE: bigint;
271
+ /**
272
+ * Pause keys each call checks on a contract with per-feature pauses (rNEAR's near-plugins Pausable,
273
+ * read with `pa_all_paused`): the call fails while any of its keys, or 'ALL', is paused. LiNEAR has
274
+ * one `is_paused` flag for everything.
275
+ */
276
+ declare const PAUSE_KEYS: Readonly<Record<string, readonly string[]>>;
277
+ /**
278
+ * Prepaid gas per call. All of it is bought upfront at min_gas_purchase_price (the unburnt part is
279
+ * refunded), so it is kept near what the calls use. Burnt on mainnet (whole transaction):
280
+ * deposit_and_stake ~3.1–3.5 Tgas on both contracts (it stakes nothing itself: the operator bot does;
281
+ * an rNEAR stake with 30 Tgas prepaid succeeded), unstake_all 3.5, withdraw_all 3.4 (rNEAR) to ~11
282
+ * (LiNEAR). None of them makes a cross-contract call but the payout transfer.
283
+ */
284
+ declare const DEFAULT_GAS: {
285
+ readonly stake: bigint;
286
+ readonly unstake: bigint;
287
+ readonly withdraw: bigint;
288
+ };
289
+ /** Gas price margin of fee estimates (+10 %, as wallet-near's own estimate), so a quoted fee also passes as `maxFee`. */
290
+ declare const GAS_PRICE_MARGIN_NUM = 11n;
291
+ declare const GAS_PRICE_MARGIN_DEN = 10n;
292
+ /**
293
+ * Price per prepaid gas unit when the node cannot report `runtime_config.min_gas_purchase_price`:
294
+ * the mainnet value (protocol 88, Nov 2026), so balance checks fail toward needing more.
295
+ */
296
+ declare const MIN_GAS_PURCHASE_PRICE_FALLBACK: bigint;
297
+ /** Epochs the APR looks back over by default (~7 days at ~6.9 h per epoch). */
298
+ declare const DEFAULT_APR_WINDOW_EPOCHS = 24;
299
+ /** Archival RPC for the APR's past price (regular nodes keep ~5 epochs). */
300
+ declare const DEFAULT_ARCHIVAL_RPC: Record<NearNetwork, string>;
301
+ /** A family contract the module knows: account id per network and the code hashes accepted for writes. */
302
+ interface LiquidPreset {
303
+ symbol: string;
304
+ name: string;
305
+ /** `deposit_and_stake` keeps storage_balance_bounds.min of an unregistered account's first deposit. */
306
+ firstStakePaysStorage: boolean;
307
+ /** Per-feature pauses (near-plugins Pausable, read with `pa_all_paused`) beside `is_paused`. */
308
+ featurePauses: boolean;
309
+ contracts: Partial<Record<NearNetwork, {
310
+ contract: string;
311
+ codeHashes: readonly string[];
312
+ }>>;
313
+ }
314
+ /** Built-in pools. Writes refuse a contract whose live code_hash is not pinned here (or in the app's config). */
315
+ declare const LIQUID_PRESETS: {
316
+ readonly linear: {
317
+ readonly symbol: "LINEAR";
318
+ readonly name: "LiNEAR";
319
+ readonly firstStakePaysStorage: false;
320
+ readonly featurePauses: false;
321
+ readonly contracts: {
322
+ readonly mainnet: {
323
+ readonly contract: "linear-protocol.near";
324
+ readonly codeHashes: readonly ["5LiDVDd1gh7ofVNbiA9VXrWwkv2m8tw46jZqYeuoC3SG"];
325
+ };
326
+ readonly testnet: {
327
+ readonly contract: "linear-protocol.testnet";
328
+ readonly codeHashes: readonly ["8Bby4ofnYGtudd3PinKZ1KyvmUKJVyxmfC99ZccRDVDv"];
329
+ };
330
+ };
331
+ };
332
+ readonly rnear: {
333
+ readonly symbol: "rNEAR";
334
+ readonly name: "Rhea Liquid Near Staking Token";
335
+ readonly firstStakePaysStorage: true;
336
+ readonly featurePauses: true;
337
+ readonly contracts: {
338
+ readonly mainnet: {
339
+ readonly contract: "lst.rhealab.near";
340
+ readonly codeHashes: readonly ["EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv"];
341
+ };
342
+ };
343
+ };
344
+ };
345
+ /** Preset names. */
346
+ type LiquidPresetName = keyof typeof LIQUID_PRESETS;
347
+
348
+ /** A pool resolved for one network. */
349
+ interface ResolvedLiquidPool {
350
+ contract: string;
351
+ symbol: string;
352
+ name: string;
353
+ codeHashes: readonly string[];
354
+ /** See {@link LiquidPoolConfig.firstStakePaysStorage}. */
355
+ firstStakePaysStorage: boolean;
356
+ /** `pa_all_paused` is read (rNEAR, and any custom contract: one without the method has no per-feature pause). */
357
+ featurePauses: boolean;
358
+ preset: LiquidPresetName | null;
359
+ }
360
+ /** Validates a custom pool config (account id, symbol, at least one pinned code hash). */
361
+ declare function validatePoolConfig(pool: LiquidPresetName | LiquidPoolConfig): void;
362
+ /** The contract, symbol and pinned code hashes of a pool on `network`. */
363
+ declare function resolvePool(pool: LiquidPresetName | LiquidPoolConfig, network: NearNetwork): ResolvedLiquidPool;
364
+ /** Stable request id of the account's unstaked balance in a contract: first 8 bytes of sha256(contract) as a u64. */
365
+ declare function poolRequestId(contract: string): bigint;
366
+
367
+ /**
368
+ * Liquid NEAR staking through the LiNEAR contract family (LiNEAR, Rhea rNEAR): `deposit_and_stake`
369
+ * mints the token, `unstake` starts the delayed exit (4+ epochs, exact epoch from the contract),
370
+ * `withdraw_all` pays out once unlocked and the contract holds the NEAR. See the package README.
371
+ *
372
+ * Never builds `ft_transfer_call` or `ft_transfer` into the contract (it has no `ft_on_transfer`:
373
+ * tokens sent that way are lost), and nothing but function calls to the pinned contract. Writes
374
+ * refuse a paused contract (or a paused feature their calls need) or one whose code hash is not
375
+ * pinned. Every quote returns the exact transactions; a write given `expected` refuses when its
376
+ * fresh plan differs.
377
+ */
378
+ declare class LiquidStakingProtocolNear extends StakingProtocol<LiquidStakingNearConfig> {
379
+ readonly reserve: bigint;
380
+ readonly gas: {
381
+ stake: bigint;
382
+ unstake: bigint;
383
+ withdraw: bigint;
384
+ };
385
+ readonly aprWindowEpochs: number;
386
+ private readonly configuredNetwork;
387
+ protected readonly rpc: NearRpc | undefined;
388
+ private archival;
389
+ private numbersCache;
390
+ private readonly blockTimes;
391
+ private aprCache;
392
+ private readonly pricer;
393
+ constructor(account: IWalletAccountReadOnly | IWalletAccount, config: LiquidStakingNearConfig);
394
+ /** The configured network, else the account's (`near:testnet` → testnet, anything else → mainnet). */
395
+ get network(): NearNetwork;
396
+ /** Contract, symbol and pinned code hashes on the current network (throws 'unsupported-network'). */
397
+ get pool(): ResolvedLiquidPool;
398
+ private client;
399
+ private archivalClient;
400
+ /** The account id, after checking the account is on the module's NEAR network. */
401
+ private me;
402
+ private view;
403
+ private epochNumbers;
404
+ /** Spendable NEAR of the account: amount − max(0, storage − locked), never below 0 (0 for an account that does not exist yet). */
405
+ private available;
406
+ /** Fee (upper bound) and upfront charge of the transactions at the current prices (see fees.ts). */
407
+ private costs;
408
+ /** What `stake` leaves on the account: `reserve`, but never less than the upfront gas of the exit it will need. */
409
+ private reserveAt;
410
+ private tx;
411
+ private assertWritable;
412
+ /** The paused features a plan's calls check (see PAUSE_KEYS); empty when every call goes through. */
413
+ private static pausedFor;
414
+ /** Withdrawals are stopped: the whole contract or its withdraw feature is paused. */
415
+ private static withdrawPaused;
416
+ /** 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. */
417
+ private static assertNotPaused;
418
+ /**
419
+ * NEAR the contract keeps from a stake for the account's NEP-145 registration: storage_balance_bounds.min
420
+ * when the contract charges it (rNEAR) and the account is not registered yet, else 0. Read live.
421
+ */
422
+ private storageFee;
423
+ private readAccount;
424
+ private contractUnlock;
425
+ /**
426
+ * The contract can pay `amount` now: its liquid balance minus what it must keep covers it. It
427
+ * keeps 1 NEAR itself, and the runtime refuses a receipt that leaves it below its storage cost
428
+ * (the whole transaction would fail, on every retry).
429
+ */
430
+ private static payable;
431
+ /** The epoch clock: height, start, measured duration (~6.9 h on mainnet), estimated end. */
432
+ getEpoch(): Promise<NearEpoch>;
433
+ /** Contract state: price, totals, pause flag, live code hash, liquidity, fee. Read fresh every time. */
434
+ getPoolInfo(): Promise<LiquidPoolInfo>;
435
+ /** The account in the contract: tokens, their NEAR value, unstaked NEAR, exact unlock epoch, registration. */
436
+ getAccountDetails(): Promise<LiquidAccountDetails>;
437
+ /** What `stake` can send now: available − reserve − the stake's upfront gas (never below 0). */
438
+ getMaxStakeable(): Promise<bigint>;
439
+ private static maxStakeable;
440
+ /**
441
+ * APR in percent: the `apr` hook, else the token price's growth over `aprWindowEpochs` (default 24,
442
+ * ~7 days), annualized by the two blocks' timestamps. The past price comes from the archival RPC;
443
+ * when that fails, from a 2-epoch window on the regular RPC. Cached for 10 minutes.
444
+ */
445
+ getApr(): Promise<number>;
446
+ private priceApr;
447
+ /** `ft_price` at a height (the next produced block when it was skipped), or at the final block, with that block's time. */
448
+ private priceAt;
449
+ /**
450
+ * The position, Tonstakers-style: `balance` = tokens held, `rate` = price (yoctoNEAR per token,
451
+ * 10^24 = 1:1), `total` = their NEAR value; `unstaked` and `withdrawable` (unlocked and payable
452
+ * from the contract's liquid balance now) beside.
453
+ */
454
+ getStakedBalance(): Promise<LiquidStakedBalance>;
455
+ /**
456
+ * The account's unstaked NEAR as one request (a contract keeps one unstaked balance per account):
457
+ * id `poolRequestId(contract)`, `unlockEpoch` exact from the contract. `claimable` needs the epoch
458
+ * reached, the contract's liquid balance to cover it (`awaitingLiquidity` otherwise) and withdrawals
459
+ * not paused (`paused`). `timestamp` is 0: the contract does not keep the unstake time.
460
+ */
461
+ getWithdrawalRequests(): Promise<LiquidWithdrawalRequestsView>;
462
+ /** Plans with fresh reads, compares with `expected`, then sends each transaction in order. */
463
+ private send;
464
+ private planStake;
465
+ /** The stake's transaction, fee, tokens expected and APR; nothing is signed. */
466
+ quoteStake(options: LiquidStakeOptions): Promise<LiquidStakeQuote>;
467
+ /**
468
+ * Stakes exactly `amount` yoctoNEAR (`deposit_and_stake`) for the token. There is no "stake
469
+ * everything": pass the amount (at most `getMaxStakeable()`).
470
+ */
471
+ stake(options: LiquidStakeOptions): Promise<LiquidStakeResult>;
472
+ private planUnstake;
473
+ /** The unstake's transaction, fee and unlock estimate; nothing is signed. `amount` is in token base units. */
474
+ quoteRequestWithdrawal(options: LiquidUnstakeOptions): Promise<LiquidUnstakeQuote>;
475
+ /**
476
+ * Unstakes `amount` token base units (`unstake` with their NEAR value), or `'all'` (`unstake_all`).
477
+ * An unlocked balance is withdrawn in the same transaction first. Once it is final,
478
+ * `getAccountDetails().unlockEpoch` is the exact epoch the NEAR unlocks at; reads use final blocks,
479
+ * so right after the send they still show the previous one (show the result's `unlock` meanwhile).
480
+ */
481
+ requestWithdrawal(options: LiquidUnstakeOptions): Promise<LiquidUnstakeResult>;
482
+ private planClaim;
483
+ /** The claim's transaction (`withdraw_all`) and fee; nothing is signed. */
484
+ quoteClaimWithdrawals(options?: LiquidClaimOptions): Promise<LiquidClaimQuote>;
485
+ /** Withdraws the unstaked NEAR (`withdraw_all`) once unlocked and payable. */
486
+ claimWithdrawals(options?: LiquidClaimOptions): Promise<LiquidClaimResult>;
487
+ /** Labels LiNEAR-family staking transactions offline; see `activity.ts`. */
488
+ describeActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null;
489
+ }
490
+
491
+ /** Why a liquid staking call was refused before anything was signed. */
492
+ type LiquidStakingErrorCode = 'wrong-chain' | 'no-provider' | 'unsupported-network' | 'invalid-amount' | 'below-minimum' | 'unknown-contract-code' | 'contract-paused' | 'exceeds-balance' | 'nothing-staked' | 'relock-refused' | 'timer-reset-refused' | 'max-fee-exceeded' | 'not-withdrawable' | 'awaiting-liquidity' | 'nothing-to-claim' | 'unknown-request' | 'quote-changed' | 'invalid-config';
493
+ /** A refusal with a code an app can branch on and a sentence it can show. */
494
+ declare class LiquidStakingError extends Error {
495
+ readonly code: LiquidStakingErrorCode;
496
+ readonly details: Record<string, unknown> | undefined;
497
+ constructor(code: LiquidStakingErrorCode, message: string, extra?: {
498
+ details?: Record<string, unknown>;
499
+ cause?: unknown;
500
+ });
501
+ }
502
+
503
+ /** True when the account can send several transactions with one approval. */
504
+ declare function canSendBatch(account: IWalletAccountReadOnly | IWalletAccount): account is IWalletAccount & NearTransactionsSender;
505
+ /**
506
+ * Same receivers, same actions, same order, same args, gas and deposits. Only function calls and
507
+ * transfers are compared field by field; any other action kind never matches (the module builds none).
508
+ */
509
+ declare function sameTransactions(a: readonly NearTransaction[], b: readonly NearTransaction[]): boolean;
510
+ /** A function-call action as the module builds them: plain JSON args, gas and deposit always set. */
511
+ declare function fc(methodName: string, args: Record<string, unknown>, gas: bigint, deposit: bigint): NearAction;
512
+ /** The only methods the module ever calls on a family contract. */
513
+ declare const LIQUID_WRITE_METHODS: readonly string[];
514
+ /**
515
+ * Throws unless every transaction goes to `contract` and holds only function calls to
516
+ * {@link LIQUID_WRITE_METHODS}. Runs on every plan before it is returned or sent. In particular it
517
+ * refuses `ft_transfer` / `ft_transfer_call` to the contract: it has no `ft_on_transfer`, so tokens
518
+ * (or "staking by transfer") sent that way are lost.
519
+ */
520
+ declare function assertLiquidPlan(transactions: readonly NearTransaction[], contract: string): void;
521
+
522
+ /** One block header: height and unix ms. */
523
+ interface BlockTime {
524
+ height: bigint;
525
+ ms: number;
526
+ }
527
+ /** The epoch numbers the validators answer carries. */
528
+ interface EpochNumbers {
529
+ epochHeight: bigint;
530
+ epochStartHeight: bigint;
531
+ }
532
+ /** The latest final block. */
533
+ declare function finalBlock(rpc: NearRpc): Promise<BlockTime>;
534
+ /** The block at `height`, or the first produced one after it when that height was skipped. */
535
+ declare function blockAt(rpc: NearRpc, height: bigint): Promise<BlockTime>;
536
+ /** `epoch_height` and `epoch_start_height` of the current epoch (one `validators` call). */
537
+ declare function readEpochNumbers(rpc: NearRpc): Promise<EpochNumbers>;
538
+ /** Options of {@link readEpoch}: reuse the caller's cached epoch numbers and block times. */
539
+ interface ReadEpochOptions {
540
+ numbers?: () => Promise<EpochNumbers>;
541
+ /** Timestamps of blocks already read, by height (block times never change). */
542
+ blockTimes?: Map<bigint, number>;
543
+ }
544
+ /** Reads the epoch clock. Falls back to {@link TYPICAL_EPOCH_MS} only when the epoch start blocks cannot be read. */
545
+ declare function readEpoch(rpc: NearRpc, options?: ReadEpochOptions): Promise<NearEpoch>;
546
+ /**
547
+ * Unix ms estimate of the start of epoch `height`. Past and current epochs count from `startedAt`;
548
+ * later ones from `endsAt` (which follows the current epoch's real progress), one `epochMs` each.
549
+ */
550
+ declare function epochStartsAt(epoch: NearEpoch, height: bigint): number;
551
+
552
+ /** Tokens `deposit_and_stake(amount)` mints: amount × totalShares / totalStaked, rounded down. */
553
+ declare function sharesForNear(amount: bigint, totals: {
554
+ totalShares: bigint;
555
+ totalStaked: bigint;
556
+ }): bigint;
557
+ /**
558
+ * NEAR that `shares` tokens are worth: shares × totalStaked / totalShares, rounded down. Passing this
559
+ * to `unstake(amount)` burns at most `shares` (the contract rounds the burnt shares up from it).
560
+ */
561
+ declare function nearForShares(shares: bigint, totals: {
562
+ totalShares: bigint;
563
+ totalStaked: bigint;
564
+ }): bigint;
565
+ /** `shares` valued at `price` (yoctoNEAR per whole token, {@link PRICE_SCALE} = 1:1), rounded down. */
566
+ declare function valueAtPrice(shares: bigint, price: bigint): bigint;
567
+ /**
568
+ * Annualized price growth in percent: (p1 / p0 − 1) × year / Δt × 100, simple (not compounded),
569
+ * computed in 10^12 fixed point. 0 when the inputs cannot give a figure (no time passed, no price).
570
+ */
571
+ declare function aprFromPrices(p0: bigint, p1: bigint, t0Ms: number, t1Ms: number): number;
572
+
573
+ /**
574
+ * The read client: `provider` from the config, else the transport of a wallet-near account
575
+ * (`_client`, or its configured `provider`). Undefined when neither exists; reads then refuse with
576
+ * 'no-provider'. External-signer accounts (wallet-selector adapters) have none: pass `provider`.
577
+ */
578
+ declare function resolveRpc(account: IWalletAccountReadOnly | IWalletAccount, config: {
579
+ provider?: NearProvider | NearProvider[];
580
+ timeoutMs?: number;
581
+ }): NearRpc | undefined;
582
+
583
+ /** Gas prices behind {@link GasCost}, yoctoNEAR per gas. */
584
+ interface GasPrices {
585
+ /** The current gas price + 10 %: the margin wallet-near's own estimate uses. */
586
+ gasPrice: bigint;
587
+ /** What the node charges per prepaid gas unit when it accepts a transaction. */
588
+ purchasePrice: bigint;
589
+ }
590
+ /** What a plan costs in NEAR, yoctoNEAR. */
591
+ interface GasCost {
592
+ /** Upper bound of the network fee: every gas unit burnt at {@link GasPrices.gasPrice}. Works as `maxFee`. */
593
+ fee: bigint;
594
+ /** NEAR held back from the account when the node accepts the transactions (deposits excluded); the unburnt part is refunded. */
595
+ upfront: bigint;
596
+ }
597
+ /** Reads the gas price fresh and `min_gas_purchase_price` once per {@link PROTOCOL_CONFIG_TTL_MS}. */
598
+ declare class GasPricer {
599
+ private readonly rpc;
600
+ private minPurchase;
601
+ constructor(rpc: () => NearRpc);
602
+ prices(): Promise<GasPrices>;
603
+ /** `runtime_config.min_gas_purchase_price`; the mainnet value when the node cannot say (fails toward a larger balance check). */
604
+ private minPurchasePrice;
605
+ }
606
+ /** Gas of the transactions as wallet-near counts it: conversion + prepaid, per action. */
607
+ declare const gasOf: (txs: readonly NearTransaction[]) => bigint;
608
+ /** Fee and upfront charge of `txs` at `prices`. */
609
+ declare function costOf(txs: readonly NearTransaction[], prices: GasPrices): GasCost;
610
+
611
+ /** Registry name, as `module.json` carries it. */
612
+ declare const MODULE_NAME = "@anywalletkit/protocol-staking-liquid-near";
613
+ /** Describes a LiNEAR / rNEAR staking transaction for the wallet's feed, or returns null when it is not one. */
614
+ declare function describeLiquidNearStakingActivity(tx: ChainTx, ctx: DescribeActivityContext, options?: {
615
+ contracts?: ReadonlyArray<{
616
+ contract: string;
617
+ symbol: string;
618
+ name?: string;
619
+ }>;
620
+ }): ActivityItem | null;
621
+
622
+ export { type BlockTime, CONTRACT_MIN_RESERVE_BALANCE, DEFAULT_APR_WINDOW_EPOCHS, DEFAULT_ARCHIVAL_RPC, DEFAULT_GAS, DEFAULT_RESERVE, EPOCH_LENGTH, type EpochNumbers, GAS_PRICE_MARGIN_DEN, GAS_PRICE_MARGIN_NUM, type GasCost, GasPricer, type GasPrices, LIQUID_PRESETS, LIQUID_WRITE_METHODS, LST_DECIMALS, type LiquidAccountDetails, type LiquidClaimOptions, type LiquidClaimQuote, type LiquidClaimResult, type LiquidPoolConfig, type LiquidPoolInfo, type LiquidPreset, type LiquidPresetName, type LiquidStakeOptions, type LiquidStakeQuote, type LiquidStakeResult, type LiquidStakedBalance, LiquidStakingError, type LiquidStakingErrorCode, type LiquidStakingNearConfig, LiquidStakingProtocolNear, type LiquidStakingWarning, type LiquidStakingWarningCode, type LiquidUnstakeOptions, type LiquidUnstakeQuote, type LiquidUnstakeResult, type LiquidWithdrawalRequest, type LiquidWithdrawalRequestsView, type LiquidWriteOptions, MIN_EPOCHS_TO_UNLOCK, MIN_GAS_PURCHASE_PRICE_FALLBACK, MIN_STAKE, MODULE_NAME, NEAR_MAINNET, NEAR_TESTNET, type NearEpoch, type NearNetwork, type NearTransactionsSender, PAUSE_KEYS, PRICE_SCALE, type ReadEpochOptions, type ResolvedLiquidPool, STORAGE_DEPOSIT, TGAS, TYPICAL_EPOCH_MS, UNSTAKED_DUST, type UnlockEstimate, YOCTO_PER_NEAR, aprFromPrices, assertLiquidPlan, blockAt, canSendBatch, costOf, LiquidStakingProtocolNear as default, describeLiquidNearStakingActivity, epochStartsAt, fc, finalBlock, gasOf, nearForShares, poolRequestId, readEpoch, readEpochNumbers, resolvePool, resolveRpc, sameTransactions, sharesForNear, validatePoolConfig, valueAtPrice };