@naviprotocol/multiply 0.2.0-preview.20261102.2 → 0.2.0-preview.20261118.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,201 +1,163 @@
1
1
  # @naviprotocol/multiply
2
2
 
3
- AccountCap-based NAVI Multiply strategy engine for wallets, Auto Vault and Open API.
4
- Default NAVI reads, native Volo/Haedal quotes and Astros fallback are included.
5
- The package builds composable Sui PTBs. It never signs or broadcasts transactions.
3
+ Composable NAVI Multiply PTBs using a Registry-bound AccountCap. The SDK reads,
4
+ quotes and builds transactions; it never signs or broadcasts them.
5
+
6
+ ## Phase 1 model
7
+
8
+ The application owns product registration. Supply its validated `Strategy[]` to
9
+ `createMultiplyClient`; the API's phase 1 directory uses four main-market pairs:
10
+ vSUI/SUI, haSUI/SUI, SUI/USDC (long SUI), and USDSUI/USDC. This SDK release adds
11
+ execution support; it does not approve their production risk policy.
12
+
13
+ A strategy has distinct collateral and debt tokens. `principalCoinType` can equal
14
+ either. It is the accounting/default withdrawal unit, independent of the selected
15
+ opening input. `acceptedInputCoinTypes` defaults to `[principalCoinType]` and may
16
+ contain either or both pair assets. No third-token principal or input is supported.
6
17
 
7
18
  ```ts
8
19
  import { Transaction } from '@mysten/sui/transactions'
9
- import { createMultiplyClient, strategies } from '@naviprotocol/multiply'
20
+ import { createMultiplyClient } from '@naviprotocol/multiply'
10
21
 
11
- const multiply = createMultiplyClient()
12
- const positions = await multiply.getPosition(address, {
13
- strategy: strategies.vsuiSui, // omit to read all configured strategies
22
+ // Values come from your reviewed application registry, not wallet input.
23
+ const multiply = createMultiplyClient({
24
+ strategies: productStrategies,
25
+ retiredRegistryKeys: retiredProductKeys,
14
26
  })
27
+ const strategy = productStrategies.find(s => s.id === 'long-sui')!
15
28
  const quote = await multiply.quote(
16
29
  address,
17
- strategies.vsuiSui,
18
- { type: 'open', amount: '10000000000', targetLeverage: '2' },
19
- { minHealthFactor: '1.15', maxSlippageBps: 50, maxLeverage: '3' },
30
+ strategy,
31
+ { type: 'open', inputCoinType: strategy.collateralCoinType,
32
+ amount: '1000000000', targetLeverage: '2' },
33
+ { minHealthFactor: '1.6', maxSlippageBps: 50 }, // example, not approved risk policy
20
34
  )
21
-
22
35
  const tx = new Transaction()
23
- const input = tx.splitCoins(tx.gas, ['10000000000'])[0]
24
36
  const built = await multiply.buildPTB(tx, quote, {
25
- coins: [{ coinType: strategies.vsuiSui.principalCoinType, coin: input }],
37
+ coins: [{ coinType: strategy.collateralCoinType, coin: suppliedSuiCoin }],
26
38
  })
27
- // Astros route change goes directly to address; the caller handles the remaining assets.
28
39
  if (built.createdAccountCap) tx.transferObjects([built.createdAccountCap], address)
29
40
  if (built.coins.length) tx.transferObjects(built.coins.map(c => c.coin), address)
30
41
  tx.setSender(address)
42
+ // Caller must simulate before signing. Do not ignore any returned Coin or Cap.
31
43
  ```
32
44
 
33
- ## Public API
45
+ ## API and amount units
34
46
 
35
47
  | Method | Behavior |
36
48
  | --- | --- |
