TypeScript reference implementation
Follow the reference code for discovery, synchronization, deposits, withdrawals, reward claims and pricing.
12. Appendix A — TypeScript reference implementation
Reference implementation of discovery, transaction construction and simulation-based pricing. Requires @mysten/sui version 1; checked against 1.45.2 under tsc --strict. The code blocks in this appendix concatenate in order into a single compilable module.
Verification status, as of 2026-08-05 against mainnet:
| Function | Status |
|---|---|
readVaultLayout | Executed against every live vault; market and reward-rule decoding confirmed |
findReceipts | Executed; attribution by vault_address confirmed, including the silent empty result when the type filter uses the latest package instead of the original |
quoteVault | Executed against every live vault, synchronizing first |
previewWithdraw | Executed with a live position, with and without oraclePrologue; omitting it aborts 1502 as specified in §3.3 |
previewClaimReward | Executed against a live position with an active reward rule |
buildDepositTx, buildWithdrawTx, buildClaimRewardTx | Command order and argument positions match the executed mainnet transactions in §5.6; never submitted as signed transactions |
buildWithdrawTx requires an oraclePrologue callback for the price update described in §3.3. The oracle entrypoint is deliberately not hardcoded: its revision advances, and a pinned name breaks when the oracle is upgraded.
A.1 Types and configuration
import { bcs } from '@mysten/sui/bcs';
import type { SuiClient } from '@mysten/sui/client';
import { Transaction } from '@mysten/sui/transactions';
import type { TransactionObjectArgument, TransactionResult } from '@mysten/sui/transactions';
const CLOCK = '0x6';
const SUI_SYSTEM_STATE = '0x5';
const U64_MAX = 18446744073709551615n;
/** WAD = 1e18. Fee rates and market penalties are scaled by this factor. */
export const WAD = 1_000_000_000_000_000_000n;
export interface VaultConfig {
/**
* LATEST published navi_vault package. Used as the `target` of every moveCall.
* Changes on every upgrade; calling a superseded package runs superseded code (§1.3).
*/
packageId: string;
/**
* ORIGINAL navi_vault package. Used for every type string — owned-object filters, event
* filters, objectType matching. Fixed for the lifetime of the deployment.
* Using `packageId` here yields silent empty results (§1.3).
*/
typePackageId: string;
/** Shared Vault<CoinType> object identifier. */
vaultId: string;
/** Fully qualified CoinType, e.g. '0x2::sui::SUI'. */
coinType: string;
/** NAVI PriceOracle shared object; required by withdraw. */
oracleId: string;
/**
* RewardFund<T> object per reward coin type. These objects belong to NAVI's incentive_v3 and
* are not recorded in vault state; resolve them from the lending side and cache them.
* Keys are canonicalized before lookup, so either `0x2::sui::SUI` or the padded form works.
*/
rewardFunds: Record<string, string>;
}
export interface MarketLayout {
poolId: string;
cap: bigint;
penalty: bigint;
loss: bigint;
/** 0 = Active, 1 = Disabled. Disabled markets still require synchronization. */
status: number;
lastSyncAtMs: bigint;
storageId: string;
assetId: number;
incentiveV3Id: string;
incentiveV2Id: string;
}
export interface RewardRuleLayout {
index: number;
naviPoolId: string;
rewardCoinType: string;
incentiveRuleId: string;
vaultRewardIndex: bigint;
lastHarvestAtMs: bigint;
isVaultNative: boolean;
rewardRate: bigint;
isActive: boolean;
totalRewardDeposited: bigint;
totalRewardDistributed: bigint;
}
export interface VaultLayout {
markets: MarketLayout[];
rules: RewardRuleLayout[];
/** 0x0 indicates deposits are routed to the idle balance. */
defaultMarket: string;
paused: boolean;
version: bigint;
vaultCap: bigint;
managementFee: bigint;
performanceFee: bigint;
}A.2 Simulation helper
type Decoded = unknown[];
/**
* Evaluate a read-only block and return the decoded return values of each Move call, in order.
* Calls that return nothing yield an empty array.
*/
async function inspect(client: SuiClient, tx: Transaction, sender: string): Promise<Decoded[]> {
const res = await client.devInspectTransactionBlock({ sender, transactionBlock: tx });
if (res.error) throw new Error(`devInspect failed: ${res.error}`);
return (res.results ?? []).map((r) =>
(r.returnValues ?? []).map(([bytes, type]) => decode(Uint8Array.from(bytes), type)),
);
}
function decode(bytes: Uint8Array, type: string): unknown {
switch (type) {
case 'bool':
return bcs.Bool.parse(bytes);
case 'u8':
return bcs.U8.parse(bytes);
case 'u64':
return BigInt(bcs.U64.parse(bytes));
case 'u256':
return BigInt(bcs.U256.parse(bytes));
case 'address':
return bcs.Address.parse(bytes);
default:
// std::ascii::String and std::string::String are structs { bytes: vector<u8> }, which share
// the BCS layout of a string. The reported address may be padded, so match on the suffix.
if (type.endsWith('::ascii::String') || type.endsWith('::string::String')) {
return bcs.string().parse(bytes);
}
throw new Error(`unhandled return type: ${type}`);
}
}
/**
* List an account's positions in one vault.
*
* `Receipt` is not generic: one type covers every vault, so the type filter alone cannot tell them
* apart — each Receipt's `vault_address` must be matched against the vault of interest. This
* matters concretely when two vaults share a CoinType, which is permitted (§1.3).
*
* The type filter uses `typePackageId`, not `packageId`. Using the latest package matches nothing
* and reports no error.
*/
export async function findReceipts(
client: SuiClient,
cfg: VaultConfig,
owner: string,
): Promise<string[]> {
const receiptType = `${cfg.typePackageId}::navi_vault::Receipt`;
const found: string[] = [];
let cursor: string | null | undefined;
do {
const page = await client.getOwnedObjects({
owner,
cursor,
filter: { StructType: receiptType },
options: { showContent: true },
});
for (const obj of page.data) {
const content = obj.data?.content;
if (content?.dataType !== 'moveObject') continue;
const fields = content.fields as { vault_address?: string };
// Receipts for other vaults share this exact type — attribution is mandatory.
if (fields.vault_address === cfg.vaultId && obj.data?.objectId) {
found.push(obj.data.objectId);
}
}
cursor = page.hasNextPage ? page.nextCursor : null;
} while (cursor);
return found;
}
/**
* Canonicalize a Move type string for comparison against contract-stored values.
*
* `get_rule_info` returns `reward_coin_type` as produced by
* `type_name::with_defining_ids<T>().into_string()`, whose address segment is zero-padded to 64
* hexadecimal characters and carries no `0x` prefix. A caller-supplied abbreviation such as
* `0x2::sui::SUI` therefore does not compare equal to the stored
* `0000…0002::sui::SUI`. Comparing without canonicalizing causes reward rules to go unmatched,
* which omits their `collect_reward` call and silently pays out only previously harvested
* rewards.
*/
function normalizeType(t: string): string {
const parts = t.split('::');
if (parts.length < 2) return t;
const addr = parts[0].replace(/^0x/, '').toLowerCase();
if (!/^[0-9a-f]{1,64}$/.test(addr)) return t;
return [`0x${addr.padStart(64, '0')}`, ...parts.slice(1)].join('::');
}
/** Look up a RewardFund object, canonicalizing configured keys so abbreviations resolve. */
function rewardFundFor(cfg: VaultConfig, coinType: string): string | undefined {
const wanted = normalizeType(coinType);
for (const [key, id] of Object.entries(cfg.rewardFunds)) {
if (normalizeType(key) === wanted) return id;
}
return undefined;
}A.3 Discovery
/**
* Read the vault's market list, reward rules and headline configuration.
*
* The result must not be cached across transactions: a curator may add a market or change a
* market's status at any time, and a newly added market has last_sync_at = 0, which causes any
* deposit or withdrawal omitting it to abort with E_MARKET_NOT_READ (10006).
*/
export async function readVaultLayout(
client: SuiClient,
cfg: VaultConfig,
sender: string,
): Promise<VaultLayout> {
const { packageId: p, vaultId, coinType: T } = cfg;
const head = new Transaction();
const v = () => head.object(vaultId);
head.moveCall({ target: `${p}::navi_vault::num_markets`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::num_reward_rules`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::get_vault_default_market`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::is_paused`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::version`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::get_vault_cap`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::get_management_fee`, typeArguments: [T], arguments: [v()] });
head.moveCall({ target: `${p}::navi_vault::get_performance_fee`, typeArguments: [T], arguments: [v()] });
const h = await inspect(client, head, sender);
const numMarkets = Number(h[0][0] as bigint);
const numRules = Number(h[1][0] as bigint);
const detail = new Transaction();
for (let i = 0; i < numMarkets; i++) {
detail.moveCall({
target: `${p}::navi_vault::get_market_address_at_index`,
typeArguments: [T],
arguments: [detail.object(vaultId), detail.pure.u64(i)],
});
}
for (let i = 0; i < numRules; i++) {
detail.moveCall({
target: `${p}::navi_vault::get_rule_info`,
typeArguments: [T],
arguments: [detail.object(vaultId), detail.pure.u64(i)],
});
}
const d = numMarkets + numRules > 0 ? await inspect(client, detail, sender) : [];
const poolIds = d.slice(0, numMarkets).map((r) => r[0] as string);
const rules: RewardRuleLayout[] = d.slice(numMarkets).map((r, index) => ({
index,
naviPoolId: r[0] as string,
rewardCoinType: normalizeType(r[1] as string),
incentiveRuleId: r[2] as string,
vaultRewardIndex: r[3] as bigint,
lastHarvestAtMs: r[4] as bigint,
isVaultNative: r[5] as boolean,
rewardRate: r[6] as bigint,
isActive: r[7] as boolean,
totalRewardDeposited: r[8] as bigint,
totalRewardDistributed: r[9] as bigint,
}));
const cfgTx = new Transaction();
for (const poolId of poolIds) {
cfgTx.moveCall({
target: `${p}::navi_vault::get_market_config`,
typeArguments: [T],
arguments: [cfgTx.object(vaultId), cfgTx.pure.address(poolId)],
});
}
const c = poolIds.length ? await inspect(client, cfgTx, sender) : [];
const markets: MarketLayout[] = poolIds.map((poolId, i) => {
const r = c[i];
return {
poolId,
cap: r[0] as bigint,
penalty: r[1] as bigint,
loss: r[2] as bigint,
status: r[3] as number,
lastSyncAtMs: r[4] as bigint,
storageId: r[5] as string,
assetId: r[6] as number,
incentiveV3Id: r[7] as string,
incentiveV2Id: r[8] as string,
};
});
return {
markets,
rules,
defaultMarket: h[2][0] as string,
paused: h[3][0] as boolean,
version: h[4][0] as bigint,
vaultCap: h[5][0] as bigint,
managementFee: h[6][0] as bigint,
performanceFee: h[7][0] as bigint,
};
}A.4 Freshness prologue
/**
* Append the synchronization and harvest calls that deposit and withdraw assert on:
* sync_market_balance for every market, Active and Disabled alike, and collect_reward for every
* active, non-vault-native reward rule.
*
* All calls in one block observe the same clock.timestamp_ms(), which is how the contract
* establishes that the refresh occurred in the same transaction.
*/
export function appendFreshness(tx: Transaction, cfg: VaultConfig, layout: VaultLayout): void {
const { packageId: p, vaultId, coinType: T } = cfg;
for (const m of layout.markets) {
tx.moveCall({
target: `${p}::navi_vault::sync_market_balance`,
typeArguments: [T],
arguments: [tx.object(vaultId), tx.object(m.storageId), tx.object(m.poolId), tx.object(CLOCK)],
});
}
for (const rule of layout.rules) {
// collect_reward has no effect for these rules; skipping them saves gas.
if (rule.isVaultNative || !rule.isActive) continue;
const market = layout.markets.find((m) => m.poolId === rule.naviPoolId);
if (!market) {
throw new Error(`rule ${rule.index} references unknown market ${rule.naviPoolId}`);
}
const fund = rewardFundFor(cfg, rule.rewardCoinType);
if (!fund) {
// Without the RewardFund object the rule cannot be harvested and the operation would abort
// with E_REWARDS_NOT_COLLECTED. Fail here instead, with a diagnosable message.
throw new Error(`no RewardFund configured for ${rule.rewardCoinType} (rule ${rule.index})`);
}
tx.moveCall({
target: `${p}::navi_vault::collect_reward`,
typeArguments: [T, rule.rewardCoinType],
arguments: [
tx.object(vaultId),
tx.object(CLOCK),
tx.object(market.storageId),
tx.object(market.incentiveV3Id),
tx.object(fund),
tx.pure.u64(rule.index),
],
});
}
}
const ZERO_ADDRESS = `0x${'0'.repeat(64)}`;
function isUnset(addr: string): boolean {
return addr === '0x0' || addr === ZERO_ADDRESS;
}
/** The market whose objects a deposit or withdrawal should be pointed at. */
function resolveTargetMarket(layout: VaultLayout, poolId?: string): MarketLayout {
const wanted =
poolId ?? (!isUnset(layout.defaultMarket) ? layout.defaultMarket : layout.markets[0]?.poolId);
const m = layout.markets.find((x) => x.poolId === wanted);
if (!m) throw new Error(`market ${wanted} is not registered on this vault`);
return m;
}A.5 Deposit
export interface DepositArgs {
/** Native token units. Must equal the deposit coin's value exactly. */
amount: bigint;
/** Existing Receipt to add to, or undefined to mint a new position. */
receiptId?: string;
/** Recipient of the Receipt. */
recipient: string;
/**
* Source coins. Omit for SUI to split from the gas coin. Otherwise pass owned coin objects;
* they are merged and split to `amount`.
*/
coinObjectIds?: string[];
}
/**
* Deposit block: M synchronizations, R harvests, then deposit.
*
* When the vault has a default market, the pool, storage and incentive arguments must be that
* market's, otherwise the call aborts with E_DEFAULT_MARKET_MISMATCH. When the default market is
* unset, assets are added to the idle balance and those arguments are not validated, but remain
* type-required.
*/
export function buildDepositTx(
cfg: VaultConfig,
layout: VaultLayout,
args: DepositArgs,
): Transaction {
if (layout.paused) throw new Error('vault is paused');
const { packageId: p, vaultId, coinType: T } = cfg;
const target = resolveTargetMarket(layout);
const tx = new Transaction();
appendFreshness(tx, cfg, layout);
// deposit asserts deposit_coin.value() == amount, so split exactly.
let source: TransactionObjectArgument;
if (args.coinObjectIds && args.coinObjectIds.length > 0) {
const [first, ...rest] = args.coinObjectIds;
source = tx.object(first);
if (rest.length) tx.mergeCoins(source, rest.map((id) => tx.object(id)));
} else {
source = tx.gas;
}
const [depositCoin] = tx.splitCoins(source, [tx.pure.u64(args.amount)]);
const receiptType = `${p}::navi_vault::Receipt`;
const receiptOpt = args.receiptId
? tx.moveCall({
target: '0x1::option::some',
typeArguments: [receiptType],
arguments: [tx.object(args.receiptId)],
})
: tx.moveCall({ target: '0x1::option::none', typeArguments: [receiptType], arguments: [] });
const [receipt] = tx.moveCall({
target: `${p}::navi_vault::deposit`,
typeArguments: [T],
arguments: [
tx.object(vaultId),
receiptOpt,
tx.object(CLOCK),
tx.object(target.storageId),
tx.object(target.poolId),
depositCoin,
tx.pure.u64(args.amount),
tx.object(target.incentiveV2Id),
tx.object(target.incentiveV3Id),
],
}) as TransactionResult;
// The Receipt is returned by value and must be consumed. When adding to an existing position
// this returns the same object to its owner.
tx.transferObjects([receipt], args.recipient);
return tx;
}A.6 Withdrawal
export interface WithdrawArgs {
receiptId: string;
/** Native token units. With fromDefault, pass U64_MAX to request a full exit. */
amount: bigint;
/**
* Bound on shares burned. Must not be 0: the contract interprets 0 as no limit rather than
* zero shares. Derive it from previewWithdraw.
*/
maxShares: bigint;
/**
* true: pool must be the default market; no penalty; amount is clamped to the holder's
* maximum. Required for a full exit.
* false: any registered market, Active or Disabled; the market's penalty applies to the
* portion drawn from it.
*/
fromDefault: boolean;
/** Source of the shortfall remaining after the idle balance. Defaults to the default market. */
poolId?: string;
recipient: string;
/**
* Appends the oracle price update that withdrawal requires (§3.3). Invoked first, before the
* market synchronizations, mirroring the verified block shape in §5.6.
*
* This is injected rather than built here because the call belongs to the oracle package, whose
* entrypoint signature and object set differ between oracle implementations and change when NAVI
* upgrades the oracle. Supply a closure that issues the update for `cfg.oracleId` using the
* oracle package the target deployment links against.
*
* Omitting it is permitted only when the caller has independently established that the price for
* this asset is inside the oracle's update_interval — 30 s by default. Otherwise the withdrawal
* aborts with 1502.
*/
oraclePrologue?: (tx: Transaction) => void;
}
/**
* Withdrawal block: oracle price update, M synchronizations, R harvests, then withdraw.
*/
export function buildWithdrawTx(
cfg: VaultConfig,
layout: VaultLayout,
args: WithdrawArgs,
): Transaction {
if (layout.paused) throw new Error('vault is paused');
if (args.maxShares === 0n) throw new Error('maxShares of 0 disables slippage protection');
const { packageId: p, vaultId, coinType: T } = cfg;
const source = args.fromDefault
? resolveTargetMarket(layout, layout.defaultMarket)
: resolveTargetMarket(layout, args.poolId);
const tx = new Transaction();
// Must precede the synchronizations: withdraw reaches NAVI's collateral valuation, which
// asserts price validity even though the vault holds no debt (§3.3).
args.oraclePrologue?.(tx);
appendFreshness(tx, cfg, layout);
const [coin] = tx.moveCall({
target: `${p}::navi_vault::withdraw`,
typeArguments: [T],
arguments: [
tx.object(vaultId),
tx.object(args.receiptId),
tx.object(CLOCK),
tx.object(cfg.oracleId),
tx.object(source.storageId),
tx.object(source.poolId),
tx.pure.u64(args.amount),
tx.pure.u64(args.maxShares),
tx.pure.bool(args.fromDefault),
tx.object(source.incentiveV2Id),
tx.object(source.incentiveV3Id),
tx.object(SUI_SYSTEM_STATE),
],
}) as TransactionResult;
// The coin's actual value is authoritative; NAVI may return marginally less than requested.
tx.transferObjects([coin], args.recipient);
return tx;
}
/** Full exit. fromDefault clamps the amount to the holder's maximum redeemable value. */
export function buildExitAllTx(
cfg: VaultConfig,
layout: VaultLayout,
a: {
receiptId: string;
maxShares: bigint;
recipient: string;
oraclePrologue?: (tx: Transaction) => void;
},
): Transaction {
return buildWithdrawTx(cfg, layout, {
receiptId: a.receiptId,
amount: U64_MAX,
maxShares: a.maxShares,
fromDefault: true,
recipient: a.recipient,
oraclePrologue: a.oraclePrologue,
});
}A.7 Reward claim
/**
* Reward claim block for one reward coin type.
*
* claim_reward has no freshness preconditions, but a preceding collect_reward is what makes newly
* accrued protocol rewards payable. Only rules denominated in this coin need harvesting.
*
* claim_reward returns a zero-valued coin rather than aborting when nothing is claimable, so
* callers should consult get_user_claimable_reward_amount and omit the transaction in that case
* rather than creating zero-valued objects.
*/
export function buildClaimRewardTx(
cfg: VaultConfig,
layout: VaultLayout,
args: { receiptId: string; rewardCoinType: string; recipient: string },
): Transaction {
if (layout.paused) throw new Error('vault is paused');
const { packageId: p, vaultId, coinType: T } = cfg;
const rewardType = normalizeType(args.rewardCoinType);
const tx = new Transaction();
for (const rule of layout.rules) {
if (rule.isVaultNative || !rule.isActive) continue;
if (rule.rewardCoinType !== rewardType) continue;
const market = layout.markets.find((m) => m.poolId === rule.naviPoolId);
const fund = rewardFundFor(cfg, rule.rewardCoinType);
if (!market || !fund) continue;
tx.moveCall({
target: `${p}::navi_vault::collect_reward`,
typeArguments: [T, rule.rewardCoinType],
arguments: [
tx.object(vaultId),
tx.object(CLOCK),
tx.object(market.storageId),
tx.object(market.incentiveV3Id),
tx.object(fund),
tx.pure.u64(rule.index),
],
});
}
const coin = tx.moveCall({
target: `${p}::navi_vault::claim_reward`,
typeArguments: [T, rewardType],
arguments: [tx.object(vaultId), tx.object(args.receiptId), tx.object(CLOCK)],
});
tx.transferObjects([coin], args.recipient);
return tx;
}A.8 Pricing
export interface VaultQuote {
totalAssets: bigint;
totalShares: bigint;
idleBalance: bigint;
userShares?: bigint;
userAssets?: bigint;
/** Shares a deposit of the requested amount would mint. */
sharesForDeposit?: bigint;
}
/**
* Price the vault against a synchronized snapshot.
*
* get_total_assets, convert_to_* and get_user_balance read MarketInfo.current_balance, whose
* freshness is bounded by the most recent on-chain sync_market_balance. Reading them directly
* understates the position by all interest accrued since. This function synchronizes every market
* first; devInspectTransactionBlock simulates execution, so nothing is written on chain.
*/
export async function quoteVault(
client: SuiClient,
cfg: VaultConfig,
layout: VaultLayout,
sender: string,
opts: { receiptId?: string; depositAmount?: bigint } = {},
): Promise<VaultQuote> {
const { packageId: p, vaultId, coinType: T } = cfg;
const tx = new Transaction();
for (const m of layout.markets) {
tx.moveCall({
target: `${p}::navi_vault::sync_market_balance`,
typeArguments: [T],
arguments: [tx.object(vaultId), tx.object(m.storageId), tx.object(m.poolId), tx.object(CLOCK)],
});
}
const readsStart = layout.markets.length;
tx.moveCall({ target: `${p}::navi_vault::get_total_assets`, typeArguments: [T], arguments: [tx.object(vaultId)] });
tx.moveCall({ target: `${p}::navi_vault::get_total_shares`, typeArguments: [T], arguments: [tx.object(vaultId)] });
tx.moveCall({ target: `${p}::navi_vault::get_idle_balance`, typeArguments: [T], arguments: [tx.object(vaultId)] });
if (opts.receiptId) {
tx.moveCall({
target: `${p}::navi_vault::get_user_shares`,
typeArguments: [T],
arguments: [tx.object(vaultId), tx.object(opts.receiptId)],
});
tx.moveCall({
target: `${p}::navi_vault::get_user_balance`,
typeArguments: [T],
arguments: [tx.object(vaultId), tx.object(opts.receiptId)],
});
}
if (opts.depositAmount !== undefined) {
tx.moveCall({
target: `${p}::navi_vault::convert_to_shares`,
typeArguments: [T],
arguments: [tx.object(vaultId), tx.pure.u64(opts.depositAmount)],
});
}
const r = await inspect(client, tx, sender);
let i = readsStart;
const quote: VaultQuote = {
totalAssets: r[i++][0] as bigint,
totalShares: r[i++][0] as bigint,
idleBalance: r[i++][0] as bigint,
};
if (opts.receiptId) {
quote.userShares = r[i++][0] as bigint;
quote.userAssets = r[i++][0] as bigint;
}
if (opts.depositAmount !== undefined) {
quote.sharesForDeposit = r[i++][0] as bigint;
}
return quote;
}
/**
* Simulate the withdrawal and read back the shares it would burn, then apply a tolerance.
*
* This is the reliable way to derive maxShares: it accounts for the non-default-market penalty,
* ceiling rounding, idle-first routing and same-transaction fee accrual, none of which
* convert_to_shares models.
*
* The drift between simulation and execution is favourable: interest accrual raises share price,
* so the same amount costs marginally fewer shares at execution time. The tolerance covers
* rounding and any fee accrual in the interval.
*
* @param toleranceBps tolerance in basis points; 30n corresponds to 0.3%.
*/
export async function previewWithdraw(
client: SuiClient,
cfg: VaultConfig,
layout: VaultLayout,
sender: string,
args: Omit<WithdrawArgs, 'maxShares'>,
toleranceBps = 30n,
): Promise<{ sharesBurned: bigint; amountOut: bigint; maxShares: bigint }> {
const tx = buildWithdrawTx(cfg, layout, { ...args, maxShares: U64_MAX });
const res = await client.devInspectTransactionBlock({ sender, transactionBlock: tx });
if (res.error) throw new Error(`withdraw simulation failed: ${res.error}`);
// withdraw returns (Coin<CoinType>, u64) and is the last command returning a u64; the
// synchronizations, harvests and trailing transferObjects return nothing.
const results = res.results ?? [];
let sharesBurned: bigint | undefined;
for (let i = results.length - 1; i >= 0; i--) {
const rv = results[i]?.returnValues?.find(([, t]) => t === 'u64');
if (rv) {
sharesBurned = BigInt(bcs.U64.parse(Uint8Array.from(rv[0])));
break;
}
}
if (sharesBurned === undefined) throw new Error('could not read shares_burned from simulation');
// The coin value is an object rather than a BCS return value, so take the amount from the
// emitted WithdrawEvent.
const ev = res.events?.find((e) => e.type.endsWith('::events::WithdrawEvent'));
const amountOut = ev ? BigInt((ev.parsedJson as { amount: string }).amount) : 0n;
return {
sharesBurned,
amountOut,
maxShares: (sharesBurned * (10_000n + toleranceBps)) / 10_000n,
};
}
/**
* A holder's true claimable reward for one coin type.
*
* get_user_claimable_reward_amount lags twice: the vault index advances only on collect_reward,
* and the holder's reward_total advances only when that holder interacts. Simulating the
* settlement path and reading the emitted ClaimRewardEvent resolves both.
*/
export async function previewClaimReward(
client: SuiClient,
cfg: VaultConfig,
layout: VaultLayout,
sender: string,
args: { receiptId: string; rewardCoinType: string },
): Promise<bigint> {
const tx = buildClaimRewardTx(cfg, layout, { ...args, recipient: sender });
const res = await client.devInspectTransactionBlock({ sender, transactionBlock: tx });
if (res.error) throw new Error(`claim simulation failed: ${res.error}`);
const ev = res.events?.find((e) => e.type.endsWith('::events::ClaimRewardEvent'));
return ev ? BigInt((ev.parsedJson as { amount: string }).amount) : 0n;
}A.9 Derived quantities
/** Share price in assets per share. Accepts a quote produced by quoteVault. */
export function sharePrice(q: Pick<VaultQuote, 'totalAssets' | 'totalShares'>): number {
const VIRTUAL_SHARES = 1_000_000n;
return Number(q.totalAssets + VIRTUAL_SHARES) / Number(q.totalShares + VIRTUAL_SHARES);
}
/**
* Deposit headroom in native units — the binding constraint of the vault-side caps.
*
* The vault cap is enforced as total_assets + amount <= vault_cap; a market cap as
* current_balance + amount <= cap. A value of 0 denotes no limit in either case. Supply
* `currentBalance` from a synchronized get_market_info read for the market a deposit is routed
* into.
*
* This is NOT the full bound. NAVI applies a third constraint, the reserve's supply_cap_ceiling,
* which is shared with every other participant in that lending market and can be reached while
* both vault-side caps still have headroom; exceeding it aborts with 1604 (§3.3). Reading it
* requires querying lending_core storage for the asset, which is outside this module's scope.
* A caller that presents headroom to a user must take the minimum of this value and the reserve
* headroom.
*/
export function vaultSideDepositHeadroom(
layout: VaultLayout,
q: VaultQuote,
target?: { poolId: string; currentBalance: bigint },
): bigint {
const vaultRoom = layout.vaultCap === 0n ? U64_MAX : max0(layout.vaultCap - q.totalAssets);
if (!target) return vaultRoom;
const m = layout.markets.find((x) => x.poolId === target.poolId);
if (!m || m.cap === 0n) return vaultRoom;
const marketRoom = max0(m.cap - target.currentBalance);
return vaultRoom < marketRoom ? vaultRoom : marketRoom;
}
function max0(x: bigint): bigint {
return x > 0n ? x : 0n;
}
/** Convert a WAD-scaled rate to a percentage. */
export function wadToPercent(wad: bigint): number {
return Number((wad * 10_000n) / WAD) / 100;
}