@anywalletkit/protocol-staking-liquid-near 0.1.0 → 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/README.md CHANGED
@@ -24,8 +24,9 @@ const rnear = new LiquidStakingProtocolNear(account, { pool: 'rnear', provider:
24
24
 
25
25
  const quote = await rnear.quoteStake({ amount: 730_000_000_000_000_000_000_000n }) // 0.73 NEAR
26
26
  // quote.transactions: [{ receiverId: 'lst.rhealab.near', actions: [deposit_and_stake, 30 Tgas, 0.73 NEAR] }]
27
- // quote.shares (tokens minted at the current totals), quote.fee (upper bound), quote.upfront (gas the node
28
- // holds back on acceptance), quote.reserve, quote.apr, quote.maxStakeable
27
+ // quote.shares (tokens minted at the current totals), quote.storageFee (0.00125 NEAR kept from a first rNEAR
28
+ // stake, else 0), quote.fee (upper bound), quote.upfront (gas the node holds back on acceptance), quote.reserve,
29
+ // quote.apr, quote.maxStakeable
29
30
  await rnear.stake({ amount: 730_000_000_000_000_000_000_000n, expected: quote.transactions })
30
31
 
31
32
  const exit = await rnear.quoteRequestWithdrawal({ amount: 'all' }) // or token base units
@@ -46,7 +47,7 @@ to NEAR for the contract, whose `unstake` takes NEAR.
46
47
 
47
48
  | Option | Default | |
48
49
  |---|---|---|
49
- | `pool` | — (required) | `'linear'`, `'rnear'`, or `{ contract, symbol, name?, codeHashes }` for another contract with the same interface. `codeHashes` is required: a contract upgrade is refused until the app pins the new build. |
50
+ | `pool` | — (required) | `'linear'`, `'rnear'`, or `{ contract, symbol, name?, codeHashes, firstStakePaysStorage? }` for another contract with the same interface. `codeHashes` is required: a contract upgrade is refused until the app pins the new build. `firstStakePaysStorage`: the contract keeps its storage fee from an unregistered account's first stake, as rNEAR does; false for a contract that stakes the whole amount, as LiNEAR does. Default: the preset's value when `contract` is a preset's own account (LiNEAR or rNEAR re-pinned after an upgrade), else true. |
50
51
  | `network` | the account's | `near:testnet` gives testnet, anything else mainnet. rNEAR has no testnet contract (`'unsupported-network'`). |
51
52
  | `provider` | the wallet-near account's RPC | URL, transport, or a list (failover). An external-signer account has no RPC: pass it. |
52
53
  | `archivalProvider` | fastnear archival | For the past price behind the APR. |
@@ -63,10 +64,10 @@ to NEAR for the contract, whose `unstake` takes NEAR.
63
64
  | `quoteStake` / `stake({ amount, expected? })` | `deposit_and_stake` with exactly `amount`. No "stake everything": pass the amount (`getMaxStakeable()` is the most it can be). |
64
65
  | `quoteRequestWithdrawal` / `requestWithdrawal({ amount, allowRelock?, allowTimerReset?, expected? })` | `unstake(nearValue)`, or `unstake_all` for `'all'` / the whole balance. An unlocked balance is withdrawn first in the same transaction. |
65
66
  | `quoteClaimWithdrawals` / `claimWithdrawals({ ids?, expected? })` | `withdraw_all`. `ids` may only be `[poolRequestId(contract)]`. |
66
- | `getWithdrawalRequests()` | One request when the account has NEAR unstaked: `claimable`, `unlockEpoch`, `awaitingLiquidity`, `unlock` (epoch and date). |
67
+ | `getWithdrawalRequests()` | One request when the account has NEAR unstaked: `claimable`, `unlockEpoch`, `awaitingLiquidity`, `paused` (withdrawals paused in the contract), `unlock` (epoch and date). |
67
68
  | `getStakedBalance()` | `balance` = tokens, `rate` = price, `total` = their NEAR value, `unstaked`, `withdrawable`. |
68
69
  | `getAccountDetails()` | Tokens, value, unstaked, exact `unlockEpoch`, `canWithdraw`, `registered`. |
69
- | `getPoolInfo()` | Price, totals, `paused`, live `codeHash` and `codeHashKnown`, `liquidity`, `kept` (what it cannot pay out), `feeBps`. |
70
+ | `getPoolInfo()` | Price, totals, `paused`, `pausedFeatures` (rNEAR's per-feature pauses), live `codeHash` and `codeHashKnown`, `liquidity`, `kept` (what it cannot pay out), `feeBps`. |
70
71
  | `getApr()` | The `apr` hook, else the price change over `aprWindowEpochs`, annualized (percent). |
71
72
  | `getEpoch()` | Height, start, measured duration, estimated end. |
72
73
  | `getMaxStakeable()` | Spendable − reserve − the stake's upfront gas. |
@@ -117,18 +118,32 @@ has `ft_on_transfer`: tokens sent that way are lost), never `Transfer`, keys or
117
118
  (`'unknown-contract-code'`) or a contract that is paused (`'contract-paused'`; a missing,
118
119
  panicking or non-boolean `is_paused` counts as paused; a transport failure is thrown, never read as
119
120
  "not paused"). Both apply to exits too: a paused contract rejects every call anyway.
121
+ - rNEAR can also pause single features (`pa_all_paused`: `internal_deposit`, `internal_stake`,
122
+ `internal_unstake`, `internal_withdraw`) while `is_paused` stays false. `getPoolInfo().pausedFeatures`
123
+ lists them, and each write is refused with `'contract-paused'` when a call it would send needs one:
124
+ a stake needs deposits and staking, an unstake unstaking, a claim withdrawals. While withdrawals
125
+ are paused, an unlocked request is not `claimable` (`paused`), and an unstake that would withdraw it
126
+ first is refused with `'relock-refused'` unless `allowRelock: true` (then it is a plain unstake that
127
+ locks it again). 'ALL', a panic or a non-list answer counts as fully paused; a contract without the
128
+ method (LiNEAR) has no per-feature pause.
120
129
  - Every method that uses the account checks it is on the module's network (`'wrong-chain'`). Writes
121
130
  on a read-only account throw `ReadOnlyAccountError` before any read.
122
- - Funds: `amount + upfront + reserve` must fit the spendable balance (amount − locked − storage),
131
+ - Funds: `amount + upfront + reserve` must fit the spendable balance (amount − max(0, storage − locked)),
123
132
  else core's `InsufficientFundsError`. Exits check their `upfront`. `upfront` is Σ gas ×
124
133
  max(gas price + 10 %, `min_gas_purchase_price` from `EXPERIMENTAL_protocol_config`, mainnet's 10^9
125
134
  when the node cannot say): the node holds it back when it accepts the transaction. `fee` is
126
135
  Σ gas × (gas price + 10 %), the margin wallet-near's estimate uses, so `maxFee: quote.fee` passes;
127
136
  the module checks `maxFee` itself too (`'max-fee-exceeded'`). Each send gets a copy of the
128
137
  quoted transactions.
129
- - No NEP-145 step: `deposit_and_stake` creates the account's entry in the contract (on mainnet, an
138
+ - No NEP-145 step: `deposit_and_stake` registers the account in the contract itself (on mainnet, an
130
139
  implicit account a 1Click delivery had just created staked into LiNEAR this way, unregistered).
131
- Registration only matters for receiving the token by transfer.
140
+ LiNEAR stakes the whole amount. rNEAR keeps `storage_balance_bounds.min` (0.00125 NEAR) of an
141
+ unregistered account's first deposit for that registration and stakes the rest: the module reads
142
+ `storage_balance_of` and the bound live, quotes `shares` for `amount − storageFee`, adds the
143
+ warning `'pays-storage'`, and refuses a first stake below fee + 0.001 NEAR (0.00225 NEAR today)
144
+ with `'below-minimum'`. At or below the fee the contract fails the stake (`amount − fee`
145
+ underflows or stakes nothing) and burns the gas; above it the contract stakes `amount − fee`,
146
+ and the module keeps its 0.001 NEAR minimum for that part, as for any stake.
132
147
  - `deposit_and_stake` leaves the rounding remainder (a yocto or two) unstaked. Balances at or below
133
148
  `UNSTAKED_DUST` (10^6 yocto) are treated as empty, so they never produce a request or a withdraw.
134
149
 
@@ -141,8 +156,10 @@ has `ft_on_transfer`: tokens sent that way are lost), never `Transfer`, keys or
141
156
  | Rhea rNEAR | `lst.rhealab.near` (v1.0.2) | `EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv` | rNEAR, 24 decimals, fee 5 % (`ref-finance.sputnik-dao.near`) |
142
157
 
143
158
  Both run the same interface: `ft_price`, `get_summary`, `get_account_details`, `is_paused`,
144
- `get_beneficiaries`, `storage_balance_of`; `deposit_and_stake`, `unstake(NEAR)`, `unstake_all`,
145
- `withdraw_all`. Neither has `get_num_epoch_to_unstake`, `instant_unstake` or `ft_on_transfer`.
159
+ `get_beneficiaries`, `storage_balance_of`, `storage_balance_bounds`; `deposit_and_stake`,
160
+ `unstake(NEAR)`, `unstake_all`, `withdraw_all`. rNEAR adds `pa_all_paused` (per-feature pauses) and
161
+ keeps the storage fee from a first stake. Neither has `get_num_epoch_to_unstake`, `instant_unstake`
162
+ or `ft_on_transfer`.
146
163
 
147
164
  Meta Pool stNEAR is a different contract family and is not in this package.
148
165
 
package/dist/index.cjs CHANGED
@@ -40,6 +40,7 @@ __export(src_exports, {
40
40
  MODULE_NAME: () => MODULE_NAME,
41
41
  NEAR_MAINNET: () => NEAR_MAINNET,
42
42
  NEAR_TESTNET: () => NEAR_TESTNET,
43
+ PAUSE_KEYS: () => PAUSE_KEYS,
43
44
  PRICE_SCALE: () => PRICE_SCALE,
44
45
  STORAGE_DEPOSIT: () => STORAGE_DEPOSIT,
45
46
  TGAS: () => TGAS,
@@ -92,6 +93,12 @@ var CONTRACT_MIN_RESERVE_BALANCE = YOCTO_PER_NEAR;
92
93
  var STORAGE_DEPOSIT = 1250000000000000000000n;
93
94
  var DEFAULT_RESERVE = 2n * 10n ** 22n;
94
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
+ };
95
102
  var DEFAULT_GAS = {
96
103
  stake: 30n * TGAS,
97
104
  unstake: 30n * TGAS,
@@ -109,6 +116,10 @@ var LIQUID_PRESETS = {
109
116
  linear: {
110
117
  symbol: "LINEAR",
111
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
112
123
  contracts: {
113
124
  mainnet: { contract: "linear-protocol.near", codeHashes: ["5LiDVDd1gh7ofVNbiA9VXrWwkv2m8tw46jZqYeuoC3SG"] },
114
125
  testnet: { contract: "linear-protocol.testnet", codeHashes: ["8Bby4ofnYGtudd3PinKZ1KyvmUKJVyxmfC99ZccRDVDv"] }
@@ -117,6 +128,10 @@ var LIQUID_PRESETS = {
117
128
  rnear: {
118
129
  symbol: "rNEAR",
119
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'
120
135
  contracts: {
121
136
  mainnet: { contract: "lst.rhealab.near", codeHashes: ["EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv"] }
122
137
  // v1.0.2
@@ -351,13 +366,18 @@ function validatePoolConfig(pool) {
351
366
  if (!Array.isArray(pool.codeHashes) || pool.codeHashes.length === 0 || !pool.codeHashes.every((h) => typeof h === "string" && h.length > 0)) {
352
367
  throw new LiquidStakingError("invalid-config", "pool.codeHashes must pin at least one code hash.");
353
368
  }
369
+ if (pool.firstStakePaysStorage !== void 0 && typeof pool.firstStakePaysStorage !== "boolean") throw new LiquidStakingError("invalid-config", "pool.firstStakePaysStorage must be a boolean.");
354
370
  }
355
371
  function resolvePool(pool, network) {
356
- if (typeof pool !== "string") return { contract: pool.contract, symbol: pool.symbol, name: pool.name ?? pool.symbol, codeHashes: pool.codeHashes, preset: null };
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
+ }
357
377
  const preset = LIQUID_PRESETS[pool];
358
378
  const on = preset.contracts[network];
359
379
  if (!on) throw new LiquidStakingError("unsupported-network", `${preset.name} has no contract on NEAR ${network}.`);
360
- return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, preset: pool };
380
+ return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, firstStakePaysStorage: preset.firstStakePaysStorage, featurePauses: preset.featurePauses, preset: pool };
361
381
  }
362
382
  function poolRequestId(contract) {
363
383
  let id = 0n;
@@ -433,6 +453,12 @@ var APR_TTL_MS = 10 * 6e4;
433
453
  var APR_FALLBACK_EPOCHS = 2n;
434
454
  var SKIP_TRIES2 = 10;
435
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
+ };
436
462
  var near = (yocto) => {
437
463
  const frac = (yocto % YOCTO_PER_NEAR).toString().padStart(24, "0").slice(0, 5).replace(/0+$/, "");
438
464
  return `${yocto / YOCTO_PER_NEAR}${frac ? `.${frac}` : ""} NEAR`;
@@ -442,6 +468,14 @@ function amountOf(v, what) {
442
468
  if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
443
469
  throw new import_core4.NetworkError(`${what}: expected a non-negative integer, got ${String(JSON.stringify(v)).slice(0, 60)}`);
444
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
+ }
445
479
  function positiveAmount(v, unit) {
446
480
  if (typeof v !== "bigint" && !(typeof v === "number" && Number.isSafeInteger(v))) {
447
481
  throw new LiquidStakingError("invalid-amount", `'amount' must be a bigint or a safe integer (${unit}).`);
@@ -532,11 +566,13 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
532
566
  });
533
567
  return value;
534
568
  }
535
- /** Spendable NEAR of the account: amount − locked − storage, never below 0 (0 for an account that does not exist yet). */
569
+ /** Spendable NEAR of the account: amount − max(0, storage − locked), never below 0 (0 for an account that does not exist yet). */
536
570
  async available(me) {
537
571
  const v = await this.client().viewAccount(me);
538
572
  if (!v) return 0n;
539
- const free = amountOf(v.amount, "view_account.amount") - amountOf(v.locked, "view_account.locked") - amountOf(v.storage_usage, "view_account.storage_usage") * import_wallet_near5.STORAGE_PRICE_PER_BYTE;
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);
540
576
  return free > 0n ? free : 0n;
541
577
  }
542
578
  /** Fee (upper bound) and upfront charge of the transactions at the current prices (see fees.ts). */
@@ -561,6 +597,36 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
561
597
  }
562
598
  if (info.paused) throw new LiquidStakingError("contract-paused", `${info.name} (${info.contract}) is paused: it rejects every call until it resumes.`);
563
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
+ }
564
630
  async readAccount(me, price) {
565
631
  const [balance, details, storage] = await Promise.all([
566
632
  this.view("ft_balance_of", { account_id: me }),
@@ -601,7 +667,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
601
667
  async getPoolInfo() {
602
668
  const pool = this.pool;
603
669
  const rpc = this.client();
604
- const [meta, summary, paused, account, beneficiaries] = await Promise.all([
670
+ const [meta, summary, pausedFlag, pausedKeys, account, beneficiaries] = await Promise.all([
605
671
  this.view("ft_metadata"),
606
672
  this.view("get_summary"),
607
673
  // A contract answer other than `false` (a missing method, a panic, a non-boolean) counts as paused; a transport failure is thrown.
@@ -609,6 +675,16 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
609
675
  if (e instanceof import_wallet_near5.NearRpcError) return true;
610
676
  throw e;
611
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
+ }),
612
688
  rpc.viewAccount(pool.contract),
613
689
  this.view("get_beneficiaries").catch((e) => {
614
690
  if (e instanceof import_wallet_near5.NearRpcError) return null;
@@ -621,6 +697,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
621
697
  for (const bps of Object.values(beneficiaries ?? {})) if (typeof bps === "number" && Number.isInteger(bps) && bps >= 0) feeBps += bps;
622
698
  const codeHash = typeof account?.code_hash === "string" ? account.code_hash : "";
623
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");
624
701
  return {
625
702
  contract: pool.contract,
626
703
  symbol: typeof meta.symbol === "string" ? meta.symbol : pool.symbol,
@@ -631,6 +708,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
631
708
  totalShares: amountOf(summary.total_share_amount, "get_summary.total_share_amount"),
632
709
  validators: typeof summary.validators_num === "number" ? summary.validators_num : 0,
633
710
  paused,
711
+ pausedFeatures: pausedKeys === "unreadable" ? [] : pausedKeys,
634
712
  codeHash,
635
713
  codeHashKnown: codeHash !== "" && pool.codeHashes.includes(codeHash),
636
714
  liquidity: account ? amountOf(account.amount, "view_account.amount") : 0n,
@@ -724,14 +802,14 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
724
802
  const info = await this.getPoolInfo();
725
803
  const a = await this.readAccount(me, info.price);
726
804
  const unstaked = a.unstaked > UNSTAKED_DUST ? a.unstaked : 0n;
727
- const withdrawable = unstaked > 0n && a.canWithdraw && _LiquidStakingProtocolNear.payable(info, unstaked) ? unstaked : 0n;
805
+ const withdrawable = unstaked > 0n && a.canWithdraw && _LiquidStakingProtocolNear.payable(info, unstaked) && !_LiquidStakingProtocolNear.withdrawPaused(info) ? unstaked : 0n;
728
806
  return { balance: a.shares, wrappedBalance: 0n, rate: info.price, total: a.value, unstaked, withdrawable, price: info.price };
729
807
  }
730
808
  /**
731
809
  * The account's unstaked NEAR as one request (a contract keeps one unstaked balance per account):
732
810
  * id `poolRequestId(contract)`, `unlockEpoch` exact from the contract. `claimable` needs the epoch
733
- * reached and the contract's liquid balance to cover it (`awaitingLiquidity` otherwise).
734
- * `timestamp` is 0: the contract does not keep the unstake time.
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.
735
813
  */
736
814
  async getWithdrawalRequests() {
737
815
  const me = await this.me();
@@ -739,7 +817,8 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
739
817
  const a = await this.readAccount(me, info.price);
740
818
  if (a.unstaked <= UNSTAKED_DUST) return { requests: [], pendingAmount: 0n, claimableAmount: 0n, claimableIds: [] };
741
819
  const awaitingLiquidity = a.canWithdraw && !_LiquidStakingProtocolNear.payable(info, a.unstaked);
742
- const claimable = a.canWithdraw && !awaitingLiquidity;
820
+ const paused = _LiquidStakingProtocolNear.withdrawPaused(info);
821
+ const claimable = a.canWithdraw && !awaitingLiquidity && !paused;
743
822
  const id = poolRequestId(info.contract);
744
823
  const request = {
745
824
  id,
@@ -749,6 +828,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
749
828
  contract: info.contract,
750
829
  unlockEpoch: a.unlockEpoch,
751
830
  awaitingLiquidity,
831
+ paused,
752
832
  unlock: claimable ? null : this.contractUnlock(await this.getEpoch(), a.unlockEpoch)
753
833
  };
754
834
  return {
@@ -792,6 +872,12 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
792
872
  const info = await this.getPoolInfo();
793
873
  this.assertWritable(info);
794
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.` }] : [];
795
881
  const [available, { fee, upfront, prices }, apr] = await Promise.all([this.available(me), this.costs(transactions), this.getApr().catch(() => null)]);
796
882
  const reserve = this.reserveAt(prices);
797
883
  const required = amount + upfront + reserve;
@@ -801,12 +887,13 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
801
887
  upfront,
802
888
  reserve,
803
889
  amount,
804
- shares: sharesForNear(amount, info),
890
+ storageFee,
891
+ shares: sharesForNear(amount - storageFee, info),
805
892
  price: info.price,
806
893
  apr,
807
894
  maxStakeable: _LiquidStakingProtocolNear.maxStakeable(available, reserve, upfront),
808
895
  transactions,
809
- warnings: []
896
+ warnings
810
897
  };
811
898
  }
812
899
  /** The stake's transaction, fee, tokens expected and APR; nothing is signed. */
@@ -835,19 +922,22 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
835
922
  const amount = all ? a.stakedNear : nearForShares(shares, info);
836
923
  if (amount === 0n) throw new LiquidStakingError("below-minimum", `${shares} ${info.symbol} base units are worth less than 1 yoctoNEAR.`);
837
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])]);
838
926
  const warnings = [];
839
927
  const actions = [];
840
928
  let withdrawsFirst = 0n, relocks = 0n, resetsTimer = false;
841
929
  if (a.unstaked > UNSTAKED_DUST && a.canWithdraw) {
842
- if (_LiquidStakingProtocolNear.payable(info, a.unstaked)) {
930
+ const withdrawPaused = _LiquidStakingProtocolNear.withdrawPaused(info);
931
+ if (_LiquidStakingProtocolNear.payable(info, a.unstaked) && !withdrawPaused) {
843
932
  actions.push(fc("withdraw_all", {}, this.gas.withdraw, 0n));
844
933
  withdrawsFirst = a.unstaked;
845
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.` });
846
935
  } else if (!o.allowRelock || amount < MIN_STAKE) {
847
- throw new LiquidStakingError("relock-refused", `${near(a.unstaked)} is unlocked, but ${info.name} cannot pay it out yet (it is waiting for its payout). A new unstake now would lock it again for 4+ epochs: claim it first${amount < MIN_STAKE ? "" : ", or pass allowRelock"}.`, { details: { unstaked: a.unstaked, liquidity: info.liquidity, kept: info.kept } });
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 } });
848
938
  } else {
849
939
  relocks = a.unstaked;
850
- warnings.push({ code: "relocks-unlocked", message: `${near(a.unstaked)} already unlocked locks again with this unstake (the contract cannot pay it out yet): the whole unstaked balance waits 4+ more epochs.` });
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.` });
851
941
  }
852
942
  } else if (a.unstaked > UNSTAKED_DUST) {
853
943
  if (amount < MIN_STAKE || !o.allowTimerReset) {
@@ -859,6 +949,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
859
949
  actions.push(unstake);
860
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." });
861
951
  const transactions = [this.tx(actions)];
952
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
862
953
  const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
863
954
  if (upfront > available) throw new import_core4.InsufficientFundsError(upfront, available, "NEAR");
864
955
  const earliestEpoch = epoch.height + MIN_EPOCHS_TO_UNLOCK;
@@ -911,6 +1002,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends import_
911
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 } });
912
1003
  }
913
1004
  const transactions = [this.tx([fc("withdraw_all", {}, this.gas.withdraw, 0n)])];
1005
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
914
1006
  const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
915
1007
  if (upfront > available) throw new import_core4.InsufficientFundsError(upfront, available, "NEAR");
916
1008
  return { fee, upfront, amount: a.unstaked, transactions };