37
- | `getPosition(address, { strategy? })` | Always returns an array. Missing Cap → `[]`; existing empty Cap → zero position. Returns Cap, amounts, HF and leverage. |
38
- | `quote(address, strategy, action, constraints)` | Resolves the Cap and reads the snapshot internally. Does not create chain objects. Produces a JSON-serializable estimate and a frozen, versioned execution plan. |
39
- | `buildPTB(tx, quote, inputs)` | Rechecks Cap, market, fees, state drift and expiry, then appends commands. Returns Cap and every remaining Coin for the caller to use. |
40
-
41
- Actions: `open`, `add_principal`, `remove_principal`, `set_leverage`, `repay`,
42
- `add_collateral`, `close`. Amounts are **raw integer strings**, never JS numbers.
43
- They use each token's native decimals (supported range: 0–18), including mixed-precision pairs. The
44
- default data source converts NAVI's normalized nine-decimal balances into native
45
- atoms (collateral down, debt up). `MarketSnapshot` prices are USD per whole token;
46
- `Pool.availableBorrow` remains NAVI-normalized units and `Pool.leftSupply` remains
47
- whole tokens. Injected data sources must follow the same contract. Frozen execution
48
- plans now use version 2; version 1 quotes must be requested again before building.
49
- Leverage/HF use decimal strings; slippage uses integer basis points. An action
50
- with an `amount` requires a positive u64 value. `set_leverage` takes
51
- `targetLeverage`; add/remove principal optionally take it and otherwise preserve
52
- the current estimated leverage. `close` takes no amount.
53
-
54
- `estimate.inputs` defines the required Coin types and amounts. Supply one Coin
55
- per type; the builder splits only the quoted amount and returns its remainder.
56
- Repay overpayment is returned. Removing principal guarantees **at least** the
57
- requested output; any surplus also returns to the caller. `healthFactor: null`
58
- means no debt; `leverage: null` means an empty position or non-positive equity; inspect the returned balances. These ratios use NAVI's
59
- oracle valuation, which can differ from a token's market or redemption value.
60
-
61
- `execution` is opaque to callers. Do not modify it, reroute during build or cache
62
- it beyond `expiresAt`. Min outputs include conversion wear/fees before slippage.
63
- The solver recomputes leverage with conversion quotes, flash fees and NAVI borrow
64
- fees. One atomic conversion leg is used per initial-release plan, so the total
65
- slippage budget applies to that leg. Exact integer arithmetic is used throughout.
66
-
67
- ## Converters and injection
68
-
69
- Product strategy registration belongs to the calling application or API. Pass its
70
- validated registry into the client; adding another supported token pair does not
71
- require changing or publishing Multiply. The bundled `strategies` export remains
72
- an optional compatibility preset, not a required allowlist.
49
+ | `getPosition(address, { strategy? })` | Array of registered positions; missing Cap returns `[]`, retained empty Cap returns zero balances. Invalid reads throw. |
50
+ | `quote(address, strategy, action, constraints)` | Resolves Cap, reads current market/position and freezes a JSON execution plan. Creates no chain objects. |
51
+ | `buildPTB(tx, quote, inputs)` | Rechecks state, fees, Registry, policy constraints and expiry before appending commands. Returns Cap and remaining Coins. |
73
52
 
74
- ```ts
75
- const multiply = createMultiplyClient({ strategies: apiOwnedStrategies })
76
- // Discovery enumerates exactly this registry. quote() accepts a Strategy definition.
77
- const positions = await multiply.getPosition(address)
78
- ```
53
+ Amounts are native-precision positive u64 **integer strings**, never JS numbers.
54
+ The default source converts NAVI nine-decimal balances into token atoms, rounding
55
+ collateral down and debt up. Token decimals 0–18 are supported. Market prices are
56
+ USD per whole token; `availableBorrow` remains NAVI-normalized units and
57
+ `leftSupply` remains whole tokens. Custom sources must preserve these units.
79
58
 
