@define-kit/position-modules
v0.1.2
Published
Typed protocol adapters for fetching, snapshotting, and evaluating DeFi positions.
Maintainers
Readme
@define-kit/position-modules
Typed protocol adapters for fetching position data, building serializable snapshots, and evaluating position state.
Installation
npm install @define-kit/position-modulesWhat the package provides
The package defines a common execution model for protocol-specific position analysis:
fetch → snapshot → evaluate → runEvery run call returns both the snapshot used for evaluation and the resulting interpretation:
{
snapshot,
result,
}This makes it possible to persist a snapshot, evaluate it again without another RPC request, and test evaluation logic with fixtures.
For the Aave V3 adapter, the snapshot also includes blockInfo so consumers can tell which chain block the observed state came from.
Current adapters
| Module | Adapter key | Status |
| --- | --- | --- |
| Health factor | health-factor:aave-v3 | Implemented |
| Maturity date | maturity-date | Scaffold; returns not_implemented |
The current health-factor evaluation observes and normalizes an Aave V3 position, then assigns a deterministic status: healthy, warning, danger, or liquidatable. Positions without debt return not_applicable; incomplete snapshots where health factor is expected return not_available. Applications remain responsible for their own alert thresholds and notification rules.
Aave V3 quick start
import {
POSITION_ADAPTER_KEYS,
healthFactor,
} from '@define-kit/position-modules';
const output = await healthFactor.run({
adapterKey: POSITION_ADAPTER_KEYS.healthFactorAaveV3,
input: {
address: '0xYourUserAddress',
chainIdOrig: 1,
contract: '0xAavePoolAddress',
marketKey: 'aave-v3-ethereum',
poolAddressesProviderContract: '0xPoolAddressesProviderAddress',
protocolKey: 'aave-v3',
rpcUrls: ['https://your-rpc.example'],
uiPoolDataProviderContract: '0xUiPoolDataProviderAddress',
},
});
console.log(output.snapshot);
console.log(output.snapshot.blockInfo);
console.log(output.result);All supplied contract addresses must belong to the same Aave V3 deployment and chain.
Result semantics
For an evaluated Aave V3 position:
console.log(output.result.evaluation.healthFactor);
console.log(output.result.evaluation.hasDebt);
console.log(output.result.evaluation.isActive);
console.log(output.result.evaluation.healthFactorApplicable);
console.log(output.result.evaluation.suppliedAssetCount);
console.log(output.result.evaluation.borrowedAssetCount);
console.log(output.result.status);Aave health factor is meaningful only when the account has debt. Use healthFactorApplicable instead of treating a missing or non-applicable health factor as an unhealthy position.
evaluation.isActive means the current snapshot has any non-zero supplied balance or variable debt. It does not distinguish between "user never opened a position" and "user fully closed a position" because that would require historical data outside the snapshot.
status is the deterministic current risk classification derived only from the current snapshot.
For the current Aave V3 adapter, run() either returns an evaluated result or throws on fetch failure. Within a successful evaluation, status: 'not_available' is a technical fallback for malformed or incomplete snapshots where health factor should be applicable but is missing.
The result also contains a signals array with explainable machine-readable facts derived from the same snapshot.
Data read by the Aave V3 adapter
The adapter reads Aave and ERC-20 contracts directly to obtain:
- total collateral;
- total debt;
- available borrowing capacity;
- current liquidation threshold;
- loan-to-value ratio;
- Aave-calculated health factor;
- user eMode category;
- supplied reserves;
- variable-debt reserves;
- reserve indexes;
- token symbols, names, and decimals.
Current balances are derived from Aave scaled balances and current reserve indexes. Numeric protocol values are retained as decimal strings so consumers do not lose integer precision.
Formatting for display
Fetching and evaluation preserve raw protocol values. Use the formatter when human-readable output is needed:
import {
formatHealthFactorAaveV3Result,
} from '@define-kit/position-modules';
const formatted = formatHealthFactorAaveV3Result({
result: output.result,
});
console.log(formatted.healthFactorDisplay);
console.log(formatted.currentLiquidationThresholdDisplay);
console.log(formatted.summary);Formatting is intentionally separate from evaluation so applications can use raw values for persistence and their own presentation rules.
RPC behavior
Pass one or more RPC URLs through rpcUrls:
rpcUrls: [
'https://primary-rpc.example',
'https://fallback-rpc.example',
]When multiple URLs are provided, the adapter creates a viem fallback transport. When rpcUrls is omitted, it uses the default HTTP RPC URLs from the matching viem chain definition.
Dedicated endpoints are recommended for production workloads because public endpoints can be rate-limited or unavailable.
The package does not persist RPC health, manage cooldowns, schedule checks, or select endpoints from an application database.
Lower-level API
The facade is the simplest entry point:
healthFactor.run(...)Lower-level functions are also exported:
import {
buildHealthFactorAaveV3Snapshot,
evaluateHealthFactorAaveV3Snapshot,
fetchHealthFactorAaveV3PositionData,
runHealthFactorAaveV3PositionModule,
} from '@define-kit/position-modules';For example, an existing snapshot can be evaluated without network access:
const result = evaluateHealthFactorAaveV3Snapshot(snapshot);Module contract
A position module implements the following shape:
interface PositionModuleT<TInput, TSnapshot, TResult> {
adapterKey: PositionAdapterKeyT;
moduleKey: PositionModuleKeyT;
evaluate(snapshot: TSnapshot): TResult | Promise<TResult>;
run(params: {
input: TInput;
}): Promise<{
snapshot: TSnapshot;
result: TResult;
}>;
}Module categories and concrete adapters are identified by:
POSITION_MODULE_KEYS
POSITION_ADAPTER_KEYSExecution stages
Fetch
Reads protocol state. Network access belongs in this stage.
Snapshot
Combines the module input and fetched data into an explicit serializable shape.
Evaluate
Interprets only the supplied snapshot. Evaluation should remain deterministic and free of RPC, persistence, and notification side effects.
Run
Coordinates fetch, snapshot construction, and evaluation, then returns { snapshot, result }.
Architectural boundary
This package owns:
- protocol-facing reads;
- module-specific normalization;
- snapshot construction;
- deterministic snapshot evaluation;
- typed module results.
This package does not own:
- cron jobs or schedulers;
- databases or historical state;
- previous-versus-current comparison;
- user-configured alert thresholds;
- notification delivery;
- NestJS integration;
- application-owned contract discovery;
- wallet signing.
Maturity-date scaffold
The exported maturity-date facade currently exists only as an explicit scaffold:
import {
POSITION_ADAPTER_KEYS,
maturityDate,
} from '@define-kit/position-modules';
const output = await maturityDate.run({
adapterKey: POSITION_ADAPTER_KEYS.maturityDate,
input: {
address: '0xYourUserAddress',
chainIdOrig: 1,
contract: '0xProtocolContract',
protocolKey: 'example-protocol',
},
});
console.log(output.result);
// { status: 'not_implemented', reason: 'maturity_date_module_not_implemented' }Do not use this adapter as a source of maturity information until a protocol-specific implementation is added.
Development
From the repository root:
yarn nx build position-modules
yarn nx test position-modules
yarn nx typecheck position-modules
yarn nx lint position-modulesEvaluation tests should normally use snapshot fixtures and avoid live RPC requests.
Runtime and packaging
- TypeScript
viemprotocol reads- ESM and CommonJS builds
- TypeScript declarations
- Node.js test environment
- no wallet private key required
Versioning
The package is below 1.0.0, so its public API may change while the module contracts stabilize. Pin an exact version for production-sensitive integrations.
License
MIT
