@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 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/protocol.ts","../src/activity.ts","../src/constants.ts","../src/epoch.ts","../src/errors.ts","../src/fees.ts","../src/math.ts","../src/pool.ts","../src/rpc.ts","../src/transactions.ts"],"sourcesContent":["export { LiquidStakingProtocolNear, LiquidStakingProtocolNear as default } from './protocol.js'\nexport type {\n NearNetwork, LiquidPoolConfig, LiquidStakingNearConfig, LiquidPoolInfo, LiquidAccountDetails, NearEpoch, UnlockEstimate,\n LiquidStakedBalance, LiquidStakingWarningCode, LiquidStakingWarning, LiquidWriteOptions, LiquidStakeOptions, LiquidStakeQuote,\n LiquidStakeResult, LiquidUnstakeOptions, LiquidUnstakeQuote, LiquidUnstakeResult, LiquidWithdrawalRequest,\n LiquidWithdrawalRequestsView, LiquidClaimOptions, LiquidClaimQuote, LiquidClaimResult, NearTransactionsSender,\n} from './types.js'\nexport { LiquidStakingError, type LiquidStakingErrorCode } from './errors.js'\nexport { resolvePool, validatePoolConfig, poolRequestId, type ResolvedLiquidPool } from './pool.js'\nexport { sameTransactions, canSendBatch, fc, assertLiquidPlan, LIQUID_WRITE_METHODS } from './transactions.js'\nexport { readEpoch, readEpochNumbers, epochStartsAt, finalBlock, blockAt, type BlockTime, type EpochNumbers, type ReadEpochOptions } from './epoch.js'\nexport { sharesForNear, nearForShares, valueAtPrice, aprFromPrices } from './math.js'\nexport { resolveRpc } from './rpc.js'\nexport { GasPricer, costOf, gasOf, type GasCost, type GasPrices } from './fees.js'\nexport { describeLiquidNearStakingActivity, MODULE_NAME } from './activity.js'\nexport * from './constants.js'\n","import {\n InsufficientFundsError, NetworkError, StakingProtocol, bigintToNumber,\n type ActivityItem, type ChainTx, type DescribeActivityContext, type IWalletAccount, type IWalletAccountReadOnly, type TransferResult, type WriteOptions,\n} from '@anywalletkit/core'\nimport {\n NearRpc, NearRpcError, STORAGE_PRICE_PER_BYTE, createClient, toBase64, type NearAction, type NearTransaction,\n} from '@anywalletkit/wallet-near'\nimport { describeLiquidNearStakingActivity } from './activity.js'\nimport {\n CONTRACT_MIN_RESERVE_BALANCE, DEFAULT_APR_WINDOW_EPOCHS, DEFAULT_ARCHIVAL_RPC, DEFAULT_GAS, DEFAULT_RESERVE, EPOCH_LENGTH, MIN_EPOCHS_TO_UNLOCK,\n MIN_STAKE, NEAR_MAINNET, NEAR_TESTNET, PAUSE_KEYS, TGAS, UNSTAKED_DUST, YOCTO_PER_NEAR,\n} from './constants.js'\nimport { blockAt, epochStartsAt, readEpoch, readEpochNumbers, type EpochNumbers } from './epoch.js'\nimport { LiquidStakingError } from './errors.js'\nimport { GasPricer, costOf, type GasCost, type GasPrices } from './fees.js'\nimport { aprFromPrices, nearForShares, sharesForNear, valueAtPrice } from './math.js'\nimport { poolRequestId, resolvePool, validatePoolConfig, type ResolvedLiquidPool } from './pool.js'\nimport { resolveRpc } from './rpc.js'\nimport { assertLiquidPlan, fc, sameTransactions } from './transactions.js'\nimport type {\n LiquidAccountDetails, LiquidClaimOptions, LiquidClaimQuote, LiquidClaimResult, LiquidPoolInfo, LiquidStakedBalance, LiquidStakeOptions,\n LiquidStakeQuote, LiquidStakeResult, LiquidStakingNearConfig, LiquidStakingWarning, LiquidUnstakeOptions, LiquidUnstakeQuote, LiquidUnstakeResult,\n LiquidWithdrawalRequest, LiquidWithdrawalRequestsView, NearEpoch, NearNetwork, UnlockEstimate,\n} from './types.js'\n\n/** How long the epoch numbers (one ~375 KB `validators` answer) are reused; they change only at epoch boundaries. */\nconst EPOCH_NUMBERS_TTL_MS = 60_000\n/** How long the price-based APR is reused. */\nconst APR_TTL_MS = 10 * 60_000\n/** Window of the APR fallback on the regular RPC when the archival one fails (regular nodes keep ~5 epochs). */\nconst APR_FALLBACK_EPOCHS = 2n\n/** Heights tried after a skipped one for a past-block read. */\nconst SKIP_TRIES = 10\n/** The protocol's gas cap per function call. */\nconst MAX_CALL_GAS = 300n * TGAS\n\n/** The account's state in the contract plus what the writes need beside it. */\ninterface AccountState extends LiquidAccountDetails {\n /** `get_account_details.staked_balance`: what `unstake_all` moves, in NEAR. */\n stakedNear: bigint\n}\n\n/** What a paused feature stops, for messages. */\nconst FEATURE_WORDS: Readonly<Record<string, string>> = {\n internal_deposit: 'deposits', internal_stake: 'staking', internal_unstake: 'unstaking', internal_withdraw: 'withdrawals',\n}\n\nconst near = (yocto: bigint): string => {\n const frac = (yocto % YOCTO_PER_NEAR).toString().padStart(24, '0').slice(0, 5).replace(/0+$/, '')\n return `${yocto / YOCTO_PER_NEAR}${frac ? `.${frac}` : ''} NEAR`\n}\n\n/** A u128 decimal string (or a small JSON number, as u64 fields come) from a contract answer. */\nfunction amountOf(v: unknown, what: string): bigint {\n if (typeof v === 'string' && /^\\d+$/.test(v)) return BigInt(v)\n if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) return BigInt(v)\n throw new NetworkError(`${what}: expected a non-negative integer, got ${String(JSON.stringify(v)).slice(0, 60)}`)\n}\n\n/** The contract has no such method: the node says MethodNotFound, in the call result's error text or in a structured JSON-RPC error. */\nfunction methodMissing(e: NearRpcError): boolean {\n if (/MethodNotFound/.test(e.message)) return true\n try {\n return /MethodNotFound/.test(JSON.stringify(e.cause) ?? '')\n } catch {\n return false\n }\n}\n\n/** A bigint or a safe integer above zero, else 'invalid-amount'. */\nfunction positiveAmount(v: unknown, unit: string): bigint {\n if (typeof v !== 'bigint' && !(typeof v === 'number' && Number.isSafeInteger(v))) {\n throw new LiquidStakingError('invalid-amount', `'amount' must be a bigint or a safe integer (${unit}).`)\n }\n const amount = BigInt(v)\n if (amount <= 0n) throw new LiquidStakingError('invalid-amount', \"'amount' must be greater than zero.\")\n return amount\n}\n\n/** The longest `unstake` argument (a u128), so the exit probe never undercounts gas. */\nconst MAX_U128_DIGITS = '9'.repeat(39)\n\n/** A fresh copy, so an account that rewrites what it is handed cannot change the quote the app holds. */\nconst copyTx = (tx: NearTransaction): NearTransaction => ({\n receiverId: tx.receiverId,\n actions: tx.actions.map((a) => ('functionCall' in a ? { functionCall: { ...a.functionCall, args: { ...(a.functionCall.args as Record<string, unknown>) } } } : a)),\n})\n\n/**\n * Liquid NEAR staking through the LiNEAR contract family (LiNEAR, Rhea rNEAR): `deposit_and_stake`\n * mints the token, `unstake` starts the delayed exit (4+ epochs, exact epoch from the contract),\n * `withdraw_all` pays out once unlocked and the contract holds the NEAR. See the package README.\n *\n * Never builds `ft_transfer_call` or `ft_transfer` into the contract (it has no `ft_on_transfer`:\n * tokens sent that way are lost), and nothing but function calls to the pinned contract. Writes\n * refuse a paused contract (or a paused feature their calls need) or one whose code hash is not\n * pinned. Every quote returns the exact transactions; a write given `expected` refuses when its\n * fresh plan differs.\n */\nexport class LiquidStakingProtocolNear extends StakingProtocol<LiquidStakingNearConfig> {\n readonly reserve: bigint\n readonly gas: { stake: bigint; unstake: bigint; withdraw: bigint }\n readonly aprWindowEpochs: number\n private readonly configuredNetwork: NearNetwork | undefined\n protected readonly rpc: NearRpc | undefined\n private archival: NearRpc | undefined\n private numbersCache: { at: number; value: Promise<EpochNumbers> } | undefined\n private readonly blockTimes = new Map<bigint, number>()\n private aprCache: { at: number; value: Promise<number> } | undefined\n private readonly pricer = new GasPricer(() => this.client())\n\n constructor(account: IWalletAccountReadOnly | IWalletAccount, config: LiquidStakingNearConfig) {\n super(account, config)\n if (!config || typeof config !== 'object') throw new LiquidStakingError('invalid-config', \"LiquidStakingProtocolNear needs a config with `pool` ('linear', 'rnear' or a contract).\")\n validatePoolConfig(config.pool)\n if (config.network !== undefined && config.network !== 'mainnet' && config.network !== 'testnet') {\n throw new LiquidStakingError('invalid-config', \"network must be 'mainnet' or 'testnet'.\")\n }\n this.configuredNetwork = config.network\n if (config.reserve !== undefined && typeof config.reserve !== 'bigint' && !(typeof config.reserve === 'number' && Number.isSafeInteger(config.reserve))) {\n throw new LiquidStakingError('invalid-config', 'reserve must be a bigint or a safe integer (yoctoNEAR).')\n }\n this.reserve = BigInt(config.reserve ?? DEFAULT_RESERVE)\n if (this.reserve < 0n) throw new LiquidStakingError('invalid-config', 'reserve must not be negative.')\n this.gas = { stake: config.gas?.stake ?? DEFAULT_GAS.stake, unstake: config.gas?.unstake ?? DEFAULT_GAS.unstake, withdraw: config.gas?.withdraw ?? DEFAULT_GAS.withdraw }\n for (const [k, g] of Object.entries(this.gas)) {\n 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.`)\n }\n 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.')\n this.aprWindowEpochs = config.aprWindowEpochs ?? DEFAULT_APR_WINDOW_EPOCHS\n if (!Number.isInteger(this.aprWindowEpochs) || this.aprWindowEpochs < 1) throw new LiquidStakingError('invalid-config', 'aprWindowEpochs must be a positive integer.')\n if (config.apr !== undefined && typeof config.apr !== 'function') throw new LiquidStakingError('invalid-config', 'apr must be a function returning the APR in percent.')\n this.rpc = resolveRpc(account, config)\n }\n\n /** The configured network, else the account's (`near:testnet` → testnet, anything else → mainnet). */\n get network(): NearNetwork {\n return this.configuredNetwork ?? (this._account.chain === NEAR_TESTNET ? 'testnet' : 'mainnet')\n }\n\n /** Contract, symbol and pinned code hashes on the current network (throws 'unsupported-network'). */\n get pool(): ResolvedLiquidPool {\n return resolvePool(this._config.pool, this.network)\n }\n\n // ── Plumbing ───────────────────────────────────────────────────────────────\n\n private client(): NearRpc {\n if (!this.rpc) throw new LiquidStakingError('no-provider', 'LiquidStakingProtocolNear needs a NEAR RPC: pass `provider`, or a wallet-near account configured with one.')\n return this.rpc\n }\n\n private archivalClient(): NearRpc {\n if (!this.archival) {\n const fetch = createClient({\n provider: this._config.archivalProvider ?? DEFAULT_ARCHIVAL_RPC[this.network],\n ...(this._config.timeoutMs !== undefined ? { timeoutMs: this._config.timeoutMs } : {}),\n })\n if (!fetch) throw new LiquidStakingError('no-provider', 'No archival RPC for the APR estimate: pass `archivalProvider` or an `apr` hook.')\n this.archival = new NearRpc(fetch)\n }\n return this.archival\n }\n\n /** The account id, after checking the account is on the module's NEAR network. */\n private async me(): Promise<string> {\n const want = this.network === 'testnet' ? NEAR_TESTNET : NEAR_MAINNET\n if (this._account.chain !== want) throw new LiquidStakingError('wrong-chain', `LiquidStakingProtocolNear works on ${want}; the account is on ${this._account.chain}.`)\n return await this._account.getAddress()\n }\n\n private view<T>(method: string, args: Record<string, unknown> = {}): Promise<T> {\n return this.client().callFunction<T>(this.pool.contract, method, args)\n }\n\n private epochNumbers(): Promise<EpochNumbers> {\n const hit = this.numbersCache\n if (hit && Date.now() - hit.at < EPOCH_NUMBERS_TTL_MS) return hit.value\n const value = readEpochNumbers(this.client())\n this.numbersCache = { at: Date.now(), value }\n value.catch(() => { if (this.numbersCache?.value === value) this.numbersCache = undefined })\n return value\n }\n\n /** Spendable NEAR of the account: amount − max(0, storage − locked), never below 0 (0 for an account that does not exist yet). */\n private async available(me: string): Promise<bigint> {\n const v = await this.client().viewAccount(me)\n if (!v) return 0n\n // `amount` is the liquid balance (`locked` is not part of it), and the locked balance pays for storage first.\n const storage = amountOf(v.storage_usage, 'view_account.storage_usage') * STORAGE_PRICE_PER_BYTE\n const locked = amountOf(v.locked, 'view_account.locked')\n const free = amountOf(v.amount, 'view_account.amount') - (storage > locked ? storage - locked : 0n)\n return free > 0n ? free : 0n\n }\n\n /** Fee (upper bound) and upfront charge of the transactions at the current prices (see fees.ts). */\n private async costs(transactions: NearTransaction[]): Promise<GasCost & { prices: GasPrices }> {\n const prices = await this.pricer.prices()\n return { ...costOf(transactions, prices), prices }\n }\n\n /** What `stake` leaves on the account: `reserve`, but never less than the upfront gas of the exit it will need. */\n private reserveAt(prices: GasPrices): bigint {\n const gas = this.gas.unstake > this.gas.withdraw ? this.gas.unstake : this.gas.withdraw\n const exit = costOf([{ receiverId: this.pool.contract, actions: [fc('unstake', { amount: MAX_U128_DIGITS }, gas, 0n)] }], prices).upfront\n return exit > this.reserve ? exit : this.reserve\n }\n\n private tx(actions: NearAction[]): NearTransaction {\n const tx = { receiverId: this.pool.contract, actions }\n assertLiquidPlan([tx], this.pool.contract)\n return tx\n }\n\n private assertWritable(info: LiquidPoolInfo): void {\n if (!info.codeHashKnown) {\n 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] } })\n }\n if (info.paused) throw new LiquidStakingError('contract-paused', `${info.name} (${info.contract}) is paused: it rejects every call until it resumes.`)\n }\n\n /** The paused features a plan's calls check (see PAUSE_KEYS); empty when every call goes through. */\n private static pausedFor(info: LiquidPoolInfo, methods: string[]): string[] {\n const keys = new Set(methods.flatMap((m) => PAUSE_KEYS[m] ?? []))\n return info.pausedFeatures.filter((k) => keys.has(k))\n }\n\n /** Withdrawals are stopped: the whole contract or its withdraw feature is paused. */\n private static withdrawPaused(info: LiquidPoolInfo): boolean {\n return info.paused || LiquidStakingProtocolNear.pausedFor(info, ['withdraw_all']).length > 0\n }\n\n /** 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. */\n private static assertNotPaused(info: LiquidPoolInfo, transactions: NearTransaction[]): void {\n const methods = transactions.flatMap((t) => t.actions.flatMap((a) => ('functionCall' in a ? [a.functionCall.methodName] : [])))\n const paused = LiquidStakingProtocolNear.pausedFor(info, methods)\n if (paused.length === 0) return\n const what = [...new Set(paused.map((k) => FEATURE_WORDS[k] ?? k))].join(' and ')\n throw new LiquidStakingError('contract-paused', `${info.name} (${info.contract}) has ${what} paused (${paused.join(', ')}): this transaction would fail until it resumes.`, { details: { pausedFeatures: paused } })\n }\n\n /**\n * NEAR the contract keeps from a stake for the account's NEP-145 registration: storage_balance_bounds.min\n * when the contract charges it (rNEAR) and the account is not registered yet, else 0. Read live.\n */\n private async storageFee(me: string): Promise<bigint> {\n if (!this.pool.firstStakePaysStorage) return 0n\n const [balance, bounds] = await Promise.all([\n this.view<unknown>('storage_balance_of', { account_id: me }),\n this.view<{ min?: unknown } | null>('storage_balance_bounds'),\n ])\n if (balance !== null && balance !== undefined) return 0n\n return amountOf(bounds?.min, 'storage_balance_bounds.min')\n }\n\n private async readAccount(me: string, price: bigint): Promise<AccountState> {\n const [balance, details, storage] = await Promise.all([\n this.view<unknown>('ft_balance_of', { account_id: me }),\n this.view<Record<string, unknown> | null>('get_account_details', { account_id: me }),\n this.view<unknown>('storage_balance_of', { account_id: me }),\n ])\n if (!details || typeof details !== 'object') throw new NetworkError(`${this.pool.contract}.get_account_details: no account details in the answer`)\n if (typeof details.can_withdraw !== 'boolean') throw new NetworkError(`${this.pool.contract}.get_account_details: can_withdraw is not a boolean`)\n const shares = amountOf(balance, 'ft_balance_of')\n return {\n shares,\n value: valueAtPrice(shares, price),\n unstaked: amountOf(details.unstaked_balance, 'get_account_details.unstaked_balance'),\n unlockEpoch: amountOf(details.unstaked_available_epoch_height, 'get_account_details.unstaked_available_epoch_height'),\n canWithdraw: details.can_withdraw,\n registered: storage !== null && storage !== undefined,\n stakedNear: amountOf(details.staked_balance, 'get_account_details.staked_balance'),\n }\n }\n\n private contractUnlock(epoch: NearEpoch, unlockEpoch: bigint): UnlockEstimate {\n const at = epochStartsAt(epoch, unlockEpoch)\n return { epoch: unlockEpoch, earliestEpoch: unlockEpoch, latestEpoch: unlockEpoch, at, earliestAt: at, latestAt: at, source: 'contract' }\n }\n\n /**\n * The contract can pay `amount` now: its liquid balance minus what it must keep covers it. It\n * keeps 1 NEAR itself, and the runtime refuses a receipt that leaves it below its storage cost\n * (the whole transaction would fail, on every retry).\n */\n private static payable(info: LiquidPoolInfo, amount: bigint): boolean {\n return info.liquidity - info.kept >= amount\n }\n\n // ── Reads ──────────────────────────────────────────────────────────────────\n\n /** The epoch clock: height, start, measured duration (~6.9 h on mainnet), estimated end. */\n async getEpoch(): Promise<NearEpoch> {\n return readEpoch(this.client(), { numbers: () => this.epochNumbers(), blockTimes: this.blockTimes })\n }\n\n /** Contract state: price, totals, pause flag, live code hash, liquidity, fee. Read fresh every time. */\n async getPoolInfo(): Promise<LiquidPoolInfo> {\n const pool = this.pool\n const rpc = this.client()\n const [meta, summary, pausedFlag, pausedKeys, account, beneficiaries] = await Promise.all([\n this.view<{ symbol?: unknown; decimals?: unknown } | null>('ft_metadata'),\n this.view<Record<string, unknown> | null>('get_summary'),\n // A contract answer other than `false` (a missing method, a panic, a non-boolean) counts as paused; a transport failure is thrown.\n this.view<unknown>('is_paused').then((v) => v !== false, (e: unknown) => {\n if (e instanceof NearRpcError) return true\n throw e\n }),\n // Per-feature pauses (near-plugins Pausable, rNEAR): null when none. LiNEAR has only `is_paused`\n // and is not asked; a custom contract without the method has none. Any other contract answer (a\n // panic, a non-list) counts as paused.\n !pool.featurePauses ? Promise.resolve<string[]>([]) : this.view<unknown>('pa_all_paused').then<string[] | 'unreadable', string[] | 'unreadable'>((v) => {\n if (v === null) return []\n return Array.isArray(v) && v.every((k) => typeof k === 'string') ? [...v].sort() : 'unreadable'\n }, (e: unknown) => {\n if (e instanceof NearRpcError) return methodMissing(e) ? [] : 'unreadable'\n throw e\n }),\n rpc.viewAccount(pool.contract),\n this.view<Record<string, unknown> | null>('get_beneficiaries').catch((e: unknown) => {\n if (e instanceof NearRpcError) return null\n throw e\n }),\n ])\n if (!summary || typeof summary !== 'object') throw new NetworkError(`${pool.contract}.get_summary: no summary in the answer`)\n if (meta?.decimals !== 24) throw new NetworkError(`${pool.contract}.ft_metadata: expected 24 decimals, got ${String(meta?.decimals)}`)\n let feeBps = 0\n for (const bps of Object.values(beneficiaries ?? {})) if (typeof bps === 'number' && Number.isInteger(bps) && bps >= 0) feeBps += bps\n const codeHash = typeof account?.code_hash === 'string' ? account.code_hash : ''\n const storageCost = account ? amountOf(account.storage_usage, 'view_account.storage_usage') * STORAGE_PRICE_PER_BYTE : 0n\n const paused = pausedFlag || pausedKeys === 'unreadable' || pausedKeys.includes('ALL')\n return {\n contract: pool.contract,\n symbol: typeof meta.symbol === 'string' ? meta.symbol : pool.symbol,\n name: pool.name,\n decimals: 24,\n price: amountOf(summary.ft_price, 'get_summary.ft_price'),\n totalStaked: amountOf(summary.total_staked_near_amount, 'get_summary.total_staked_near_amount'),\n totalShares: amountOf(summary.total_share_amount, 'get_summary.total_share_amount'),\n validators: typeof summary.validators_num === 'number' ? summary.validators_num : 0,\n paused,\n pausedFeatures: pausedKeys === 'unreadable' ? [] : pausedKeys,\n codeHash,\n codeHashKnown: codeHash !== '' && pool.codeHashes.includes(codeHash),\n liquidity: account ? amountOf(account.amount, 'view_account.amount') : 0n,\n kept: storageCost > CONTRACT_MIN_RESERVE_BALANCE ? storageCost : CONTRACT_MIN_RESERVE_BALANCE,\n feeBps,\n }\n }\n\n /** The account in the contract: tokens, their NEAR value, unstaked NEAR, exact unlock epoch, registration. */\n async getAccountDetails(): Promise<LiquidAccountDetails> {\n const me = await this.me()\n const price = amountOf(await this.view<unknown>('ft_price'), 'ft_price')\n const a = await this.readAccount(me, price)\n return { shares: a.shares, value: a.value, unstaked: a.unstaked, unlockEpoch: a.unlockEpoch, canWithdraw: a.canWithdraw, registered: a.registered }\n }\n\n /** What `stake` can send now: available − reserve − the stake's upfront gas (never below 0). */\n async getMaxStakeable(): Promise<bigint> {\n const me = await this.me()\n const [available, cost] = await Promise.all([this.available(me), this.costs([this.tx([fc('deposit_and_stake', {}, this.gas.stake, MIN_STAKE)])])])\n return LiquidStakingProtocolNear.maxStakeable(available, this.reserveAt(cost.prices), cost.upfront)\n }\n\n private static maxStakeable(available: bigint, reserve: bigint, upfront: bigint): bigint {\n const max = available - reserve - upfront\n return max > 0n ? max : 0n\n }\n\n /**\n * APR in percent: the `apr` hook, else the token price's growth over `aprWindowEpochs` (default 24,\n * ~7 days), annualized by the two blocks' timestamps. The past price comes from the archival RPC;\n * when that fails, from a 2-epoch window on the regular RPC. Cached for 10 minutes.\n */\n override async getApr(): Promise<number> {\n if (this._config.apr) return await this._config.apr()\n const hit = this.aprCache\n if (hit && Date.now() - hit.at < APR_TTL_MS) return await hit.value\n const value = this.priceApr()\n this.aprCache = { at: Date.now(), value }\n value.catch(() => { if (this.aprCache?.value === value) this.aprCache = undefined })\n return await value\n }\n\n private async priceApr(): Promise<number> {\n const rpc = this.client()\n const now = await this.priceAt(rpc)\n try {\n const past = await this.priceAt(this.archivalClient(), now.height - BigInt(this.aprWindowEpochs) * EPOCH_LENGTH)\n return aprFromPrices(past.price, now.price, past.ms, now.ms)\n } catch (archivalError) {\n try {\n const past = await this.priceAt(rpc, now.height - APR_FALLBACK_EPOCHS * EPOCH_LENGTH)\n return aprFromPrices(past.price, now.price, past.ms, now.ms)\n } catch {\n throw archivalError\n }\n }\n }\n\n /** `ft_price` at a height (the next produced block when it was skipped), or at the final block, with that block's time. */\n private async priceAt(rpc: NearRpc, height?: bigint): Promise<{ price: bigint; height: bigint; ms: number }> {\n const contract = this.pool.contract\n const args = toBase64(new TextEncoder().encode('{}'))\n const query = async (blockRef: Record<string, unknown>) => {\n const r = (await rpc.fetch('query', { request_type: 'call_function', account_id: contract, method_name: 'ft_price', args_base64: args, ...blockRef })) as { result?: number[]; error?: string; block_height?: number } | null\n if (!r || r.error || !Array.isArray(r.result) || typeof r.block_height !== 'number') throw new NetworkError(`${contract}.ft_price: no result${r?.error ? ` (${r.error})` : ''}`)\n return { price: amountOf(JSON.parse(new TextDecoder().decode(Uint8Array.from(r.result))), 'ft_price'), height: BigInt(r.block_height) }\n }\n let read: { price: bigint; height: bigint } | undefined\n if (height === undefined) read = await query({ finality: 'final' })\n else {\n let last: unknown\n for (let i = 0n; i <= BigInt(SKIP_TRIES) && !read; i++) {\n try {\n read = await query({ block_id: bigintToNumber(height + i) })\n } catch (e) {\n // Only a skipped height moves on.\n if (!(e instanceof NearRpcError) || !/UNKNOWN_BLOCK/i.test(e.errorName ?? '')) throw e\n last = e\n }\n }\n if (!read) throw last\n }\n const known = this.blockTimes.get(read.height)\n const ms = known ?? (await blockAt(rpc, read.height)).ms\n this.blockTimes.set(read.height, ms)\n return { ...read, ms }\n }\n\n /**\n * The position, Tonstakers-style: `balance` = tokens held, `rate` = price (yoctoNEAR per token,\n * 10^24 = 1:1), `total` = their NEAR value; `unstaked` and `withdrawable` (unlocked and payable\n * from the contract's liquid balance now) beside.\n */\n override async getStakedBalance(): Promise<LiquidStakedBalance> {\n const me = await this.me()\n const info = await this.getPoolInfo()\n const a = await this.readAccount(me, info.price)\n const unstaked = a.unstaked > UNSTAKED_DUST ? a.unstaked : 0n\n const withdrawable = unstaked > 0n && a.canWithdraw && LiquidStakingProtocolNear.payable(info, unstaked) && !LiquidStakingProtocolNear.withdrawPaused(info) ? unstaked : 0n\n return { balance: a.shares, wrappedBalance: 0n, rate: info.price, total: a.value, unstaked, withdrawable, price: info.price }\n }\n\n /**\n * The account's unstaked NEAR as one request (a contract keeps one unstaked balance per account):\n * id `poolRequestId(contract)`, `unlockEpoch` exact from the contract. `claimable` needs the epoch\n * reached, the contract's liquid balance to cover it (`awaitingLiquidity` otherwise) and withdrawals\n * not paused (`paused`). `timestamp` is 0: the contract does not keep the unstake time.\n */\n override async getWithdrawalRequests(): Promise<LiquidWithdrawalRequestsView> {\n const me = await this.me()\n const info = await this.getPoolInfo()\n const a = await this.readAccount(me, info.price)\n if (a.unstaked <= UNSTAKED_DUST) return { requests: [], pendingAmount: 0n, claimableAmount: 0n, claimableIds: [] }\n const awaitingLiquidity = a.canWithdraw && !LiquidStakingProtocolNear.payable(info, a.unstaked)\n const paused = LiquidStakingProtocolNear.withdrawPaused(info)\n const claimable = a.canWithdraw && !awaitingLiquidity && !paused\n const id = poolRequestId(info.contract)\n const request: LiquidWithdrawalRequest = {\n id, amount: a.unstaked, timestamp: 0, claimable, contract: info.contract, unlockEpoch: a.unlockEpoch, awaitingLiquidity, paused,\n unlock: claimable ? null : this.contractUnlock(await this.getEpoch(), a.unlockEpoch),\n }\n return {\n requests: [request],\n pendingAmount: claimable ? 0n : a.unstaked,\n claimableAmount: claimable ? a.unstaked : 0n,\n claimableIds: claimable ? [id] : [],\n }\n }\n\n // ── Writes ─────────────────────────────────────────────────────────────────\n\n /** Plans with fresh reads, compares with `expected`, then sends each transaction in order. */\n private async send<Q extends { transactions: NearTransaction[]; fee: bigint }>(\n method: string, plan: () => Promise<Q>, o: { expected?: NearTransaction[]; maxFee?: bigint } | undefined,\n ): Promise<Q & { fee: bigint; hash: string; hashes: string[] }> {\n const account = this.requireSigningAccount(method)\n const quote = await plan()\n assertLiquidPlan(quote.transactions, this.pool.contract)\n if (o?.expected !== undefined && !sameTransactions(o.expected, quote.transactions)) {\n 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 } })\n }\n // The module checks maxFee itself: wallet-selector adapters ignore it.\n if (o?.maxFee !== undefined && quote.fee > BigInt(o.maxFee)) {\n 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) } })\n }\n const options: WriteOptions | undefined = o?.maxFee !== undefined ? { maxFee: o.maxFee } : undefined\n const hashes: string[] = []\n let fee = 0n\n for (const tx of quote.transactions) {\n let r: TransferResult\n try {\n r = await account.sendTransaction(copyTx(tx), options)\n } catch (e) {\n throw Object.assign(e instanceof Error ? e : new Error(String(e)), { sent: [...hashes] })\n }\n hashes.push(r.hash)\n fee += BigInt(r.fee ?? 0)\n }\n return { ...quote, fee, hash: hashes[0]!, hashes }\n }\n\n private async planStake(o: LiquidStakeOptions): Promise<LiquidStakeQuote> {\n const amount = positiveAmount(o?.amount, 'yoctoNEAR')\n if (amount < MIN_STAKE) throw new LiquidStakingError('below-minimum', `A stake must be at least ${near(MIN_STAKE)}.`)\n const me = await this.me()\n const info = await this.getPoolInfo()\n this.assertWritable(info)\n // deposit_and_stake creates the account's entry in the contract (real deposits on both contracts\n // carry no storage_deposit). rNEAR keeps storage_balance_bounds.min of an unregistered account's\n // deposit for that registration and stakes the rest; LiNEAR stakes all of it.\n const transactions = [this.tx([fc('deposit_and_stake', {}, this.gas.stake, amount)])]\n LiquidStakingProtocolNear.assertNotPaused(info, transactions)\n const storageFee = await this.storageFee(me)\n // At or below the fee the contract's `amount − fee` underflows or stakes nothing: the transaction fails and burns its gas.\n // Above it the contract stakes `amount − fee`, which is held to MIN_STAKE like any stake.\n if (storageFee > 0n && amount - storageFee < MIN_STAKE) {\n 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 } })\n }\n const warnings: LiquidStakingWarning[] = storageFee > 0n\n ? [{ 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.` }]\n : []\n const [available, { fee, upfront, prices }, apr] = await Promise.all([this.available(me), this.costs(transactions), this.getApr().catch(() => null)])\n const reserve = this.reserveAt(prices)\n const required = amount + upfront + reserve\n if (required > available) throw new InsufficientFundsError(required, available, 'NEAR')\n return {\n fee, upfront, reserve, amount, storageFee, shares: sharesForNear(amount - storageFee, info), price: info.price, apr,\n maxStakeable: LiquidStakingProtocolNear.maxStakeable(available, reserve, upfront), transactions, warnings,\n }\n }\n\n /** The stake's transaction, fee, tokens expected and APR; nothing is signed. */\n override async quoteStake(options: LiquidStakeOptions): Promise<LiquidStakeQuote> {\n return this.planStake(options)\n }\n\n /**\n * Stakes exactly `amount` yoctoNEAR (`deposit_and_stake`) for the token. There is no \"stake\n * everything\": pass the amount (at most `getMaxStakeable()`).\n */\n override async stake(options: LiquidStakeOptions): Promise<LiquidStakeResult> {\n return this.send('stake', () => this.planStake(options), options)\n }\n\n private async planUnstake(o: LiquidUnstakeOptions): Promise<LiquidUnstakeQuote> {\n const requested = o?.amount === 'all' ? 'all' : positiveAmount(o?.amount, 'token base units')\n const me = await this.me()\n const info = await this.getPoolInfo()\n this.assertWritable(info)\n const [a, epoch] = await Promise.all([this.readAccount(me, info.price), this.getEpoch()])\n if (a.shares === 0n) throw new LiquidStakingError('nothing-staked', `${me} holds no ${info.symbol}.`)\n if (requested !== 'all' && requested > a.shares) {\n throw new LiquidStakingError('exceeds-balance', `Asked to unstake ${requested} ${info.symbol} base units; the balance is ${a.shares}.`, { details: { balance: a.shares } })\n }\n const all = requested === 'all' || requested === a.shares\n const shares = all ? a.shares : requested\n // The contract takes NEAR, not tokens. This value burns at most `shares` (the contract rounds the burnt shares up from it).\n const amount = all ? a.stakedNear : nearForShares(shares, info)\n if (amount === 0n) throw new LiquidStakingError('below-minimum', `${shares} ${info.symbol} base units are worth less than 1 yoctoNEAR.`)\n const unstake = all ? fc('unstake_all', {}, this.gas.unstake, 0n) : fc('unstake', { amount: String(amount) }, this.gas.unstake, 0n)\n // Unstaking paused: refused before the relock check below, whose allowRelock would not help.\n LiquidStakingProtocolNear.assertNotPaused(info, [this.tx([unstake])])\n\n const warnings: LiquidStakingWarning[] = []\n const actions: NearAction[] = []\n let withdrawsFirst = 0n, relocks = 0n, resetsTimer = false\n if (a.unstaked > UNSTAKED_DUST && a.canWithdraw) {\n const withdrawPaused = LiquidStakingProtocolNear.withdrawPaused(info)\n if (LiquidStakingProtocolNear.payable(info, a.unstaked) && !withdrawPaused) {\n // A new unstake sets the unlock epoch of the whole unstaked balance: withdraw the unlocked part first.\n actions.push(fc('withdraw_all', {}, this.gas.withdraw, 0n))\n withdrawsFirst = a.unstaked\n 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.` })\n } else if (!o.allowRelock || amount < MIN_STAKE) {\n const why = withdrawPaused ? 'has withdrawals paused' : 'cannot pay it out yet (it is waiting for its payout)'\n 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 } })\n } else {\n relocks = a.unstaked\n 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.` })\n }\n } else if (a.unstaked > UNSTAKED_DUST) {\n // The contract keeps one unlock epoch per account: this unstake moves it for everything already unbonding.\n if (amount < MIN_STAKE || !o.allowTimerReset) {\n 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 } })\n }\n resetsTimer = true\n 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.` })\n }\n actions.push(unstake)\n warnings.push({ code: 'unlock-may-be-later', message: 'Unstaking takes 4 or more epochs (~6.9 h each, about 21–35 h or more): the contract may add epochs for large amounts or after its epoch settlement. The exact epoch is known after the unstake.' })\n\n const transactions = [this.tx(actions)]\n LiquidStakingProtocolNear.assertNotPaused(info, transactions)\n const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)])\n if (upfront > available) throw new InsufficientFundsError(upfront, available, 'NEAR')\n const earliestEpoch = epoch.height + MIN_EPOCHS_TO_UNLOCK\n return {\n fee, upfront, shares, amount, id: poolRequestId(info.contract), withdrawsFirst, resetsTimer, relocks,\n unlock: { epoch: null, earliestEpoch, latestEpoch: null, at: null, earliestAt: epochStartsAt(epoch, earliestEpoch), latestAt: null, source: 'estimate' },\n transactions, warnings,\n }\n }\n\n /** The unstake's transaction, fee and unlock estimate; nothing is signed. `amount` is in token base units. */\n override async quoteRequestWithdrawal(options: LiquidUnstakeOptions): Promise<LiquidUnstakeQuote> {\n return this.planUnstake(options)\n }\n\n /**\n * Unstakes `amount` token base units (`unstake` with their NEAR value), or `'all'` (`unstake_all`).\n * An unlocked balance is withdrawn in the same transaction first. Once it is final,\n * `getAccountDetails().unlockEpoch` is the exact epoch the NEAR unlocks at; reads use final blocks,\n * so right after the send they still show the previous one (show the result's `unlock` meanwhile).\n */\n override async requestWithdrawal(options: LiquidUnstakeOptions): Promise<LiquidUnstakeResult> {\n return { ...(await this.send('requestWithdrawal', () => this.planUnstake(options), options)), approveHash: null }\n }\n\n private async planClaim(o: LiquidClaimOptions = {}): Promise<LiquidClaimQuote> {\n const me = await this.me()\n const info = await this.getPoolInfo()\n this.assertWritable(info)\n const a = await this.readAccount(me, info.price)\n const id = poolRequestId(info.contract)\n if (o.ids !== undefined) {\n if (!Array.isArray(o.ids)) throw new LiquidStakingError('unknown-request', '`ids` must be a list of request ids.')\n const ids = [...new Set(o.ids.map((x) => BigInt(x)))]\n const unknown = ids.filter((x) => x !== id)\n 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 } })\n if (ids.length === 0) throw new LiquidStakingError('nothing-to-claim', 'No request ids were given.')\n }\n if (a.unstaked <= UNSTAKED_DUST) throw new LiquidStakingError('nothing-to-claim', `${me} has no unstaked NEAR in ${info.contract}.`)\n if (!a.canWithdraw) {\n const unlock = this.contractUnlock(await this.getEpoch(), a.unlockEpoch)\n throw new LiquidStakingError('not-withdrawable', `${near(a.unstaked)} unlocks at epoch ${a.unlockEpoch}.`, { details: { unlock, amount: a.unstaked } })\n }\n if (!LiquidStakingProtocolNear.payable(info, a.unstaked)) {\n 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 } })\n }\n const transactions = [this.tx([fc('withdraw_all', {}, this.gas.withdraw, 0n)])]\n LiquidStakingProtocolNear.assertNotPaused(info, transactions)\n const [{ fee, upfront }, available] = await Promise.all([this.costs(transactions), this.available(me)])\n if (upfront > available) throw new InsufficientFundsError(upfront, available, 'NEAR')\n return { fee, upfront, amount: a.unstaked, transactions }\n }\n\n /** The claim's transaction (`withdraw_all`) and fee; nothing is signed. */\n override async quoteClaimWithdrawals(options: LiquidClaimOptions = {}): Promise<LiquidClaimQuote> {\n return this.planClaim(options)\n }\n\n /** Withdraws the unstaked NEAR (`withdraw_all`) once unlocked and payable. */\n override async claimWithdrawals(options: LiquidClaimOptions = {}): Promise<LiquidClaimResult> {\n return this.send('claimWithdrawals', () => this.planClaim(options), options)\n }\n\n // ── Activity ───────────────────────────────────────────────────────────────\n\n /** Labels LiNEAR-family staking transactions offline; see `activity.ts`. */\n override describeActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const pool = typeof this._config.pool === 'string' ? undefined : this._config.pool\n return describeLiquidNearStakingActivity(tx, ctx, pool ? { contracts: [{ contract: pool.contract, symbol: pool.symbol, ...(pool.name ? { name: pool.name } : {}) }] } : {})\n }\n}\n","import { activityBase, netTransfers, splitNet, type ActivityAsset, type ActivityItem, type ChainTx, type DescribeActivityContext } from '@anywalletkit/core'\nimport { LIQUID_PRESETS, LST_DECIMALS, NEAR_MAINNET, NEAR_TESTNET } from './constants.js'\nimport type { NearNetwork } from './types.js'\n\n// Activity recognition for LiNEAR-family liquid staking: pure and offline.\n//\n// A transaction is this module's when the wallet sent it (`tx.from` is own) and `call.to` is a family\n// contract (a preset for the transaction's network, or one the app configured), with a staking\n// method among `call.programs`. Amounts come from the transfers the history source reported:\n// the attached deposit of `deposit_and_stake`, the token minted or burnt (NEP-141 events), the NEAR\n// paid back by `withdraw*`. An RPC-mapped transaction does not list receipt transfers, so a\n// withdrawal's amount is then read from the contract's own `withdraw` event in the kept outcome.\n// A lone `storage_deposit`, `ft_transfer` or `ft_transfer_call` is left to the generic fallback.\n\n/** Registry name, as `module.json` carries it. */\nexport const MODULE_NAME = '@anywalletkit/protocol-staking-liquid-near'\n\n/** Labels for the preset contracts, as feeds show them (\"Rhea rNEAR liquid staking\"). */\nconst LABELS: Record<keyof typeof LIQUID_PRESETS, string> = { linear: 'LiNEAR', rnear: 'Rhea rNEAR' }\n\nconst NEAR = { symbol: 'NEAR', decimals: 24 }\n\ninterface Known { contract: string; symbol: string; label: string }\n\nfunction knownContracts(network: NearNetwork, extra: ReadonlyArray<{ contract: string; symbol: string; name?: string }>): Known[] {\n const out: Known[] = []\n for (const [key, preset] of Object.entries(LIQUID_PRESETS) as Array<[keyof typeof LIQUID_PRESETS, (typeof LIQUID_PRESETS)[keyof typeof LIQUID_PRESETS]]>) {\n const on = (preset.contracts as Partial<Record<NearNetwork, { contract: string }>>)[network]\n if (on) out.push({ contract: on.contract, symbol: preset.symbol, label: LABELS[key] })\n }\n for (const c of extra) out.push({ contract: c.contract, symbol: c.symbol, label: c.name ?? c.symbol })\n return out\n}\n\n/** NEAR paid out by the contract's `withdraw` event (standards `linear` / `rhea_lst`) in a kept RPC outcome. */\nfunction withdrawnFromLogs(tx: ChainTx, contract: string, me: string): bigint {\n const rpc = (tx.raw as { rpc?: { receipts_outcome?: Array<{ outcome?: { executor_id?: string; logs?: string[] } }> } } | undefined)?.rpc\n let sum = 0n\n for (const r of rpc?.receipts_outcome ?? []) {\n if (r.outcome?.executor_id !== contract) continue\n for (const log of r.outcome.logs ?? []) {\n if (!log.startsWith('EVENT_JSON:')) continue\n try {\n const ev = JSON.parse(log.slice('EVENT_JSON:'.length)) as { event?: string; data?: Array<{ account_id?: string; amount?: string }> }\n if (ev.event !== 'withdraw') continue\n for (const d of ev.data ?? []) if (d.account_id === me && typeof d.amount === 'string' && /^\\d+$/.test(d.amount)) sum += BigInt(d.amount)\n } catch { /* not an event */ }\n }\n }\n return sum\n}\n\n/** Describes a LiNEAR / rNEAR staking transaction for the wallet's feed, or returns null when it is not one. */\nexport function describeLiquidNearStakingActivity(\n tx: ChainTx,\n ctx: DescribeActivityContext,\n options: { contracts?: ReadonlyArray<{ contract: string; symbol: string; name?: string }> } = {},\n): ActivityItem | null {\n const network: NearNetwork | null = tx.chain === NEAR_MAINNET ? 'mainnet' : tx.chain === NEAR_TESTNET ? 'testnet' : null\n const call = tx.call\n if (!network || !call) return null\n const known = knownContracts(network, options.contracts ?? []).find((c) => c.contract === call.to)\n if (!known || !ctx.own.has(tx.from)) return null\n\n const methods = call.programs?.length ? call.programs : [call.method ?? '']\n const has = (...names: string[]) => names.some((n) => methods.includes(n))\n let kind: ActivityItem['kind'], title: string\n if (has('deposit_and_stake')) {\n kind = 'stake'\n title = `Staked NEAR for ${known.symbol}`\n } else if (has('stake', 'stake_all')) {\n kind = 'stake'\n title = `Restaked NEAR for ${known.symbol}`\n } else if (has('unstake', 'unstake_all')) {\n kind = 'unstake'\n title = has('withdraw', 'withdraw_all') ? 'Withdrew and requested unstake' : 'Requested unstake'\n } else if (has('withdraw', 'withdraw_all')) {\n kind = 'claim'\n title = 'Withdrew unstaked NEAR'\n } else return null\n\n const meta = (token: string | null) => (token === null ? NEAR : token === known.contract ? { symbol: known.symbol, decimals: LST_DECIMALS } : undefined)\n const { assetsIn, assetsOut } = splitNet(netTransfers(tx, ctx.own), meta)\n if (kind === 'stake' && !assetsOut.some((a) => a.token === null) && tx.nativeValue > 0n) {\n assetsOut.push({ token: null, amount: tx.nativeValue, ...NEAR } as ActivityAsset)\n }\n if (has('withdraw', 'withdraw_all') && !assetsIn.some((a) => a.token === null)) {\n const paid = withdrawnFromLogs(tx, known.contract, tx.from)\n if (paid > 0n) assetsIn.push({ token: null, amount: paid, ...NEAR } as ActivityAsset)\n }\n return activityBase(tx, kind, title, {\n protocol: MODULE_NAME,\n subtitle: `${known.label} liquid staking`,\n counterparty: call.to,\n assetsIn,\n assetsOut,\n })\n}\n","// Liquid NEAR staking constants: the LiNEAR contract family (LiNEAR and its fork Rhea rNEAR).\n// Contract ids, code hashes and views checked on mainnet / testnet on 2026-11-08 (ft_metadata,\n// get_summary, get_account_details, is_paused, storage_balance_bounds, view_account.code_hash).\n// Meta Pool stNEAR is deliberately not here: it is a different contract family, offered by apps as\n// \"Instant stNEAR via 1Click\" only.\n\nimport type { NearNetwork } from './types.js'\n\nexport const NEAR_MAINNET = 'near:mainnet'\nexport const NEAR_TESTNET = 'near:testnet'\n\nexport const YOCTO_PER_NEAR = 10n ** 24n\nexport const TGAS = 10n ** 12n\n\n/** LST decimals for the whole family (LINEAR, rNEAR). */\nexport const LST_DECIMALS = 24\n/** `ft_price` scale: yoctoNEAR per 1 whole token (10^24 = 1 NEAR per token). */\nexport const PRICE_SCALE = 10n ** 24n\n\n/** Epochs an unstake waits at least (the contract may add more: big amounts, after the epoch's settlement). */\nexport const MIN_EPOCHS_TO_UNLOCK = 4n\n/** Block heights per epoch, mainnet and testnet. */\nexport const EPOCH_LENGTH = 43_200n\n/** Fallback epoch duration when the chain cannot be read: ~6.9 h (measured 6.9–7.1 h on mainnet in November 2026). */\nexport const TYPICAL_EPOCH_MS = 24_840_000\n/**\n * Unstaked balances at or below this many yoctoNEAR are treated as empty. `deposit_and_stake` charges\n * the share price rounded down and leaves the remainder (a yocto or two) unstaked; offering to\n * withdraw it would cost more gas than it is worth.\n */\nexport const UNSTAKED_DUST = 1_000_000n\n/**\n * Liquid NEAR the contract keeps for itself: a withdrawal needs contract balance − 1 NEAR ≥ amount\n * (assert_can_withdraw). The runtime also keeps the contract's storage cost (storage_usage × 10^19:\n * ~52 NEAR for rNEAR, ~133 NEAR for LiNEAR), so what it can pay is balance − max(1 NEAR, storage).\n */\nexport const CONTRACT_MIN_RESERVE_BALANCE = YOCTO_PER_NEAR\n/**\n * NEP-145 registration, the same on every family contract (storage_balance_bounds.min, 0.00125 NEAR).\n * `deposit_and_stake` registers an unregistered staker itself; rNEAR keeps this much of that first\n * deposit for it (it stakes `amount − min`), LiNEAR stakes the whole amount. The module reads the\n * live bound; this is the value on 2026-11-08.\n */\nexport const STORAGE_DEPOSIT = 1_250_000_000_000_000_000_000n\n\n/**\n * NEAR left on the account by `stake`: 0.02 NEAR. `stake` never leaves less than the upfront gas of\n * one unstake (about 0.035 NEAR at today's prices, see fees.ts), so the stake can always be left.\n */\nexport const DEFAULT_RESERVE = 2n * 10n ** 22n\n/** Smallest stake the module sends: 0.001 NEAR, staked after any storage fee (an rNEAR first stake needs 0.00225 NEAR). */\nexport const MIN_STAKE = 10n ** 21n\n\n/**\n * Pause keys each call checks on a contract with per-feature pauses (rNEAR's near-plugins Pausable,\n * read with `pa_all_paused`): the call fails while any of its keys, or 'ALL', is paused. LiNEAR has\n * one `is_paused` flag for everything.\n */\nexport const PAUSE_KEYS: Readonly<Record<string, readonly string[]>> = {\n deposit_and_stake: ['internal_deposit', 'internal_stake'],\n unstake: ['internal_unstake'],\n unstake_all: ['internal_unstake'],\n withdraw_all: ['internal_withdraw'],\n}\n\n/**\n * Prepaid gas per call. All of it is bought upfront at min_gas_purchase_price (the unburnt part is\n * refunded), so it is kept near what the calls use. Burnt on mainnet (whole transaction):\n * deposit_and_stake ~3.1–3.5 Tgas on both contracts (it stakes nothing itself: the operator bot does;\n * an rNEAR stake with 30 Tgas prepaid succeeded), unstake_all 3.5, withdraw_all 3.4 (rNEAR) to ~11\n * (LiNEAR). None of them makes a cross-contract call but the payout transfer.\n */\nexport const DEFAULT_GAS = {\n stake: 30n * TGAS,\n unstake: 30n * TGAS,\n withdraw: 30n * TGAS,\n} as const\n\n/** Gas price margin of fee estimates (+10 %, as wallet-near's own estimate), so a quoted fee also passes as `maxFee`. */\nexport const GAS_PRICE_MARGIN_NUM = 11n\nexport const GAS_PRICE_MARGIN_DEN = 10n\n/**\n * Price per prepaid gas unit when the node cannot report `runtime_config.min_gas_purchase_price`:\n * the mainnet value (protocol 88, Nov 2026), so balance checks fail toward needing more.\n */\nexport const MIN_GAS_PURCHASE_PRICE_FALLBACK = 10n ** 9n\n\n/** Epochs the APR looks back over by default (~7 days at ~6.9 h per epoch). */\nexport const DEFAULT_APR_WINDOW_EPOCHS = 24\n\n/** Archival RPC for the APR's past price (regular nodes keep ~5 epochs). */\nexport const DEFAULT_ARCHIVAL_RPC: Record<NearNetwork, string> = {\n mainnet: 'https://archival-rpc.mainnet.fastnear.com',\n testnet: 'https://archival-rpc.testnet.fastnear.com',\n}\n\n/** A family contract the module knows: account id per network and the code hashes accepted for writes. */\nexport interface LiquidPreset {\n symbol: string\n name: string\n /** `deposit_and_stake` keeps storage_balance_bounds.min of an unregistered account's first deposit. */\n firstStakePaysStorage: boolean\n /** Per-feature pauses (near-plugins Pausable, read with `pa_all_paused`) beside `is_paused`. */\n featurePauses: boolean\n contracts: Partial<Record<NearNetwork, { contract: string; codeHashes: readonly string[] }>>\n}\n\n/** Built-in pools. Writes refuse a contract whose live code_hash is not pinned here (or in the app's config). */\nexport const LIQUID_PRESETS = {\n linear: {\n symbol: 'LINEAR',\n name: 'LiNEAR',\n firstStakePaysStorage: false, // stake.rs: internal_deposit(attached); an unregistered implicit account staked 0.266 NEAR whole (fixture)\n featurePauses: false, // one `paused` flag (is_paused); pa_all_paused is MethodNotFound on mainnet\n contracts: {\n mainnet: { contract: 'linear-protocol.near', codeHashes: ['5LiDVDd1gh7ofVNbiA9VXrWwkv2m8tw46jZqYeuoC3SG'] },\n testnet: { contract: 'linear-protocol.testnet', codeHashes: ['8Bby4ofnYGtudd3PinKZ1KyvmUKJVyxmfC99ZccRDVDv'] },\n },\n },\n rnear: {\n symbol: 'rNEAR',\n name: 'Rhea Liquid Near Staking Token',\n firstStakePaysStorage: true, // stake_pool_itf.rs: internal_deposit(amount − storage_balance_bounds.min) when storage_balance_of is null\n featurePauses: true, // #[pause] on internal_deposit / internal_stake / internal_unstake / internal_withdraw; is_paused reads only 'ALL'\n contracts: {\n mainnet: { contract: 'lst.rhealab.near', codeHashes: ['EPLT4C61pkVYf5Km6dC4X9x5PMo6rfBwuEwo7vgKpmuv'] }, // v1.0.2\n },\n },\n} as const satisfies Record<string, LiquidPreset>\n\n/** Preset names. */\nexport type LiquidPresetName = keyof typeof LIQUID_PRESETS\n","import { NetworkError, bigintToNumber } from '@anywalletkit/core'\nimport { NearRpcError, type NearRpc } from '@anywalletkit/wallet-near'\nimport { EPOCH_LENGTH, TYPICAL_EPOCH_MS } from './constants.js'\nimport type { NearEpoch } from './types.js'\n\n// Epoch clock from the chain: `validators` (epoch_height, epoch_start_height), `block` (latest final\n// height and timestamp) and the first blocks of this and the previous epoch (measured duration).\n\n/** Heights tried after a skipped one before giving up (skipped heights are rare and short). */\nconst SKIP_TRIES = 10\n\n/** One block header: height and unix ms. */\nexport interface BlockTime { height: bigint; ms: number }\n\n/** The epoch numbers the validators answer carries. */\nexport interface EpochNumbers { epochHeight: bigint; epochStartHeight: bigint }\n\nfunction blockTimeOf(raw: unknown): BlockTime {\n const h = (raw as { header?: Record<string, unknown> } | null)?.header\n if (!h || typeof h.height !== 'number') throw new NetworkError('block: no header in the response')\n // timestamp_nanosec is exact; `timestamp` is a JSON number that has already lost precision.\n let ms: number\n if (typeof h.timestamp_nanosec === 'string' && /^\\d+$/.test(h.timestamp_nanosec)) ms = bigintToNumber(BigInt(h.timestamp_nanosec) / 1_000_000n)\n else if (typeof h.timestamp === 'number') ms = Math.floor(h.timestamp / 1e6)\n else throw new NetworkError('block: no timestamp in the header')\n return { height: BigInt(h.height), ms }\n}\n\n/** The latest final block. */\nexport async function finalBlock(rpc: NearRpc): Promise<BlockTime> {\n return blockTimeOf(await rpc.fetch('block', { finality: 'final' }))\n}\n\n/** The block at `height`, or the first produced one after it when that height was skipped. */\nexport async function blockAt(rpc: NearRpc, height: bigint): Promise<BlockTime> {\n let last: unknown\n for (let i = 0n; i <= BigInt(SKIP_TRIES); i++) {\n try {\n return blockTimeOf(await rpc.fetch('block', { block_id: bigintToNumber(height + i) }))\n } catch (e) {\n // Only a skipped height moves on; a pruned block or a transport failure is the caller's to handle.\n if (!(e instanceof NearRpcError) || !/UNKNOWN_BLOCK/i.test(e.errorName ?? '')) throw e\n last = e\n }\n }\n throw last\n}\n\n/** `epoch_height` and `epoch_start_height` of the current epoch (one `validators` call). */\nexport async function readEpochNumbers(rpc: NearRpc): Promise<EpochNumbers> {\n const r = (await rpc.fetch('validators', [null])) as { epoch_height?: unknown; epoch_start_height?: unknown } | null\n if (typeof r?.epoch_height !== 'number' || typeof r.epoch_start_height !== 'number') throw new NetworkError('validators: no epoch_height / epoch_start_height in the response')\n return { epochHeight: BigInt(r.epoch_height), epochStartHeight: BigInt(r.epoch_start_height) }\n}\n\n/** Options of {@link readEpoch}: reuse the caller's cached epoch numbers and block times. */\nexport interface ReadEpochOptions {\n numbers?: () => Promise<EpochNumbers>\n /** Timestamps of blocks already read, by height (block times never change). */\n blockTimes?: Map<bigint, number>\n}\n\n/** Reads the epoch clock. Falls back to {@link TYPICAL_EPOCH_MS} only when the epoch start blocks cannot be read. */\nexport async function readEpoch(rpc: NearRpc, options: ReadEpochOptions = {}): Promise<NearEpoch> {\n const [numbers, latest] = await Promise.all([(options.numbers ?? (() => readEpochNumbers(rpc)))(), finalBlock(rpc)])\n const times = options.blockTimes ?? new Map<bigint, number>()\n const timeAt = async (height: bigint): Promise<number | null> => {\n const known = times.get(height)\n if (known !== undefined) return known\n try {\n const ms = (await blockAt(rpc, height)).ms\n times.set(height, ms)\n return ms\n } catch {\n return null // a node that pruned it: estimated below\n }\n }\n const length = EPOCH_LENGTH\n const startBlock = numbers.epochStartHeight\n const [started, prevStarted] = await Promise.all([timeAt(startBlock), timeAt(startBlock - length)])\n const epochMs = started !== null && prevStarted !== null && started > prevStarted ? started - prevStarted : TYPICAL_EPOCH_MS\n const msPerBlock = epochMs / bigintToNumber(length)\n const into = latest.height > startBlock ? latest.height - startBlock : 0n\n const startedAt = started ?? Math.round(latest.ms - bigintToNumber(into) * msPerBlock)\n const blocksLeft = startBlock + length > latest.height ? startBlock + length - latest.height : 0n\n return {\n height: numbers.epochHeight,\n startBlock,\n length,\n block: latest.height,\n blocksLeft,\n startedAt,\n epochMs,\n endsAt: Math.round(latest.ms + bigintToNumber(blocksLeft) * msPerBlock),\n }\n}\n\n/**\n * Unix ms estimate of the start of epoch `height`. Past and current epochs count from `startedAt`;\n * later ones from `endsAt` (which follows the current epoch's real progress), one `epochMs` each.\n */\nexport function epochStartsAt(epoch: NearEpoch, height: bigint): number {\n if (height <= epoch.height) return epoch.startedAt - bigintToNumber(epoch.height - height) * epoch.epochMs\n return epoch.endsAt + bigintToNumber(height - epoch.height - 1n) * epoch.epochMs\n}\n","/** Why a liquid staking call was refused before anything was signed. */\nexport type LiquidStakingErrorCode =\n | 'wrong-chain' // the account is not on the configured NEAR network\n | 'no-provider'\n | 'unsupported-network' // the preset has no contract on this network (rNEAR on testnet)\n | 'invalid-amount'\n | 'below-minimum'\n | 'unknown-contract-code' // the contract's live code_hash is not pinned\n | 'contract-paused' // is_paused true or missing, or a feature the plan calls paused (pa_all_paused)\n | 'exceeds-balance' // unstake larger than the token balance\n | 'nothing-staked'\n | 'relock-refused' // see LiquidUnstakeOptions.allowRelock\n | 'timer-reset-refused' // see LiquidUnstakeOptions.allowTimerReset\n | 'max-fee-exceeded' // the fresh plan's fee is above the write's `maxFee`\n | 'not-withdrawable' // unlock epoch not reached; see `details.unlock`\n | 'awaiting-liquidity' // unlocked, but the contract cannot pay yet\n | 'nothing-to-claim'\n | 'unknown-request'\n | 'quote-changed'\n | 'invalid-config'\n\n/** A refusal with a code an app can branch on and a sentence it can show. */\nexport class LiquidStakingError extends Error {\n readonly code: LiquidStakingErrorCode\n readonly details: Record<string, unknown> | undefined\n constructor(code: LiquidStakingErrorCode, message: string, extra: { details?: Record<string, unknown>; cause?: unknown } = {}) {\n super(message, extra.cause !== undefined ? { cause: extra.cause } : undefined)\n this.name = 'LiquidStakingError'\n this.code = code\n this.details = extra.details\n }\n}\n","import { WalletAccountReadOnlyNear, type NearRpc, type NearTransaction } from '@anywalletkit/wallet-near'\nimport { GAS_PRICE_MARGIN_DEN, GAS_PRICE_MARGIN_NUM, MIN_GAS_PURCHASE_PRICE_FALLBACK } from './constants.js'\n\n// NEAR charges a transaction in two parts. When the node accepts it, the signer pays the conversion\n// gas at the gas price and BUYS all prepaid gas upfront at max(gas price, min_gas_purchase_price)\n// (protocol config; 10^9 on mainnet since protocol 88, ten times the 10^8 gas price). What the\n// receipts do not burn comes back a few blocks later. So the balance a transaction needs is\n// deposit + `upfront`, while what it finally costs is at most `fee`.\n\n/** Gas prices behind {@link GasCost}, yoctoNEAR per gas. */\nexport interface GasPrices {\n /** The current gas price + 10 %: the margin wallet-near's own estimate uses. */\n gasPrice: bigint\n /** What the node charges per prepaid gas unit when it accepts a transaction. */\n purchasePrice: bigint\n}\n\n/** What a plan costs in NEAR, yoctoNEAR. */\nexport interface GasCost {\n /** Upper bound of the network fee: every gas unit burnt at {@link GasPrices.gasPrice}. Works as `maxFee`. */\n fee: bigint\n /** NEAR held back from the account when the node accepts the transactions (deposits excluded); the unburnt part is refunded. */\n upfront: bigint\n}\n\n/** How long the protocol config is reused: it changes only with a protocol upgrade. */\nconst PROTOCOL_CONFIG_TTL_MS = 10 * 60_000\n/** How long a failed protocol-config read is answered by the fallback before it is tried again. */\nconst FALLBACK_TTL_MS = 60_000\n\n/** Reads the gas price fresh and `min_gas_purchase_price` once per {@link PROTOCOL_CONFIG_TTL_MS}. */\nexport class GasPricer {\n private minPurchase: { at: number; ttl: number; value: Promise<bigint> } | undefined\n\n constructor(private readonly rpc: () => NearRpc) {}\n\n async prices(): Promise<GasPrices> {\n const [price, min] = await Promise.all([this.rpc().gasPrice(), this.minPurchasePrice()])\n const gasPrice = (price * GAS_PRICE_MARGIN_NUM) / GAS_PRICE_MARGIN_DEN\n return { gasPrice, purchasePrice: gasPrice > min ? gasPrice : min }\n }\n\n /** `runtime_config.min_gas_purchase_price`; the mainnet value when the node cannot say (fails toward a larger balance check). */\n private minPurchasePrice(): Promise<bigint> {\n const hit = this.minPurchase\n if (hit && Date.now() - hit.at < hit.ttl) return hit.value\n const entry = { at: Date.now(), ttl: PROTOCOL_CONFIG_TTL_MS, value: Promise.resolve(MIN_GAS_PURCHASE_PRICE_FALLBACK) }\n entry.value = this.rpc().fetch('EXPERIMENTAL_protocol_config', { finality: 'final' }).then((r) => {\n const v = (r as { runtime_config?: { min_gas_purchase_price?: unknown } } | null)?.runtime_config?.min_gas_purchase_price\n if (typeof v === 'string' && /^\\d{1,30}$/.test(v)) return BigInt(v)\n entry.ttl = FALLBACK_TTL_MS\n return MIN_GAS_PURCHASE_PRICE_FALLBACK\n }, () => {\n entry.ttl = FALLBACK_TTL_MS\n return MIN_GAS_PURCHASE_PRICE_FALLBACK\n })\n this.minPurchase = entry\n return entry.value\n }\n}\n\n/** Gas of the transactions as wallet-near counts it: conversion + prepaid, per action. */\nexport const gasOf = (txs: readonly NearTransaction[]): bigint =>\n txs.reduce((s, tx) => s + WalletAccountReadOnlyNear.gasOf(tx.actions, false), 0n)\n\n/** Fee and upfront charge of `txs` at `prices`. */\nexport function costOf(txs: readonly NearTransaction[], prices: GasPrices): GasCost {\n const gas = gasOf(txs)\n return { fee: gas * prices.gasPrice, upfront: gas * prices.purchasePrice }\n}\n","import { bigintToNumber } from '@anywalletkit/core'\nimport { PRICE_SCALE } from './constants.js'\n\n// Share math of the LiNEAR contract family, in the contract's own rounding (internal.rs), and the\n// price-based APR. Everything is bigint; floats appear only in the final percent.\n\n/** Tokens `deposit_and_stake(amount)` mints: amount × totalShares / totalStaked, rounded down. */\nexport function sharesForNear(amount: bigint, totals: { totalShares: bigint; totalStaked: bigint }): bigint {\n if (totals.totalStaked <= 0n) return 0n\n return (amount * totals.totalShares) / totals.totalStaked\n}\n\n/**\n * NEAR that `shares` tokens are worth: shares × totalStaked / totalShares, rounded down. Passing this\n * to `unstake(amount)` burns at most `shares` (the contract rounds the burnt shares up from it).\n */\nexport function nearForShares(shares: bigint, totals: { totalShares: bigint; totalStaked: bigint }): bigint {\n if (totals.totalShares <= 0n) return 0n\n return (shares * totals.totalStaked) / totals.totalShares\n}\n\n/** `shares` valued at `price` (yoctoNEAR per whole token, {@link PRICE_SCALE} = 1:1), rounded down. */\nexport function valueAtPrice(shares: bigint, price: bigint): bigint {\n return (shares * price) / PRICE_SCALE\n}\n\nconst YEAR_MS = 31_557_600_000n // 365.25 days\nconst FIXED = 10n ** 12n\n\n/**\n * Annualized price growth in percent: (p1 / p0 − 1) × year / Δt × 100, simple (not compounded),\n * computed in 10^12 fixed point. 0 when the inputs cannot give a figure (no time passed, no price).\n */\nexport function aprFromPrices(p0: bigint, p1: bigint, t0Ms: number, t1Ms: number): number {\n const dt = BigInt(Math.round(t1Ms - t0Ms))\n if (p0 <= 0n || p1 <= 0n || dt <= 0n) return 0\n const scaled = ((p1 - p0) * YEAR_MS * 100n * FIXED) / (p0 * dt)\n return bigintToNumber(scaled) / bigintToNumber(FIXED)\n}\n","import { sha256 } from '@noble/hashes/sha2.js'\nimport { isValidAccountId } from '@anywalletkit/wallet-near'\nimport { LIQUID_PRESETS, type LiquidPreset, type LiquidPresetName } from './constants.js'\nimport { LiquidStakingError } from './errors.js'\nimport type { LiquidPoolConfig, NearNetwork } from './types.js'\n\n/** A pool resolved for one network. */\nexport interface ResolvedLiquidPool {\n contract: string\n symbol: string\n name: string\n codeHashes: readonly string[]\n /** See {@link LiquidPoolConfig.firstStakePaysStorage}. */\n firstStakePaysStorage: boolean\n /** `pa_all_paused` is read (rNEAR, and any custom contract: one without the method has no per-feature pause). */\n featurePauses: boolean\n preset: LiquidPresetName | null\n}\n\n/** Validates a custom pool config (account id, symbol, at least one pinned code hash). */\nexport function validatePoolConfig(pool: LiquidPresetName | LiquidPoolConfig): void {\n if (typeof pool === 'string') {\n 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.`)\n return\n }\n if (!pool || typeof pool !== 'object' || typeof pool.contract !== 'string' || !isValidAccountId(pool.contract)) throw new LiquidStakingError('invalid-config', 'pool.contract must be a NEAR account id.')\n if (typeof pool.symbol !== 'string' || pool.symbol.length === 0) throw new LiquidStakingError('invalid-config', 'pool.symbol is required.')\n if (!Array.isArray(pool.codeHashes) || pool.codeHashes.length === 0 || !pool.codeHashes.every((h) => typeof h === 'string' && h.length > 0)) {\n throw new LiquidStakingError('invalid-config', 'pool.codeHashes must pin at least one code hash.')\n }\n if (pool.firstStakePaysStorage !== undefined && typeof pool.firstStakePaysStorage !== 'boolean') throw new LiquidStakingError('invalid-config', 'pool.firstStakePaysStorage must be a boolean.')\n}\n\n/** The contract, symbol and pinned code hashes of a pool on `network`. */\nexport function resolvePool(pool: LiquidPresetName | LiquidPoolConfig, network: NearNetwork): ResolvedLiquidPool {\n if (typeof pool !== 'string') {\n // A config for a preset's own contract (re-pinned after an upgrade) keeps that preset's storage behaviour unless it says otherwise.\n const known = (Object.values(LIQUID_PRESETS) as LiquidPreset[]).find((p) => Object.values(p.contracts).some((c) => c?.contract === pool.contract))\n const firstStakePaysStorage = pool.firstStakePaysStorage ?? known?.firstStakePaysStorage ?? true\n return { contract: pool.contract, symbol: pool.symbol, name: pool.name ?? pool.symbol, codeHashes: pool.codeHashes, firstStakePaysStorage, featurePauses: true, preset: null }\n }\n const preset = LIQUID_PRESETS[pool]\n const on = (preset.contracts as Partial<Record<NearNetwork, { contract: string; codeHashes: readonly string[] }>>)[network]\n if (!on) throw new LiquidStakingError('unsupported-network', `${preset.name} has no contract on NEAR ${network}.`)\n return { contract: on.contract, symbol: preset.symbol, name: preset.name, codeHashes: on.codeHashes, firstStakePaysStorage: preset.firstStakePaysStorage, featurePauses: preset.featurePauses, preset: pool }\n}\n\n/** Stable request id of the account's unstaked balance in a contract: first 8 bytes of sha256(contract) as a u64. */\nexport function poolRequestId(contract: string): bigint {\n let id = 0n\n for (const b of sha256(new TextEncoder().encode(contract)).subarray(0, 8)) id = (id << 8n) | BigInt(b)\n return id\n}\n","import type { IWalletAccount, IWalletAccountReadOnly } from '@anywalletkit/core'\nimport { NearRpc, createClient, type NearFetch, type NearProvider } from '@anywalletkit/wallet-near'\n\n/**\n * The read client: `provider` from the config, else the transport of a wallet-near account\n * (`_client`, or its configured `provider`). Undefined when neither exists; reads then refuse with\n * 'no-provider'. External-signer accounts (wallet-selector adapters) have none: pass `provider`.\n */\nexport function resolveRpc(\n account: IWalletAccountReadOnly | IWalletAccount,\n config: { provider?: NearProvider | NearProvider[]; timeoutMs?: number },\n): NearRpc | undefined {\n if (config.provider !== undefined) {\n const fetch = createClient({ provider: config.provider, ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}) })\n return fetch ? new NearRpc(fetch) : undefined\n }\n const own = account as unknown as { _client?: NearFetch; _config?: { provider?: NearProvider | NearProvider[]; timeoutMs?: number } }\n if (typeof own._client === 'function') return new NearRpc(own._client)\n if (own._config?.provider !== undefined) {\n const fetch = createClient({ provider: own._config.provider, ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}) })\n return fetch ? new NearRpc(fetch) : undefined\n }\n return undefined\n}\n","import type { IWalletAccount, IWalletAccountReadOnly } from '@anywalletkit/core'\nimport type { NearAction, NearTransaction } from '@anywalletkit/wallet-near'\nimport type { NearTransactionsSender } from './types.js'\n\n/** True when the account can send several transactions with one approval. */\nexport function canSendBatch(account: IWalletAccountReadOnly | IWalletAccount): account is IWalletAccount & NearTransactionsSender {\n return typeof (account as Partial<NearTransactionsSender>).sendTransactions === 'function'\n}\n\nconst canonicalArgs = (args: unknown): unknown =>\n args instanceof Uint8Array ? { bytes: Array.from(args) } : typeof args === 'string' ? { text: args } : args\n\nconst canonicalAction = (a: NearAction): unknown => {\n if ('functionCall' in a) {\n const f = a.functionCall\n return { functionCall: { methodName: f.methodName, args: canonicalArgs(f.args), gas: String(f.gas ?? 0n), deposit: String(f.deposit ?? 0n) } }\n }\n if ('transfer' in a) return { transfer: { deposit: String(a.transfer.deposit) } }\n return { other: Object.keys(a)[0] }\n}\n\n/** Sorted-key JSON, so argument key order never makes two equal plans differ. */\nconst stable = (v: unknown): string => {\n if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`\n if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`\n return JSON.stringify(typeof v === 'bigint' ? String(v) : v)\n}\n\n/**\n * Same receivers, same actions, same order, same args, gas and deposits. Only function calls and\n * transfers are compared field by field; any other action kind never matches (the module builds none).\n */\nexport function sameTransactions(a: readonly NearTransaction[], b: readonly NearTransaction[]): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n const x = a[i]!, y = b[i]!\n if (x.receiverId !== y.receiverId || x.actions.length !== y.actions.length) return false\n for (let j = 0; j < x.actions.length; j++) {\n const ca = canonicalAction(x.actions[j]!), cb = canonicalAction(y.actions[j]!)\n if ((ca as { other?: unknown }).other !== undefined || stable(ca) !== stable(cb)) return false\n }\n }\n return true\n}\n\n/** A function-call action as the module builds them: plain JSON args, gas and deposit always set. */\nexport function fc(methodName: string, args: Record<string, unknown>, gas: bigint, deposit: bigint): NearAction {\n return { functionCall: { methodName, args, gas, deposit } }\n}\n\n/** The only methods the module ever calls on a family contract. */\nexport const LIQUID_WRITE_METHODS: readonly string[] = ['deposit_and_stake', 'unstake', 'unstake_all', 'withdraw_all']\n\n/**\n * Throws unless every transaction goes to `contract` and holds only function calls to\n * {@link LIQUID_WRITE_METHODS}. Runs on every plan before it is returned or sent. In particular it\n * refuses `ft_transfer` / `ft_transfer_call` to the contract: it has no `ft_on_transfer`, so tokens\n * (or \"staking by transfer\") sent that way are lost.\n */\nexport function assertLiquidPlan(transactions: readonly NearTransaction[], contract: string): void {\n for (const tx of transactions) {\n if (tx.receiverId !== contract) throw new Error(`Refusing a transaction to ${tx.receiverId}: liquid staking only calls ${contract}.`)\n if (tx.signerId !== undefined) throw new Error('Refusing a transaction with a signerId: the account signs as itself.')\n for (const a of tx.actions) {\n const method = 'functionCall' in a ? a.functionCall.methodName : null\n if (method === null) throw new Error(`Refusing a ${Object.keys(a)[0]} action: liquid staking sends function calls only.`)\n 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)' : ''}.`)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAGO;AACP,IAAAC,sBAEO;;;ACNP,kBAAwI;;;ACQjI,IAAM,eAAe;AACrB,IAAM,eAAe;AAErB,IAAM,iBAAiB,OAAO;AAC9B,IAAM,OAAO,OAAO;AAGpB,IAAM,eAAe;AAErB,IAAM,cAAc,OAAO;AAG3B,IAAM,uBAAuB;AAE7B,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAMzB,IAAM,gBAAgB;AAMtB,IAAM,+BAA+B;AAOrC,IAAM,kBAAkB;AAMxB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