80
- Registry IDs must be unique. The client snapshots the registry on initialization.
81
- Strategies bind a stable ID, market and token types to an AccountCap. Keep mutable
82
- names, display labels and product policies outside that definition. The supported
83
- execution model remains one collateral token, a distinct debt token and principal
84
- equal to debt, with lending v2, a health-factor limiter, main-market flash liquidity
85
- and an immediate converter route. Unsupported capabilities fail explicitly; new
86
- protocol mechanisms require an appropriate adapter rather than a new product ID.
87
-
88
- ```ts
89
- import {
90
- createMultiplyClient, createNaviDataSource, voloConverter, haedalConverter,
91
- } from '@naviprotocol/multiply'
92
-
93
- const multiply = createMultiplyClient({
94
- client,
95
- dataSource: createNaviDataSource({ client }), // optional, or your DataSource
96
- converters: [voloConverter({ client }), haedalConverter({ client })],
97
- // fallbackConverter: customConverter, // optional; default is Astros
98
- })
99
- ```
100
-
101
- A strategy describes tokens and lending market, not a converter. Eligible primary
102
- converters are compared by minimum net output, then stable ID. If none can quote,
103
- the fallback is used. A malformed primary quote fails instead of becoming a
104
- silently accepted route. Volo uses its live `get_amount_out` view; Haedal uses
105
- live conversion views and configured fees. Only immediate Coin → Coin conversion
106
- is supported. Native instant redemption can become unavailable; requesting a new
107
- quote can select the fallback. A build never silently selects another route.
108
-
109
- Astros uses the published `@naviprotocol/astros-aggregator-sdk@2.0.7` with its default
110
- fee and positive-slippage behavior. Route change is transferred directly to the
111
- user in `quote.address`, independently of the transaction sender or gas sponsor.
112
- It is not included in `built.coins`. The engine's other remaining coins are still
113
- returned to the caller. Its numeric route builder limits supported amounts to safe
114
- JS integers; larger routes are explicitly rejected. Minimum output, health factor
115
- and flash repayment checks remain enforced; extra fees can cause a PTB to abort
116
- if those bounds cannot be met.
117
-
118
- When calling the exported Astros converter directly, pass the real user address as
119
- the fourth build argument: `converter.buildPTB(tx, quote, coin, { changeRecipient: address })`.
120
- A missing, malformed or zero recipient is rejected before appending swap commands.
121
-
122
- A custom `DataSource` must supply complete, coherent, verified Cap/position/risk/
123
- price/fee data and prepare the oracle commands for its network. Failures must not
124
- be converted to empty positions. Custom converters and data sources execute
125
- trusted application code. Built-in deployments target **Sui mainnet**; passing a
126
- testnet client alone does not switch their contract addresses.
127
-
128
- ## AccountCap and Vault integration
129
-
130
- New Caps use `navi:multiply:v1:<strategyId>` as the name and the strategy definition
131
- as the description. Existing Caps are reused after close. A default reader
132
- excludes Caps registered to the Lending E-Mode product, validates strategy
133
- metadata, and rejects duplicates. It never registers a Multiply Cap as an E-Mode
134
- product Cap.
135
-
136
- **One wallet/strategy is enforced by discovery and SDK checks only.** Two concurrent
137
- transactions or direct contract calls can create duplicate names; renaming or
138
- transferring a Cap can bypass this convention. A contract registry is needed for
139
- a chain-enforced uniqueness guarantee. Names/descriptions are not authorization.
140
-
141
- Auto Vault can inject a resolver for wrapped Caps and pass a PTB result through
142
- `inputs.accountCap`. The resolver/caller is responsible for binding that transaction
143
- result to the quoted Cap and snapshot; a transaction result cannot be authenticated
144
- by its JS handle. Plain object-ID overrides must match the quoted ID. The engine
145
- keeps Cap transfer/wrapping and final Coin custody with the caller, except for
146
- Astros route change, which is refunded directly to `quote.address`. Vault integrations
147
- must account for that refund policy or inject a converter with their custody policy.
148
-
149
- Open API should retain quotes server-side or authenticate its quote envelope.
150
- The SHA-256 checksum detects accidental mutation; it is **not** a signature or
151
- permission to trust arbitrary client-supplied routes. A composed PTB must be
152
- simulated by its caller before signing. HF, minimum conversion output, requested
153
- principal output and optional maximum leverage are also enforced on chain. Close
154
- reads the current balance in the PTB and asserts that both balances are zero.
155
-
156
- ## Initial release boundaries
157
-
158
- - Built-in strategies: `vsuiSui`, `hasuiSui`, in their dedicated NAVI markets.
159
- Main-market flash liquidity is independent of the position market.
160
- - Principal must equal debt; collateral must be distinct. The default reader
161
- currently supports nine-decimal pools. An unsupported E-Mode override is rejected.
162
- - Delayed redemption/claim workflows, generic mixed-asset positions, cross-market
163
- position aggregation, APY/history and on-chain unique-Cap registration are not
164
- implemented. The data source checks assets in the selected market; it cannot
165
- establish exclusive use of a Cap across every other market.
166
- - Source reads and quote→build checks do not lock chain state. Changed liquidity,
167
- prices or fees can make the transaction abort. Discard a partially built PTB
168
- after a builder/network error; obtain a fresh quote rather than reuse it.
169
- - Package publication is a separate release step. The implementation is accompanied
170
- by mainnet simulation evidence, not signed/persisted chain transactions.
171
-
172
- ## Reproduce
173
-
174
- From the monorepo root (Node 24 and pnpm 10.1.0 used for the recorded run):
59
+ | Action | Amount unit / output |
60
+ | --- | --- |
61
+ | `open` | Selected `inputCoinType`, default principal; target leverage required. |
62
+ | `add_principal` | Selected SDK `inputCoinType`, default principal; API phase 1 exposes only principal. |
63
+ | `remove_principal` | Minimum net principal output, excluding wallet gas; optional target leverage. |
64
+ | `set_leverage` | Target leverage only. Returns any route surplus. |
65
+ | `repay` | Debt atoms; unused input returned. |
66
+ | `add_collateral` | Collateral atoms. |
67
+ | `close` | All remaining principal and explicit per-token dust; no amount parameter. |
68
+
69
+ HF, LTV and solver leverage use **NAVI risk oracle values**. Economic display
70
+ valuation belongs to the API and may differ for LST backing. Zero debt has null
71
+ HF; empty/non-positive equity has null leverage.
72
+
73
+ ## Execution plan v4
74
+
75
+ Older plans must be re-quoted. `funding` identifies wallet collateral/debt or no
76
+ input. Each `PlannedConversion` extends `ConversionQuote` with `id`, `purpose`
77
+ (`input | leverage | repayment | output`) and `source`. Quote fields remain flat.
78
+ The current two-asset flows have at most one conversion; arbitrary instruction
79
+ graphs and serial multi-leg conversions are rejected. A DEX route may itself have
80
+ multiple hops, bounded by the single quoted minimum output.
81
+
82
+ Collateral input is supplied directly; only borrowed debt is converted. Debt
83
+ input may merge with debt flash funding before conversion. A 1x collateral opening
84
+ needs no conversion or flash loan. On a collateral-principal withdrawal/close,
85
+ only the collateral required for debt repayment is sold; the remainder is returned
86
+ as principal. Debt dust remains a separate output. Long SUI therefore exits in SUI.
87
+
88
+ The builder independently validates funding, conversion roles, projected balances,
89
+ repayment math and minimum principal output. Different token types never merge.
90
+ `estimate.inputs` defines caller funding. Do not change execution data or reuse an
91
+ expired/partially built plan. The checksum detects mutation; it is **not** a
92
+ signature or permission to accept untrusted client plans. Open API stores quotes
93
+ server-side. The caller must simulate the final composed PTB before signing.
94
+
95
+ ## Converters
96
+
97
+ Volo and Haedal use live contract getters. Eligible routes are compared by minimum
98
+ net output. Astros is the fallback only for explicit route unavailability or
99
+ minimum-amount errors; malformed quotes, invalid inputs and read failures propagate.
100
+ A build never silently switches routes. Haedal instant redemption requires gross
101
+ SUI equivalent >= 1 SUI **before** its service fee in the pinned staking module.
102
+ Unknown conversion fees are omitted, never fabricated as zero. Known fees are
103
+ marked `includedInExpectedOutput: true`. Optional route metadata describes provider,
104
+ hops, pools/DEX and observation time; it is separate from opaque executable data.
105
+
106
+ Astros is pinned to 2.0.7. Its route change goes directly to `quote.address`, not
107
+ the gas sponsor or `built.coins`. Vault integrations must account for that custody
108
+ policy or supply another converter. Its numeric builder rejects amounts above JS
109
+ safe integer range. When using the converter directly, pass a validated
110
+ `{ changeRecipient: address }` as the fourth `buildPTB` argument.
111
+
112
+ ## Registry and injected sources
113
+
114
+ Keys `(strategyNumericId, strategyVersion)` are permanent execution identities,
115
+ unique per registry definition. Never reassign a deployed key to different assets
116
+ or market. New Caps are created and registered atomically; close retains the Cap.
117
+ Invalid ownership, duplicate Caps/accounts, unsupported E-Mode and unknown keys
118
+ fail explicitly. Only **explicit** `retiredRegistryKeys` may be skipped; structural,
119
+ identity and duplicate checks still run first. Retiring a key does not move funds.
120
+
121
+ The source and engine must receive identical strategies, retired keys and
122
+ `capRegistry`. Custom sources declare `capRegistry`; wrapped Cap resolvers must
123
+ bind any supplied transaction-result Cap to the quoted identity/state. Object-ID
124
+ overrides must match. Sender must equal quote.address. No wallet scan fallback or
125
+ migration of unregistered Caps is performed.
126
+
127
+ The optional `DataSource.readConsistentPosition(cap, strategy, signal)` capability
128
+ is for proven historical valuation: it returns native amounts, accountCapId,
129
+ accountOwner, marketKey, stateCheckpoint, stable stateId, completed:true and the
130
+ market snapshot. The amounts and accrued interest must come from one completed
131
+ chain view, not independent latest reads with an attached checkpoint number.
132
+ Respect cancellation. **The default NAVI source does not implement this capability.**
133
+ The API consequently reports lifetime yield unavailable until a conforming source
134
+ and complete history watermark are available. Basic positions and risk still work.
135
+
136
+ Custom adapters are trusted application code. Built-in contract deployments target
137
+ Sui mainnet; changing only the client URL does not switch those addresses. E-Mode,
138
+ isolated phase 2, third-token inputs and delayed redemption are out of scope.
139
+ The exported `strategies.vsuiSui`/`hasuiSui` remain legacy dedicated-market presets
140
+ (keys 1:1/2:1); phase 1 products must use the API-owned main-market registry.
141
+
142
+ ## Verification and release
143
+
144
+ From the monorepo root (Node 24, pnpm 10.1.0):
175
145
 
