@arca-network/sdk 1.8.0 → 1.10.0

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/arca.js CHANGED
@@ -186,18 +186,28 @@ function isIdFormat(value) {
186
186
  }
187
187
  /**
188
188
  * Pre-computed function selectors (first 4 bytes of keccak256 of the signature)
189
- * for the ArcaCustodyPool contract. These are fixed since the contract ABI is known.
189
+ * for the v4 ArcaCustodyKernel contract. These are fixed since the contract ABI
190
+ * is known, and are pinned by a keccak-derived selector test.
190
191
  *
191
- * Verified against: `cast sig "lockBoundary(bytes32)"` etc. from Foundry.
192
+ * Verified against: `cast sig "claimRecovery(bytes32)"` etc. from Foundry.
193
+ *
194
+ * NOTE: the pre-reset v1 pool ABI (`withdraw`, `assignRecoveryKey`,
195
+ * `setTimeLock`, `cancelPendingExit`, `recoveryWithdrawAccount`) no longer
196
+ * exists on-chain — those builders were removed. The v4 sovereign-exit path is
197
+ * `claimRecovery` → wait `RECOVERY_WINDOW` (7 days) → `recoveryWithdraw`, with
198
+ * `cancelRecovery` to abort a false-alarm claim and `setCosignKey` to delegate
199
+ * or rotate the day-to-day co-sign key. `lockBoundary` / `unlockBoundary` are
200
+ * the operator/coordinator operational freeze (kept for coordinator tooling;
201
+ * they are NOT the sovereign recovery path — the kernel gates them on the
202
+ * boundary coordinator, not the recovery key).
192
203
  */
193
204
  const CUSTODY_SELECTORS = {
194
205
  'lockBoundary(bytes32)': '0x67f82a1d',
195
206
  'unlockBoundary(bytes32)': '0x83a2f7cd',
196
- 'withdraw(bytes32)': '0x8e19899e',
197
- 'assignRecoveryKey(bytes32,address)': '0xf5b7e3a6',
198
- 'setTimeLock(bytes32,uint256)': '0x3e41d187',
199
- 'cancelPendingExit(bytes32)': '0x5e50fbe8',
200
- 'recoveryWithdrawAccount(bytes32)': '0xba7b2fbd',
207
+ 'claimRecovery(bytes32)': '0x9180c0a6',
208
+ 'cancelRecovery(bytes32)': '0x631fec7f',
209
+ 'recoveryWithdraw(bytes32)': '0x28bcced4',
210
+ 'setCosignKey(bytes32,address)': '0xbc919ffc',
201
211
  };
202
212
  /**
203
213
  * Minimal ABI encoder for custody contract calls.
@@ -476,10 +486,21 @@ class Arca {
476
486
  // At the fill instant, mid == price (we're projecting the moment
477
487
  // the order fills). The merged position's uPnL contribution is
478
488
  // invariant to the new fill, so equityPost only changes by the fee.
479
- const perUnit = marginAvail / merged.size;
480
- const liq = merged.side === 'long' ? price - perUnit : price + perUnit;
481
- if (liq > 0) {
482
- estimatedLiquidationPrice = fmt(liq);
489
+ //
490
+ // As the mark moves, equity falls at `size` per unit while this
491
+ // position's own maintenance requirement falls at `mmr * size`
492
+ // (MM = mmr * size * mark), so the gap closes at only
493
+ // `size * (1 -/+ mmr)` per unit. Omitting that term reads
494
+ // optimistic for shorts. Mirrors `crossMarginLiqPrice` in
495
+ // sim-exchange's account.go.
496
+ const mmrEff = mergedNotional > 0 ? mmMerged / mergedNotional : 0;
497
+ const sensitivity = merged.side === 'long' ? 1 - mmrEff : 1 + mmrEff;
498
+ if (sensitivity > 0) {
499
+ const perUnit = marginAvail / (merged.size * sensitivity);
500
+ const liq = merged.side === 'long' ? price - perUnit : price + perUnit;
501
+ if (liq > 0) {
502
+ estimatedLiquidationPrice = fmt(liq);
503
+ }
483
504
  }
484
505
  }
485
506
  }
@@ -750,6 +771,18 @@ class Arca {
750
771
  * are transferred to that Arca before deletion.
751
772
  *
752
773
  * If the object is already deleted, returns the existing state.
774
+ *
775
+ * Authorization is value-aware: deleting an object that holds no value
776
+ * (zero settled balance, no venue equity, no open positions) never
777
+ * requires browser step-up — on any realm type, including with API keys.
778
+ * Deleting a funded object on a production realm requires step-up, and
779
+ * if the object's isolation boundary is co-sign armed the request is
780
+ * refused with `412 COSIGN_DRAIN_REQUIRED` (an {@link ArcaError} with
781
+ * that code): drain the object via a co-signed withdrawal first, then
782
+ * delete the then-empty object. Treat `COSIGN_DRAIN_REQUIRED` as
783
+ * blocked-pending-user, not retryable. Use
784
+ * `GET /objects/{id}/deletion-readiness` (`authorization` field) to
785
+ * determine the path without probing.
753
786
  */
