@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/dist/index.js CHANGED
@@ -31,6 +31,12 @@ var CONTRACT_MIN_RESERVE_BALANCE = YOCTO_PER_NEAR;
31
31
  var STORAGE_DEPOSIT = 1250000000000000000000n;
32
32
  var DEFAULT_RESERVE = 2n * 10n ** 22n;
33
33
  var MIN_STAKE = 10n ** 21n;
34
+ var PAUSE_KEYS = {
35
+ deposit_and_stake: ["internal_deposit", "internal_stake"],
36
+ unstake: ["internal_unstake"],
37
+ unstake_all: ["internal_unstake"],
38
+ withdraw_all: ["internal_withdraw"]
39
+ };
34
40
  var DEFAULT_GAS = {
35
41
  stake: 30n * TGAS,
36
42
  unstake: 30n * TGAS,
@@ -48,6 +54,10 @@ var LIQUID_PRESETS = {
48
54
  linear: {
49
55
  symbol: "LINEAR",
50
56
  name: "LiNEAR",
57
+ firstStakePaysStorage: false,
58
+ // stake.rs: internal_deposit(attached); an unregistered implicit account staked 0.266 NEAR whole (fixture)
59
+ featurePauses: false,
60
+ // one `paused` flag (is_paused); pa_all_paused is MethodNotFound on mainnet
51
61
  contracts: {
52
62
  mainnet: { contract: "linear-protocol.near", codeHashes: ["5LiDVDd1gh7ofVNbiA9VXrWwkv2m8tw46jZqYeuoC3SG"] },
53
63
  testnet: { contract: "linear-protocol.testnet", codeHashes: ["8Bby4ofnYGtudd3PinKZ1KyvmUKJVyxmfC99ZccRDVDv"] }
@@ -56,6 +66,10 @@ var LIQUID_PRESETS = {
56
66
  rnear: {
57
67
  symbol: "rNEAR",
58
68
  name: "Rhea Liquid Near Staking Token",
69
+ firstStakePaysStorage: true,
70
+ // stake_pool_itf.rs: internal_deposit(amount − storage_balance_bounds.min) when storage_balance_of is null
71
+ featurePauses: true,
72
+ // #[pause] on internal_deposit / internal_stake / internal_unstake / internal_withdraw; is_paused reads only 'ALL'
59
73
  contracts: {
60
74
  mainnet: { contract: "lst.rhealab.near", codeHashes: ["EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv"] }
61
75
  // v1.0.2
@@ -290,13 +304,18 @@ function validatePoolConfig(pool) {
290
304
  if (!Array.isArray(pool.codeHashes) || pool.codeHashes.length === 0 || !pool.codeHashes.every((h) => typeof h === "string" && h.length > 0)) {
291
305
  throw new LiquidStakingError("invalid-config", "pool.codeHashes must pin at least one code hash.");
292
306
  }
307
+ if (pool.firstStakePaysStorage !== void 0 && typeof pool.firstStakePaysStorage !== "boolean") throw new LiquidStakingError("invalid-config", "pool.firstStakePaysStorage must be a boolean.");
293
308
  }
294
309
  function resolvePool(pool, network) {
295
- if (typeof pool !== "string") return { contract: pool.contract, symbol: pool.symbol, name: pool.name ?? pool.symbol, codeHashes: pool.codeHashes, preset: null };
310
+ if (typeof pool !== "string") {
311
+ const known = Object.values(LIQUID_PRESETS).find((p) => Object.values(p.contracts).some((c) => c?.contract === pool.contract));
312
+ const firstStakePaysStorage = pool.firstStakePaysStorage ?? known?.firstStakePaysStorage ?? true;
313
+ return { contract: pool.contract, symbol: pool.symbol, name: pool.name ?? pool.symbol, codeHashes: pool.codeHashes, firstStakePaysStorage, featurePauses: true, preset: null };
314
+ }
296
315
  const preset = LIQUID_PRESETS[pool];
297
316
  const on = preset.contracts[network];
298
317
  if (!on) throw new LiquidStakingError("unsupported-network", `${preset.name} has no contract on NEAR ${network}.`);
299
- return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, preset: pool };
318
+ return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, firstStakePaysStorage: preset.firstStakePaysStorage, featurePauses: preset.featurePauses, preset: pool };
300
319
  }
301
320
  function poolRequestId(contract) {
302
321
  let id = 0n;
@@ -372,6 +391,12 @@ var APR_TTL_MS = 10 * 6e4;
372
391
  var APR_FALLBACK_EPOCHS = 2n;
373
392
  var SKIP_TRIES2 = 10;
374
393
  var MAX_CALL_GAS = 300n * TGAS;
394
+ var FEATURE_WORDS = {
395
+ internal_deposit: "deposits",
396
+ internal_stake: "staking",
397
+ internal_unstake: "unstaking",
398
+ internal_withdraw: "withdrawals"
399
+ };
375
400
  var near = (yocto) => {
376
401
  const frac = (yocto % YOCTO_PER_NEAR).toString().padStart(24, "0").slice(0, 5).replace(/0+$/, "");
377
402
  return `${yocto / YOCTO_PER_NEAR}${frac ? `.${frac}` : ""} NEAR`;
@@ -381,6 +406,14 @@ function amountOf(v, what) {
381
406
  if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
382
407
  throw new NetworkError2(`${what}: expected a non-negative integer, got ${String(JSON.stringify(v)).slice(0, 60)}`);
383
408
  }
409
+ function methodMissing(e) {
410
+ if (/MethodNotFound/.test(e.message)) return true;
411
+ try {
412
+ return /MethodNotFound/.test(JSON.stringify(e.cause) ?? "");
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
384
417
  function positiveAmount(v, unit) {
385
418
  if (typeof v !== "bigint" && !(typeof v === "number" && Number.isSafeInteger(v))) {
386
419
  throw new LiquidStakingError("invalid-amount", `'amount' must be a bigint or a safe integer (${unit}).`);
@@ -471,11 +504,13 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
471
504
  });
472
505
  return value;
473
506
  }
474
- /** Spendable NEAR of the account: amount − locked − storage, never below 0 (0 for an account that does not exist yet). */
507
+ /** Spendable NEAR of the account: amount − max(0, storage − locked), never below 0 (0 for an account that does not exist yet). */
475
508
  async available(me) {
476
509
  const v = await this.client().viewAccount(me);
477
510
  if (!v) return 0n;
478
- const free = amountOf(v.amount, "view_account.amount") - amountOf(v.locked, "view_account.locked") - amountOf(v.storage_usage, "view_account.storage_usage") * STORAGE_PRICE_PER_BYTE;
511
+ const storage = amountOf(v.storage_usage, "view_account.storage_usage") * STORAGE_PRICE_PER_BYTE;
512
+ const locked = amountOf(v.locked, "view_account.locked");
513
+ const free = amountOf(v.amount, "view_account.amount") - (storage > locked ? storage - locked : 0n);
479
514
  return free > 0n ? free : 0n;
480
515
  }
481
516
  /** Fee (upper bound) and upfront charge of the transactions at the current prices (see fees.ts). */
@@ -500,6 +535,36 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
500
535
  }
501
536
  if (info.paused) throw new LiquidStakingError("contract-paused", `${info.name} (${info.contract}) is paused: it rejects every call until it resumes.`);
502
537
  }
538
+ /** The paused features a plan's calls check (see PAUSE_KEYS); empty when every call goes through. */
539
+ static pausedFor(info, methods) {
540
+ const keys = new Set(methods.flatMap((m) => PAUSE_KEYS[m] ?? []));
541
+ return info.pausedFeatures.filter((k) => keys.has(k));
542
+ }
543
+ /** Withdrawals are stopped: the whole contract or its withdraw feature is paused. */
544
+ static withdrawPaused(info) {
545
+ return info.paused || _LiquidStakingProtocolNear.pausedFor(info, ["withdraw_all"]).length > 0;
546
+ }
547
+ /** 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. */
548
+ static assertNotPaused(info, transactions) {
549
+ const methods = transactions.flatMap((t) => t.actions.flatMap((a) => "functionCall" in a ? [a.functionCall.methodName] : []));
550
+ const paused = _LiquidStakingProtocolNear.pausedFor(info, methods);
551
+ if (paused.length === 0) return;
552
+ const what = [...new Set(paused.map((k) => FEATURE_WORDS[k] ?? k))].join(" and ");
553
+ throw new LiquidStakingError("contract-paused", `${info.name} (${info.contract}) has ${what} paused (${paused.join(", ")}): this transaction would fail until it resumes.`, { details: { pausedFeatures: paused } });
554
+ }
555
+ /**
556
+ * NEAR the contract keeps from a stake for the account's NEP-145 registration: storage_balance_bounds.min
557
+ * when the contract charges it (rNEAR) and the account is not registered yet, else 0. Read live.
558
+ */
559
+ async storageFee(me) {
560
+ if (!this.pool.firstStakePaysStorage) return 0n;
561
+ const [balance, bounds] = await Promise.all([
562
+ this.view("storage_balance_of", { account_id: me }),
563
+ this.view("storage_balance_bounds")
564
+ ]);
565
+ if (balance !== null && balance !== void 0) return 0n;
566
+ return amountOf(bounds?.min, "storage_balance_bounds.min");
567
+ }
503
568
  async readAccount(me, price) {
504
569
  const [balance, details, storage] = await Promise.all([
505
570
  this.view("ft_balance_of", { account_id: me }),
@@ -540,7 +605,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
540
605
  async getPoolInfo() {
541
606
  const pool = this.pool;
542
607
  const rpc = this.client();
543
- const [meta, summary, paused, account, beneficiaries] = await Promise.all([
608
+ const [meta, summary, pausedFlag, pausedKeys, account, beneficiaries] = await Promise.all([
544
609
  this.view("ft_metadata"),
545
610
  this.view("get_summary"),
546
611
  // A contract answer other than `false` (a missing method, a panic, a non-boolean) counts as paused; a transport failure is thrown.
@@ -548,6 +613,16 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
548
613
  if (e instanceof NearRpcError2) return true;
549
614
  throw e;
550
615
  }),
616
+ // Per-feature pauses (near-plugins Pausable, rNEAR): null when none. LiNEAR has only `is_paused`
617
+ // and is not asked; a custom contract without the method has none. Any other contract answer (a
618
+ // panic, a non-list) counts as paused.
619
+ !pool.featurePauses ? Promise.resolve([]) : this.view("pa_all_paused").then((v) => {
620
+ if (v === null) return [];
621
+ return Array.isArray(v) && v.every((k) => typeof k === "string") ? [...v].sort() : "unreadable";
622
+ }, (e) => {
623
+ if (e instanceof NearRpcError2) return methodMissing(e) ? [] : "unreadable";
624
+ throw e;
625
+ }),
551
626
  rpc.viewAccount(pool.contract),
552
627
  this.view("get_beneficiaries").catch((e) => {
553
628
  if (e instanceof NearRpcError2) return null;
@@ -560,6 +635,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
560
635
  for (const bps of Object.values(beneficiaries ?? {})) if (typeof bps === "number" && Number.isInteger(bps) && bps >= 0) feeBps += bps;
561
636
  const codeHash = typeof account?.code_hash === "string" ? account.code_hash : "";
562
637
  const storageCost = account ? amountOf(account.storage_usage, "view_account.storage_usage") * STORAGE_PRICE_PER_BYTE : 0n;
638
+ const paused = pausedFlag || pausedKeys === "unreadable" || pausedKeys.includes("ALL");
563
639
  return {
564
640
  contract: pool.contract,
565
641
  symbol: typeof meta.symbol === "string" ? meta.symbol : pool.symbol,
@@ -570,6 +646,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
570
646
  totalShares: amountOf(summary.total_share_amount, "get_summary.total_share_amount"),
571
647
  validators: typeof summary.validators_num === "number" ? summary.validators_num : 0,
572
648
  paused,
649
+ pausedFeatures: pausedKeys === "unreadable" ? [] : pausedKeys,
573
650
  codeHash,
574
651
  codeHashKnown: codeHash !== "" && pool.codeHashes.includes(codeHash),
575
652
  liquidity: account ? amountOf(account.amount, "view_account.amount") : 0n,
@@ -663,14 +740,14 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
663
740
  const info = await this.getPoolInfo();
664
741
  const a = await this.readAccount(me, info.price);
665
742
  const unstaked = a.unstaked > UNSTAKED_DUST ? a.unstaked : 0n;
666
- const withdrawable = unstaked > 0n && a.canWithdraw && _LiquidStakingProtocolNear.payable(info, unstaked) ? unstaked : 0n;
743
+ const withdrawable = unstaked > 0n && a.canWithdraw && _LiquidStakingProtocolNear.payable(info, unstaked) && !_LiquidStakingProtocolNear.withdrawPaused(info) ? unstaked : 0n;
667
744
  return { balance: a.shares, wrappedBalance: 0n, rate: info.price, total: a.value, unstaked, withdrawable, price: info.price };
668
745
  }
669
746
  /**
670
747
  * The account's unstaked NEAR as one request (a contract keeps one unstaked balance per account):
671
748
  * id `poolRequestId(contract)`, `unlockEpoch` exact from the contract. `claimable` needs the epoch
672
- * reached and the contract's liquid balance to cover it (`awaitingLiquidity` otherwise).
673
- * `timestamp` is 0: the contract does not keep the unstake time.
749
+ * reached, the contract's liquid balance to cover it (`awaitingLiquidity` otherwise) and withdrawals
750
+ * not paused (`paused`). `timestamp` is 0: the contract does not keep the unstake time.
674
751
  */
675
752
  async getWithdrawalRequests() {
676
753
  const me = await this.me();
@@ -678,7 +755,8 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
678
755
  const a = await this.readAccount(me, info.price);
679
756
  if (a.unstaked <= UNSTAKED_DUST) return { requests: [], pendingAmount: 0n, claimableAmount: 0n, claimableIds: [] };
680
757
  const awaitingLiquidity = a.canWithdraw && !_LiquidStakingProtocolNear.payable(info, a.unstaked);
681
- const claimable = a.canWithdraw && !awaitingLiquidity;
758
+ const paused = _LiquidStakingProtocolNear.withdrawPaused(info);
759
+ const claimable = a.canWithdraw && !awaitingLiquidity && !paused;
682
760
  const id = poolRequestId(info.contract);
683
761
  const request = {
684
762
  id,
@@ -688,6 +766,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
688
766
  contract: info.contract,
689
767
  unlockEpoch: a.unlockEpoch,
690
768
  awaitingLiquidity,
769
+ paused,
691
770
  unlock: claimable ? null : this.contractUnlock(await this.getEpoch(), a.unlockEpoch)
692
771
  };
693
772
  return {
@@ -731,6 +810,12 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
731
810
  const info = await this.getPoolInfo();
732
811
  this.assertWritable(info);
733
812
  const transactions = [this.tx([fc("deposit_and_stake", {}, this.gas.stake, amount)])];
813
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
814
+ const storageFee = await this.storageFee(me);
815
+ if (storageFee > 0n && amount - storageFee < MIN_STAKE) {
816
+ 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 } });
817
+ }
818
+ 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.` }] : [];
734
819
  const [available, { fee, upfront, prices }, apr] = await Promise.all([this.available(me), this.costs(transactions), this.getApr().catch(() => null)]);
735
820
  const reserve = this.reserveAt(prices);
736
821
  const required = amount + upfront + reserve;
@@ -740,12 +825,13 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
740
825
  upfront,
741
826
  reserve,
742
827
  amount,
743
- shares: sharesForNear(amount, info),
828
+ storageFee,
829
+ shares: sharesForNear(amount - storageFee, info),
744
830
  price: info.price,
745
831
  apr,
746
832
  maxStakeable: _LiquidStakingProtocolNear.maxStakeable(available, reserve, upfront),
747
833
  transactions,
748
- warnings: []
834
+ warnings
749
835
  };
750
836
  }
751
837
  /** The stake's transaction, fee, tokens expected and APR; nothing is signed. */
@@ -774,19 +860,22 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
774
860
  const amount = all ? a.stakedNear : nearForShares(shares, info);
775
861
  if (amount === 0n) throw new LiquidStakingError("below-minimum", `${shares} ${info.symbol} base units are worth less than 1 yoctoNEAR.`);
776
862
  const unstake = all ? fc("unstake_all", {}, this.gas.unstake, 0n) : fc("unstake", { amount: String(amount) }, this.gas.unstake, 0n);
863
+ _LiquidStakingProtocolNear.assertNotPaused(info, [this.tx([unstake])]);
777
864
  const warnings = [];
778
865
  const actions = [];
779
866
  let withdrawsFirst = 0n, relocks = 0n, resetsTimer = false;
780
867
  if (a.unstaked > UNSTAKED_DUST && a.canWithdraw) {
781
- if (_LiquidStakingProtocolNear.payable(info, a.unstaked)) {
868
+ const withdrawPaused = _LiquidStakingProtocolNear.withdrawPaused(info);
869
+ if (_LiquidStakingProtocolNear.payable(info, a.unstaked) && !withdrawPaused) {
782
870
  actions.push(fc("withdraw_all", {}, this.gas.withdraw, 0n));
783
871
  withdrawsFirst = a.unstaked;
784
872
  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.` });
785
873
  } else if (!o.allowRelock || amount < MIN_STAKE) {
786
- 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 } });
874
+ const why = withdrawPaused ? "has withdrawals paused" : "cannot pay it out yet (it is waiting for its payout)";
875
+ 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 } });
787
876
  } else {
788
877
  relocks = a.unstaked;
789
- 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.` });
878
+ 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.` });
790
879
  }
791
880
  } else if (a.unstaked > UNSTAKED_DUST) {
792
881
  if (amount < MIN_STAKE || !o.allowTimerReset) {
@@ -798,6 +887,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
798
887
  actions.push(unstake);
799
888
  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." });
800
889
  const transactions = [this.tx(actions)];
890
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
801
891
  const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
802
892
  if (upfront > available) throw new InsufficientFundsError(upfront, available, "NEAR");
803
893
  const earliestEpoch = epoch.height + MIN_EPOCHS_TO_UNLOCK;
@@ -850,6 +940,7 @@ var LiquidStakingProtocolNear = class _LiquidStakingProtocolNear extends Staking
850
940
  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 } });
851
941
  }
852
942
  const transactions = [this.tx([fc("withdraw_all", {}, this.gas.withdraw, 0n)])];
943
+ _LiquidStakingProtocolNear.assertNotPaused(info, transactions);
853
944
  const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)]);
854
945
  if (upfront > available) throw new InsufficientFundsError(upfront, available, "NEAR");
855
946
  return { fee, upfront, amount: a.unstaked, transactions };
@@ -890,6 +981,7 @@ export {
890
981
  MODULE_NAME,
891
982
  NEAR_MAINNET,
892
983
  NEAR_TESTNET,
984
+ PAUSE_KEYS,
893
985
  PRICE_SCALE,
894
986
  STORAGE_DEPOSIT,
895
987
  TGAS,