176
146
  ```sh
177
147
  pnpm install --frozen-lockfile
178
- pnpm --filter @naviprotocol/lending --filter @naviprotocol/astros-aggregator-sdk build
148
+ pnpm --filter @naviprotocol/multiply test
179
149
  pnpm --filter @naviprotocol/multiply typecheck
150
+ pnpm --filter @naviprotocol/multiply lint
180
151
  pnpm --filter @naviprotocol/multiply build
181
- pnpm --filter @naviprotocol/multiply test:e2e
182
152
  ```
183
153
 
184
- The test runner was committed before implementation (`57804f1`, with live-schema
185
- fixture corrections in `fba268f`). No unit tests or mocked protocol implementations
186
- were added. See [failure inventory](e2e/FAILURE-MATRIX.md) and [verification notes](docs/verification.md).
187
-
188
- Each run writes input, frozen quotes, unsigned transaction bytes, commands, actual
189
- post-operation balances/HF, simulation responses, a report and SHA-256 manifest
190
- under `out/multiply/`. `MULTIPLY_E2E_ADDRESS` selects a **public funded simulation
191
- address**; its key is neither read nor required. Defaults use the public NAVI
192
- oracle sender. `MULTIPLY_E2E_ONLY` selects scenarios; only a complete run constitutes
193
- full-suite evidence. Live chain state and service availability can change results.
194
- The lifecycle fixture is real VM execution with a transient injected snapshot;
195
- it does not prove persisted discovery or concurrent uniqueness.
196
-
197
- The packed-package consumer replay is documented in the verification report.
154
+ This preview pins published Lending 2.2.0 and Astros 2.0.7. Package it with `npm pack`
155
+ after building; API integration uses an exact local tarball plus lockfile integrity
156
+ until npm publication. A local package is not an npm release.
198
157
 