754
787
  ensureDeleted(opts) {
755
788
  return this.op(() => this.client.post('/objects/delete', {
@@ -1988,17 +2021,32 @@ class Arca {
1988
2021
  return result;
1989
2022
  }
1990
2023
  /**
1991
- * Open a position and attach reduce-only TP/SL triggers in **one atomic
1992
- * batch** — Hyperliquid `normalTpsl` parity. The entry and its triggers are
1993
- * submitted as a single signed batch to one operation: the whole bracket
1994
- * validates and commits at the venue, or none of it does. The trigger legs
1995
- * **arm only when the entry fills**, and the venue links them with a shared
1996
- * one-cancels-the-other group so a fill on one cancels its sibling.
2024
+ * Open a position and attach reduce-only TP/SL triggers as a **linked
2025
+ * `normalTpsl` bracket** — Hyperliquid parity. The entry and its triggers are
2026
+ * submitted as a single signed batch to one operation; one signature links
2027
+ * the legs. The trigger legs **arm only when the entry fills**, and the venue
2028
+ * links them with a shared one-cancels-the-other group so a fill on one
2029
+ * cancels its sibling.
2030
+ *
2031
+ * **`normalTpsl` is a fixed-size parent-order bracket.** Each TP/SL child
2032
+ * defaults to the entry's size (a normalTpsl child is a fixed-size leg of the
2033
+ * parent order, NOT a whole-position trigger). Pass `takeProfitSz` /
2034
+ * `stopLossSz` for a smaller partial-close child. For a **whole-position**
2035
+ * TP/SL that sizes to the entire live position (Hyperliquid `positionTpsl`),
2036
+ * use {@link setStopLoss} / {@link setTakeProfit} / {@link setPositionTpsl}
2037
+ * instead — that is a separate trigger-only model with no entry leg and is
2038
+ * not accepted here.
1997
2039
  *
1998
2040
  * Returns one {@link OrderHandle} per leg (`entry`, `takeProfit?`,
1999
2041
  * `stopLoss?`), all backed by the single bracket operation. At least one of
2000
- * `takeProfitPx` / `stopLossPx` is required. The TP/SL legs are unsized
2001
- * (`sizeToMax`) reduce-only triggers that close the entire position.
2042
+ * `takeProfitPx` / `stopLossPx` is required. Until the entry fills, a TP/SL
2043
+ * child is not yet a live venue order (it has no venue order id — it is
2044
+ * addressable only by its cloid); its {@link OrderHandle} matches fills by
2045
+ * cloid, and cancelling it before activation cancels the parent bracket.
2046
+ *
2047
+ * A single signature links the legs, but this is **not** a globally
2048
+ * all-or-none batch: Hyperliquid only guarantees whole-payload rejection for
2049
+ * pre-validation failures.
2002
2050
  *
2003
2051
  * @example
2004
2052
  * ```ts
@@ -2029,17 +2077,17 @@ class Arca {
2029
2077
  const closingSide = opts.side === 'buy' ? 'sell' : 'buy';
2030
2078
  const tif = opts.timeInForce ?? 'GTC';
2031
2079
  // Build orders[] in request order: entry first, then the trigger legs.
2080
+ // A `normalTpsl` child is a FIXED-SIZE leg of the parent order: it defaults
2081
+ // to the entry's size. An explicit `sz` is a smaller partial-close child.
2082
+ // We never send `sizeToMax` here — that is the whole-position `positionTpsl`
2083
+ // model, which this endpoint rejects (use setStopLoss / setTakeProfit).
2032
2084
  const trigger = (tpsl, triggerPx, sz) => {
2033
- const sized = sz != null && sz !== '';
2085
+ const childSize = sz != null && sz !== '' ? sz : opts.size;
2034
2086
  return {
2035
2087
  market: opts.market,
2036
2088
  side: closingSide,
2037
2089
  orderType: triggersAreMarket ? 'MARKET' : 'LIMIT',
2038
- // Sized: a partial reduce-only close of exactly `sz` (reduce-only caps
2039
- // it at the live position). Unsized: carries no quantity and closes the
2040
- // whole live position when it fires (size is ignored by the venue).
2041
- size: sized ? sz : '0',
2042
- ...(sized ? {} : { sizeToMax: true }),
2090
+ size: childSize,
2043
2091
  reduceOnly: true,
2044
2092
  isTrigger: true,
2045
2093
  triggerPx,
@@ -2955,6 +3003,44 @@ class Arca {
2955
3003
  this.historyCache.set(key, result);
2956
3004
  return result;
2957
3005
  }
3006
+ /**
3007
+ * Get market-wide SETTLED funding-rate history for a market.
3008
+ *
3009
+ * Returns the venue's real settlement series — each observation carries the
3010
+ * settlement time (`t`, Unix ms), the settled `fundingRate`, and the
3011
+ * `premium` — in chronological order. This is distinct from the
3012
+ * account-scoped funding *payments* streamed by {@link Arca.watchFunding};
3013
+ * these are the market-wide rates that drive those payments.
3014
+ *
3015
+ * `market` must be a canonical market id (e.g. `"hl:0:BTC"`, `"hl:1:TSLA"`);
3016
+ * HIP-3 markets are supported where history exists. Funding is an event
3017
+ * series, so there is no `interval`. The default window is the trailing 7
3018
+ * days; the documented maximum window is 30 days. Returns an empty array for
3019
+ * an unknown market or a range with no data.
3020
+ *
3021
+ * These are settled historical rates, never predicted — for the
3022
+ * current/predicted rate read the ticker's `funding` + `nextFundingTime`.
3023
+ */
3024
+ async getFundingHistory(market, options) {
3025
+ const key = (0, cache_1.buildCacheKey)('fundingHistory', {
3026
+ market,
3027
+ startTime: options?.startTime !== undefined ? String(options.startTime) : undefined,
3028
+ endTime: options?.endTime !== undefined ? String(options.endTime) : undefined,
3029
+ });
3030
+ const cached = this.historyCache.get(key);
3031
+ if (cached)
3032
+ return cached;
3033
+ await this.ready();
3034
+ const params = {};
3035
+ if (options?.startTime !== undefined)
3036
+ params.startTime = String(options.startTime);
3037
+ if (options?.endTime !== undefined)
3038
+ params.endTime = String(options.endTime);
3039
+ const result = await this.client.get(`/exchange/market/funding/${market}`, params);
3040
+ if (result.funding.length > 0)
3041
+ this.historyCache.set(key, result);
3042
+ return result;
3043
+ }
2958
3044
  /**
2959
3045
  * Get sparkline close-price arrays for all tracked coins in a single request.
2960
3046
  * Returns a map of market name to an array of 24 hourly close prices.
@@ -3654,89 +3740,112 @@ class Arca {
3654
3740
  });
3655
3741
  }
3656
3742
  /**
3657
- * Prepare an unsigned `lockBoundary` transaction.
3658
- * The caller signs and submits this transaction from their recovery key wallet.
3659
- * Locking freezes all operator fund movement and cancels any pending exit.
3660
- */
3661
- prepareLockBoundary(contractAddress, chainId, boundaryId) {
3662
- return {
3663
- to: contractAddress,
3664
- data: encodeCustodyCall('lockBoundary(bytes32)', [boundaryId]),
3665
- chainId,
3666
- value: '0',
3667
- };
3668
- }
3669
- /**
3670
- * Prepare an unsigned `unlockBoundary` transaction.
3671
- * Only the actor who locked the boundary can unlock it.
3743
+ * Prepare an unsigned `claimRecovery` transaction — the v4 sovereign
3744
+ * escape hatch. The recovery key holder signs and broadcasts this from their
3745
+ * own wallet; no operator involvement.
3746
+ *
3747
+ * `claimRecovery` arms the recovery channel on the boundary: it stamps the
3748
+ * recovery-claim timestamp (starting the fixed 7-day `RECOVERY_WINDOW`
3749
+ * clock), freezes value-out, and triggers venue agent revocation. It is the
3750
+ * ONLY action that arms recovery — distinct from the operator's
3751
+ * `lockBoundary` operational freeze, which never starts a recovery window.
3752
+ * Requires: caller is the boundary's recovery key.
3753
+ *
3754
+ * After the window elapses, call `prepareRecoveryWithdraw` to sweep the
3755
+ * balance. To abort a false alarm before withdrawing, use
3756
+ * `prepareCancelRecovery`.
3672
3757
  */
3673
- prepareUnlockBoundary(contractAddress, chainId, boundaryId) {
3758
+ prepareClaimRecovery(contractAddress, chainId, boundaryId) {
3674
3759
  return {
3675
3760
  to: contractAddress,
3676
- data: encodeCustodyCall('unlockBoundary(bytes32)', [boundaryId]),
3761
+ data: encodeCustodyCall('claimRecovery(bytes32)', [boundaryId]),
3677
3762
  chainId,
3678
3763
  value: '0',
3679
3764
  };
3680
3765
  }
3681
3766
  /**
3682
- * Prepare an unsigned `withdraw` transaction.
3683
- * Withdraws the entire boundary balance to the recovery key holder.
3684
- * Requires: boundary is locked by the caller, caller is recovery key holder.
3767
+ * Prepare an unsigned `cancelRecovery` transaction. Closes an in-flight
3768
+ * recovery claim (false alarm), clearing the window clock and re-enabling
3769
+ * normal value flows. Requires: caller is the boundary's recovery key and a
3770
+ * claim is currently in progress.
3771
+ *
3772
+ * Note the kernel does NOT re-arm the venue agents `claimRecovery` revoked;
3773
+ * re-establishing trading authority after a cancel is a separate step.
3685
3774
  */
3686
- prepareWithdraw(contractAddress, chainId, boundaryId) {
3775
+ prepareCancelRecovery(contractAddress, chainId, boundaryId) {
3687
3776
  return {
3688
3777
  to: contractAddress,
3689
- data: encodeCustodyCall('withdraw(bytes32)', [boundaryId]),
3778
+ data: encodeCustodyCall('cancelRecovery(bytes32)', [boundaryId]),
3690
3779
  chainId,
3691
3780
  value: '0',
3692
3781
  };
3693
3782
  }
3694
3783
  /**
3695
- * Prepare an unsigned `assignRecoveryKey` transaction for changing an existing key.
3696
- * When the boundary already has a recovery key, only the current holder can change it.
3697
- * For initial assignment (no existing key), use `registerRecoveryKey()` instead.
3784
+ * Prepare an unsigned `recoveryWithdraw` transaction. Sweeps the entire
3785
+ * boundary balance to the recovery key holder. Requires: caller is the
3786
+ * boundary's recovery key, an active recovery claim exists, and the 7-day
3787
+ * `RECOVERY_WINDOW` has elapsed (or the operator fast-tracked it).
3788
+ *
3789
+ * This replaces the pre-reset v1 `withdraw(bytes32)` builder.
3698
3790
  */
3699
- prepareAssignRecoveryKey(contractAddress, chainId, boundaryId, newRecoveryKey) {
3791
+ prepareRecoveryWithdraw(contractAddress, chainId, boundaryId) {
3700
3792
  return {
3701
3793
  to: contractAddress,
3702
- data: encodeCustodyCall('assignRecoveryKey(bytes32,address)', [boundaryId, newRecoveryKey]),
3794
+ data: encodeCustodyCall('recoveryWithdraw(bytes32)', [boundaryId]),
3703
3795
  chainId,
3704
3796
  value: '0',
3705
3797
  };
3706
3798
  }
3707
3799
  /**
3708
- * Prepare an unsigned `setTimeLock` transaction.
3709
- * Recovery key holders can only increase the time lock; never decrease.
3800
+ * Prepare an unsigned `setCosignKey` transaction. Delegates or rotates the
3801
+ * boundary's day-to-day co-sign key — the key that authorizes routine
3802
+ * operator-driven withdrawals via a per-action EIP-712 signature. The
3803
+ * co-sign key is a delegation FROM the sovereign recovery key.
3804
+ *
3805
+ * Access: INITIAL delegation (no co-sign key yet) is recovery-key-only;
3806
+ * ROTATION is by the current co-sign key OR the recovery key. The
3807
+ * operator/coordinator can never seat a co-sign key. `newCosignKey` may be a
3808
+ * bare EOA (the fast path) or an `IArcaCosignVerifier` contract (the shared
3809
+ * `CosignRegistry`, for multi-device / passkey co-sign).
3810
+ *
3811
+ * This replaces the pre-reset v1 `assignRecoveryKey(bytes32,address)`
3812
+ * builder; the recovery key itself is still assigned via `registerRecoveryKey`
3813
+ * (operator-assisted) or rotated via the 2-of-2 `rotate-recovery-key` flow.
3710
3814
  */
3711
- prepareSetTimeLock(contractAddress, chainId, boundaryId, durationSeconds) {
3815
+ prepareSetCosignKey(contractAddress, chainId, boundaryId, newCosignKey) {
3712
3816
  return {
3713
3817
  to: contractAddress,
3714
- data: encodeCustodyCall('setTimeLock(bytes32,uint256)', [boundaryId, durationSeconds.toString()]),
3818
+ data: encodeCustodyCall('setCosignKey(bytes32,address)', [boundaryId, newCosignKey]),
3715
3819
  chainId,
3716
3820
  value: '0',
3717
3821
  };
3718
3822
  }
3719
3823
  /**
3720
- * Prepare an unsigned `cancelPendingExit` transaction.
3721
- * Can be called by recovery key holder or operator.
3824
+ * Prepare an unsigned `lockBoundary` transaction — the operator/coordinator
3825
+ * OPERATIONAL freeze (incident response). This is NOT the sovereign recovery
3826
+ * path: the kernel gates `lockBoundary` on the boundary's coordinator, so it
3827
+ * cannot be broadcast from a self-custody recovery-key wallet — it is exposed
3828
+ * here only for coordinator-side tooling that builds calldata. For the
3829
+ * sovereign freeze-and-exit, use `prepareClaimRecovery`.
3722
3830
  */
3723
- prepareCancelPendingExit(contractAddress, chainId, boundaryId) {
3831
+ prepareLockBoundary(contractAddress, chainId, boundaryId) {
3724
3832
  return {
3725
3833
  to: contractAddress,
3726
- data: encodeCustodyCall('cancelPendingExit(bytes32)', [boundaryId]),
3834
+ data: encodeCustodyCall('lockBoundary(bytes32)', [boundaryId]),
3727
3835
  chainId,
3728
3836
  value: '0',
3729
3837
  };
3730
3838
  }
3731
3839
  /**
3732
- * Prepare an unsigned `recoveryWithdrawAccount` transaction.
3733
- * Sweeps an exchange arca's balance back to its boundary.
3734
- * Requires: boundary is locked by the recovery key holder.
3840
+ * Prepare an unsigned `unlockBoundary` transaction — reverses the operator's
3841
+ * operational `lockBoundary`. Callable only by the address that placed the
3842
+ * lock (the coordinator). Like `prepareLockBoundary`, this is coordinator
3843
+ * tooling, not the sovereign recovery path.
3735
3844
  */
3736
- prepareRecoveryWithdrawAccount(contractAddress, chainId, arcaId) {
3845
+ prepareUnlockBoundary(contractAddress, chainId, boundaryId) {
3737
3846
  return {
3738
3847
  to: contractAddress,
3739
- data: encodeCustodyCall('recoveryWithdrawAccount(bytes32)', [arcaId]),
3848
+ data: encodeCustodyCall('unlockBoundary(bytes32)', [boundaryId]),
3740
3849
  chainId,
3741
3850
  value: '0',
3742
3851
  };