199
- The package pins published Lending 2.1.0 and Astros 2.0.7 dependencies. The clean
200
- package consumer installs only the Multiply tarball locally and resolves these
201
- dependencies from npm, without workspace links or dependency overrides.
158
+ The phase 1 tests exercise both funding relationships, management/close outputs,
159
+ threshold fallback and malformed/retired identities. Historical documents under
160
+ `docs/` and the existing `e2e/` results concern earlier presets: they do not prove
161
+ phase 1 hosted simulation or signed-wallet acceptance. Each product must progress
162
+ through open simulation → human sample creation → management simulation → human
163
+ management/close, with matching Registry keys and source/artifact revisions.
@@ -0,0 +1,18 @@
1
+ import { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
2
+ import { CapRegistryConfig, RegistryKey, Strategy } from './types.js';
3
+
4
+ export declare const ACCOUNT_CAP_TYPE = "0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap";
5
+ export declare const MAINNET_CAP_REGISTRY: Readonly<CapRegistryConfig>;
6
+ export declare function normalizeCapRegistry(config: CapRegistryConfig): CapRegistryConfig;
7
+ export declare function registryKeyString(key: RegistryKey): string;
8
+ export declare function indexRegistryStrategies(strategies: Strategy[]): Map<string, Strategy>;
9
+ export interface RegistryEntry {
10
+ registryKey: RegistryKey;
11
+ capId: string;
12
+ }
13
+ /** Decode all rows before using any of them. A malformed response is never an empty registry. */
14
+ export declare function decodeRegistryEntries(values: {
15
+ bcs: Uint8Array;
16
+ }[]): RegistryEntry[];
17
+ export declare function registerCreatedCapPTB(tx: Transaction, cap: TransactionObjectArgument, key: RegistryKey, deployment: CapRegistryConfig): void;
18
+ //# sourceMappingURL=cap-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cap-registry.d.ts","sourceRoot":"","sources":["../src/cap-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAGvE,eAAO,MAAM,gBAAgB,4FAC8D,CAAA;AAE3F,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,iBAAiB,CAI3D,CAAA;AAEF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,CAUjF;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,WAAW,GAAG,MAAM,CAU1D;AAED,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAWrF;AAED,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,WAAW,CAAA;IACxB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,iGAAiG;AACjG,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,UAAU,CAAA;CAAE,EAAE,GAAG,aAAa,EAAE,CAiCpF;AAED,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,WAAW,EACf,GAAG,EAAE,yBAAyB,EAC9B,GAAG,EAAE,WAAW,EAChB,UAAU,EAAE,iBAAiB,QAkB9B"}
@@ -0,0 +1,85 @@
1
+ import { bcs as i } from "@mysten/sui/bcs";
2
+ import { check as s, address as o, uint as I, U64_MAX as u } from "./utils.js";
3
+ const p = "0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap", R = Object.freeze({
4
+ network: "sui:mainnet",
5
+ packageId: "0xe98ff1aab2414aa2e60d0561284d011b3c486d47313b51700a2691ad4d37b162",
6
+ objectId: "0x1fb36a5acfcb96b75f0be8869fd6acebbe7586e3e271b81ae4cdcb8ae4ebdd39"
7
+ });
8
+ function A(e) {
9
+ s(e?.network === "sui:mainnet", "INVALID_ARGUMENT", "Unsupported Registry network");
10
+ const r = o(e.packageId), t = o(e.objectId);
11
+ return s(
12
+ r !== o("0x0") && t !== o("0x0"),
13
+ "INVALID_ARGUMENT",
14
+ "Zero Registry address"
15
+ ), Object.freeze({ network: e.network, packageId: r, objectId: t });
16
+ }
17
+ function b(e) {
18
+ s(e, "INVALID_ARGUMENT", "Missing strategy Registry key");
19
+ const r = I(e.strategyNumericId, !1), t = I(e.strategyVersion, !1);
20
+ return s(
21
+ t < 100000n && r * 100000n + t <= u,
22
+ "INVALID_ARGUMENT",
23
+ "Strategy Registry key is outside contract range"
24
+ ), `${r}:${t}`;
25
+ }
26
+ function _(e) {
27
+ const r = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set();
28
+ for (const n of e) {
29
+ const a = b(n.registryKey);
30
+ s(!t.has(n.id), "INVALID_ARGUMENT", "Strategy registry contains duplicate ids"), s(!r.has(a), "INVALID_ARGUMENT", "Strategy registry contains duplicate numeric keys"), t.add(n.id), r.set(a, n);
31
+ }
32
+ return r;
33
+ }
34
+ function m(e) {
35
+ try {
36
+ s(e?.length === 3, "READ_FAILED", "Invalid Registry return values");
37
+ const r = i.vector(i.u64()).parse(e[0].bcs), t = i.vector(i.u64()).parse(e[1].bcs), n = i.vector(i.Address).parse(e[2].bcs);
38
+ s(
39
+ r.length === t.length && r.length === n.length,
40
+ "READ_FAILED",
41
+ "Registry arrays differ in length"
42
+ );
43
+ const a = /* @__PURE__ */ new Set();
44
+ return r.map((c, g) => {
45
+ const d = t[g], y = `${c}:${d}`;
46
+ return s(
47
+ BigInt(c) > 0n && BigInt(d) > 0n && BigInt(d) < 100000n && BigInt(c) * 100000n + BigInt(d) <= u && !a.has(y),
48
+ "READ_FAILED",
49
+ "Invalid or duplicate Registry key"
50
+ ), a.add(y), {
51
+ registryKey: { strategyNumericId: c, strategyVersion: d },
52
+ capId: o(n[g])
53
+ };
54
+ });
55
+ } catch {
56
+ s(!1, "READ_FAILED", "Unable to decode complete Multiply Registry");
57
+ }
58
+ }
59
+ function E(e, r, t, n) {
60
+ b(t);
61
+ const a = A(n), c = e.moveCall({
62
+ target: "0x2::object::id_address",
63
+ typeArguments: [p],
64
+ arguments: [r]
65
+ });
66
+ e.moveCall({
67
+ target: `${a.packageId}::multiply_registry::register_mul_for_account_cap`,
68
+ arguments: [
69
+ e.object(a.objectId),
70
+ c,
71
+ e.pure.u64(t.strategyNumericId),
72
+ e.pure.u64(t.strategyVersion)
73
+ ]
74
+ });
75
+ }
76
+ export {
77
+ p as ACCOUNT_CAP_TYPE,
78
+ R as MAINNET_CAP_REGISTRY,
79
+ m as decodeRegistryEntries,
80
+ _ as indexRegistryStrategies,
81
+ A as normalizeCapRegistry,
82
+ E as registerCreatedCapPTB,
83
+ b as registryKeyString
84
+ };
85
+ //# sourceMappingURL=cap-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cap-registry.js","sources":["../src/cap-registry.ts"],"sourcesContent":["import { bcs } from '@mysten/sui/bcs'\nimport type { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions'\nimport type { CapRegistryConfig, RegistryKey, Strategy } from './types'\nimport { address, check, U64_MAX, uint } from './utils'\n\nexport const ACCOUNT_CAP_TYPE =\n '0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap'\n\nexport const MAINNET_CAP_REGISTRY: Readonly<CapRegistryConfig> = Object.freeze({\n network: 'sui:mainnet',\n packageId: '0xe98ff1aab2414aa2e60d0561284d011b3c486d47313b51700a2691ad4d37b162',\n objectId: '0x1fb36a5acfcb96b75f0be8869fd6acebbe7586e3e271b81ae4cdcb8ae4ebdd39'\n})\n\nexport function normalizeCapRegistry(config: CapRegistryConfig): CapRegistryConfig {\n check(config?.network === 'sui:mainnet', 'INVALID_ARGUMENT', 'Unsupported Registry network')\n const packageId = address(config.packageId),\n objectId = address(config.objectId)\n check(\n packageId !== address('0x0') && objectId !== address('0x0'),\n 'INVALID_ARGUMENT',\n 'Zero Registry address'\n )\n return Object.freeze({ network: config.network, packageId, objectId })\n}\n\nexport function registryKeyString(key: RegistryKey): string {\n check(key, 'INVALID_ARGUMENT', 'Missing strategy Registry key')\n const id = uint(key.strategyNumericId, false),\n version = uint(key.strategyVersion, false)\n check(\n version < 100000n && id * 100000n + version <= U64_MAX,\n 'INVALID_ARGUMENT',\n 'Strategy Registry key is outside contract range'\n )\n return `${id}:${version}`\n}\n\nexport function indexRegistryStrategies(strategies: Strategy[]): Map<string, Strategy> {\n const byKey = new Map<string, Strategy>(),\n ids = new Set<string>()\n for (const strategy of strategies) {\n const key = registryKeyString(strategy.registryKey)\n check(!ids.has(strategy.id), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate ids')\n check(!byKey.has(key), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate numeric keys')\n ids.add(strategy.id)\n byKey.set(key, strategy)\n }\n return byKey\n}\n\nexport interface RegistryEntry {\n registryKey: RegistryKey\n capId: string\n}\n\n/** Decode all rows before using any of them. A malformed response is never an empty registry. */\nexport function decodeRegistryEntries(values: { bcs: Uint8Array }[]): RegistryEntry[] {\n try {\n check(values?.length === 3, 'READ_FAILED', 'Invalid Registry return values')\n const ids = bcs.vector(bcs.u64()).parse(values[0].bcs)\n const versions = bcs.vector(bcs.u64()).parse(values[1].bcs)\n const caps = bcs.vector(bcs.Address).parse(values[2].bcs)\n check(\n ids.length === versions.length && ids.length === caps.length,\n 'READ_FAILED',\n 'Registry arrays differ in length'\n )\n const keys = new Set<string>()\n return ids.map((id, i) => {\n const version = versions[i],\n key = `${id}:${version}`\n check(\n BigInt(id) > 0n &&\n BigInt(version) > 0n &&\n BigInt(version) < 100000n &&\n BigInt(id) * 100000n + BigInt(version) <= U64_MAX &&\n !keys.has(key),\n 'READ_FAILED',\n 'Invalid or duplicate Registry key'\n )\n keys.add(key)\n return {\n registryKey: { strategyNumericId: id, strategyVersion: version },\n capId: address(caps[i])\n }\n })\n } catch {\n check(false, 'READ_FAILED', 'Unable to decode complete Multiply Registry')\n }\n}\n\nexport function registerCreatedCapPTB(\n tx: Transaction,\n cap: TransactionObjectArgument,\n key: RegistryKey,\n deployment: CapRegistryConfig\n) {\n registryKeyString(key)\n const config = normalizeCapRegistry(deployment)\n const capAddress = tx.moveCall({\n target: '0x2::object::id_address',\n typeArguments: [ACCOUNT_CAP_TYPE],\n arguments: [cap]\n })\n tx.moveCall({\n target: `${config.packageId}::multiply_registry::register_mul_for_account_cap`,\n arguments: [\n tx.object(config.objectId),\n capAddress,\n tx.pure.u64(key.strategyNumericId),\n tx.pure.u64(key.strategyVersion)\n ]\n })\n}\n"],"names":["ACCOUNT_CAP_TYPE","MAINNET_CAP_REGISTRY","normalizeCapRegistry","config","check","packageId","address","objectId","registryKeyString","key","id","uint","version","U64_MAX","indexRegistryStrategies","strategies","byKey","ids","strategy","decodeRegistryEntries","values","bcs","versions","caps","keys","i","registerCreatedCapPTB","tx","cap","deployment","capAddress"],"mappings":";;AAKO,MAAMA,IACX,2FAEWC,IAAoD,OAAO,OAAO;AAAA,EAC7E,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;AAEM,SAASC,EAAqBC,GAA8C;AACjF,EAAAC,EAAMD,GAAQ,YAAY,eAAe,oBAAoB,8BAA8B;AAC3F,QAAME,IAAYC,EAAQH,EAAO,SAAS,GACxCI,IAAWD,EAAQH,EAAO,QAAQ;AACpC,SAAAC;AAAA,IACEC,MAAcC,EAAQ,KAAK,KAAKC,MAAaD,EAAQ,KAAK;AAAA,IAC1D;AAAA,IACA;AAAA,EAAA,GAEK,OAAO,OAAO,EAAE,SAASH,EAAO,SAAS,WAAAE,GAAW,UAAAE,GAAU;AACvE;AAEO,SAASC,EAAkBC,GAA0B;AAC1D,EAAAL,EAAMK,GAAK,oBAAoB,+BAA+B;AAC9D,QAAMC,IAAKC,EAAKF,EAAI,mBAAmB,EAAK,GAC1CG,IAAUD,EAAKF,EAAI,iBAAiB,EAAK;AAC3C,SAAAL;AAAA,IACEQ,IAAU,WAAWF,IAAK,UAAUE,KAAW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W,KACvB,OAAO,CAAC,aAAa,CAAC;mBAyEnB,WAAW,iBACA,aAAa,UACpB,WAAW,KAClB,OAAO,CAAC,WAAW,CAAC;EA0cxB"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAkC,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAEV,MAAM,EACN,WAAW,EACX,WAAW,EACX,WAAW,EAGX,eAAe,EACf,aAAa,EACb,QAAQ,EACR,QAAQ,EACT,MAAM,SAAS,CAAA;AAiChB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,eAAoB;yBA2IvD,MAAM,UACN;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAC7B,OAAO,CAAC,QAAQ,EAAE,CAAC;mBAuBb,MAAM,oBACK,QAAQ,UAClB,MAAM,eACD,WAAW,KACvB,OAAO,CAAC,aAAa,CAAC;mBAmFnB,WAAW,iBACA,aAAa,UACpB,WAAW,KAClB,OAAO,CAAC,WAAW,CAAC;EAuexB"}