@augustdigital/sdk 8.7.2 → 8.9.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.
@@ -55,7 +55,60 @@ function alertMissingSubgraphOnce(args) {
55
55
  function needsMonadSuffix(chainId, symbol) {
56
56
  return chainId === 143 && symbol.toLowerCase() === 'earnausd';
57
57
  }
58
- function transformUserHistory(data, chainId, decimals, poolAddress) {
58
+ /**
59
+ * Read the decimals of every distinct deposit asset in a batch of deposit
60
+ * rows, keyed by lowercased token address.
61
+ *
62
+ * Pre-deposit / evm-2 vaults accept multiple deposit assets whose decimals can
63
+ * differ from the vault's own (e.g. RLUSD at 18 deposited into a 6-decimal
64
+ * sentUSD vault). `transformUserHistory` must normalize each deposit against
65
+ * its own asset's decimals rather than the vault's, or an 18-decimal amount
66
+ * normalized at 6 decimals renders ~1e12× too large (a 0.5 deposit shows as
67
+ * "500B"). `getDecimals` is cached and in-flight-deduped, and the distinct-asset
68
+ * set is tiny (typically 1-3), so this is at most a handful of RPC reads.
69
+ *
70
+ * Native-token deposits carry a sentinel `assetIn` — either the zero address or
71
+ * {@link NATIVE_ADDRESS} — that has no on-chain `decimals()`. These are mapped
72
+ * directly to {@link EVM_NATIVE_DECIMALS} (18 on every supported EVM chain)
73
+ * instead of being read. Without this guard `getDecimals(ZeroAddress)` returns
74
+ * `0`, which the caller's `?? decimals` fallback cannot override (0 is not
75
+ * nullish), overstating a native deposit ~1e18×; and `getDecimals(NATIVE_ADDRESS)`
76
+ * reverts, silently dropping to the vault's decimals which may differ.
77
+ *
78
+ * Only successfully-read decimals are entered in the map; a non-native asset
79
+ * whose `decimals()` read fails is omitted so the caller falls back to the
80
+ * vault's decimals. This also lets the vault-decimals read run in parallel with
81
+ * this one (no fallback value is needed up front).
82
+ *
83
+ * @param provider - EVM contract runner used to read `decimals()`.
84
+ * @param deposits - Deposit rows from the subgraph; `assetIn` may be absent.
85
+ * @returns Map of lowercased asset address to decimals (native sentinels and
86
+ * successful reads only).
87
+ */
88
+ async function buildDepositAssetDecimals(provider, deposits) {
89
+ const map = new Map();
90
+ // Lowercased native-token sentinels: no ERC-20 `decimals()` exists to read.
91
+ const nativeSentinels = new Set([
92
+ ethers_1.ZeroAddress.toLowerCase(),
93
+ core_1.NATIVE_ADDRESS.toLowerCase(),
94
+ ]);
95
+ const unique = new Set();
96
+ for (const d of deposits ?? []) {
97
+ if (d?.assetIn)
98
+ unique.add(d.assetIn.toLowerCase());
99
+ }
100
+ await Promise.all([...unique].map(async (addr) => {
101
+ if (nativeSentinels.has(addr)) {
102
+ map.set(addr, core_1.EVM_NATIVE_DECIMALS);
103
+ return;
104
+ }
105
+ const dec = await (0, core_1.getDecimals)(provider, addr, false);
106
+ if (typeof dec === 'number')
107
+ map.set(addr, dec);
108
+ }));
109
+ return map;
110
+ }
111
+ function transformUserHistory(data, chainId, decimals, poolAddress, assetDecimals) {
59
112
  //ok to return dupes even though withdraws will return dupe because we parse out duplicate txn hash on the FE
60
113
  return [
61
114
  ...(data.withdraws?.map((item) => ({
@@ -92,23 +145,33 @@ function transformUserHistory(data, chainId, decimals, poolAddress) {
92
145
  timestamp: item.timestamp_,
93
146
  decimals: decimals,
94
147
  })) || []),
95
- ...(data.deposits?.map((item) => ({
96
- ...item,
97
- contractId_: item.contractId_ || poolAddress,
98
- chainId: chainId,
99
- type: 'deposit',
100
- address: item?.sender || item?.senderAddr,
101
- amount: item?.assets || item?.amountIn,
102
- transactionHash: item.transactionHash_,
103
- timestamp: item.timestamp_,
104
- decimals: decimals,
105
- })) || []),
148
+ ...(data.deposits?.map((item) => {
149
+ // Pair the decimals to the amount's denomination. `assets` (evm-1) is
150
+ // already in the vault's underlying, so it keeps the vault decimals.
151
+ // Only `amountIn` (evm-2 / pre-deposit) is denominated in `assetIn`,
152
+ // which may differ from the vault (e.g. RLUSD 18 → sentUSD 6) and would
153
+ // otherwise overstate the amount ~1e12×. Using the same source for both
154
+ // avoids a denomination/decimals mismatch, and the truthy `assetIn`
155
+ // guard drops empty-string addresses back to the vault decimals.
156
+ const assetKey = !item?.assets && item.assetIn ? item.assetIn.toLowerCase() : undefined;
157
+ return {
158
+ ...item,
159
+ contractId_: item.contractId_ || poolAddress,
160
+ chainId: chainId,
161
+ type: 'deposit',
162
+ address: item?.sender || item?.senderAddr,
163
+ amount: item?.assets || item?.amountIn,
164
+ transactionHash: item.transactionHash_,
165
+ timestamp: item.timestamp_,
166
+ decimals: (assetKey ? assetDecimals?.get(assetKey) : undefined) ?? decimals,
167
+ };
168
+ }) || []),
106
169
  ];
107
170
  }
108
- function sortUserHistory(data, chainId, decimals, poolAddress) {
171
+ function sortUserHistory(data, chainId, decimals, poolAddress, assetDecimals) {
109
172
  if (!(data && chainId && decimals))
110
173
  return [];
111
- return transformUserHistory(data, chainId, decimals, poolAddress).sort((a, b) => Number(a.timestamp_) - Number(b.timestamp_));
174
+ return transformUserHistory(data, chainId, decimals, poolAddress, assetDecimals).sort((a, b) => Number(a.timestamp_) - Number(b.timestamp_));
112
175
  }
113
176
  // queries
114
177
  const WITHDRAWALS_REQUESTED_QUERY_PROPS = `
@@ -707,9 +770,12 @@ async function getSubgraphUserHistory(user, provider, pool, slackWebookUrl = sla
707
770
  return requests;
708
771
  }
709
772
  const json = (await result.json());
710
- // Format data
711
- const decimals = await (0, core_1.getDecimals)(provider, pool);
712
- const formattedRequests = sortUserHistory(json.data, chainId, decimals, pool);
773
+ // Format data — vault decimals and per-asset decimals are independent reads.
774
+ const [decimals, assetDecimals] = await Promise.all([
775
+ (0, core_1.getDecimals)(provider, pool),
776
+ buildDepositAssetDecimals(provider, json.data?.deposits),
777
+ ]);
778
+ const formattedRequests = sortUserHistory(json.data, chainId, decimals, pool, assetDecimals);
713
779
  return formattedRequests;
714
780
  }
715
781
  catch (e) {
@@ -857,10 +923,13 @@ async function getSubgraphVaultHistory(provider, pool, slackWebookUrl = slack_1.
857
923
  break;
858
924
  skip += PAGE_SIZE;
859
925
  }
860
- // Format data
926
+ // Format data — vault decimals and per-asset decimals are independent reads.
861
927
  const chainId = await (0, core_1.getChainId)(provider);
862
- const decimals = await (0, core_1.getDecimals)(provider, pool);
863
- const formattedRequests = sortUserHistory(accumulated, chainId, decimals, pool);
928
+ const [decimals, assetDecimals] = await Promise.all([
929
+ (0, core_1.getDecimals)(provider, pool),
930
+ buildDepositAssetDecimals(provider, accumulated?.deposits),
931
+ ]);
932
+ const formattedRequests = sortUserHistory(accumulated, chainId, decimals, pool, assetDecimals);
864
933
  return formattedRequests;
865
934
  }
866
935
  catch (e) {
@@ -0,0 +1,280 @@
1
+ import type { IAddress } from './web3';
2
+ /**
3
+ * A whitelisted token as embedded in loan-book records by the backend
4
+ * `WhitelistedTokenModel` schema. `chain` is the numeric August chain id
5
+ * (backend `Chain` IntEnum value, e.g. `1` for Ethereum mainnet).
6
+ */
7
+ export interface IWhitelistedToken {
8
+ chain: number;
9
+ name: string;
10
+ token_type: string;
11
+ address: IAddress;
12
+ decimals: number;
13
+ symbol: string;
14
+ discount_factor: number;
15
+ img_url: string | null;
16
+ price: number | null;
17
+ }
18
+ /**
19
+ * The amount and due date of a loan's next scheduled payment, as serialized
20
+ * by the backend `UpcomingPayment` schema. `due_date` is an ISO-8601 datetime
21
+ * string.
22
+ */
23
+ export interface ILoanUpcomingPayment {
24
+ amount: number;
25
+ due_date: string;
26
+ }
27
+ /**
28
+ * One loan-book entry from the admin loan-book endpoints (backend
29
+ * `LoanBookInfo` schema). Amounts are decimal-adjusted floats; monetary
30
+ * fields are denominated in the loan's principal token. `deployed_date` is an
31
+ * ISO-8601 datetime string; `state` is the backend `LoanStateStr` value
32
+ * (e.g. `"ACTIVE"`).
33
+ */
34
+ export interface ILoanBookInfo {
35
+ address: IAddress;
36
+ lender: IAddress;
37
+ borrower: IAddress;
38
+ state: string;
39
+ total_repaid: number;
40
+ principal_token: IWhitelistedToken;
41
+ principal_amount: number;
42
+ interest_amount: number;
43
+ upcoming_payment: ILoanUpcomingPayment;
44
+ apr: number;
45
+ initial_principal_amount: number;
46
+ deployed_date: string;
47
+ payment_interval: number;
48
+ total_interest_payment_fees: number;
49
+ lender_apr: number;
50
+ }
51
+ /**
52
+ * A token's discount-factor ladder from `GET /risk/discount_factors`
53
+ * (backend `DiscountFactorRead` schema). `steps` are ascending notional
54
+ * thresholds (in the token's smallest unit) and `factors` the corresponding
55
+ * ascending haircut multipliers in `[0, 1]`; the two arrays are equal length.
56
+ * `chain` is the numeric August chain id.
57
+ */
58
+ export interface IDiscountFactorLadder {
59
+ steps: number[] | null;
60
+ factors: number[] | null;
61
+ address: IAddress;
62
+ chain: number;
63
+ }
64
+ /**
65
+ * Result of `GET /risk/collateral_excess_or_deficit` (backend
66
+ * `CollateralExcessOrDeficit` schema). A positive value is excess collateral
67
+ * that could be withdrawn; a negative value is the shortfall that must be
68
+ * deposited to reach the target health factor.
69
+ */
70
+ export interface ICollateralExcessOrDeficit {
71
+ amount_usd: number;
72
+ amount_token: number;
73
+ }
74
+ /**
75
+ * Request body for `POST /risk/collateral_simulation` (backend
76
+ * `CollateralSimulation` schema). Chain fields are numeric August chain ids.
77
+ * `collateral_tokens` is a list of `[chain, address]` pairs and
78
+ * `collateral_token_allocation` the matching per-token weights (normalized
79
+ * server-side, so relative magnitudes are what matter). When `on_platform`
80
+ * is `true`, both `loan_redeployed_token_*` fields are required by the
81
+ * backend.
82
+ */
83
+ export interface ICollateralSimulationInput {
84
+ loan_token_chain: number;
85
+ loan_token_address: IAddress;
86
+ loan_amount: number;
87
+ on_platform?: boolean;
88
+ loan_redeployed_token_chain?: number | null;
89
+ loan_redeployed_token_address?: IAddress | null;
90
+ collateral_tokens: [number, IAddress][];
91
+ collateral_token_allocation: number[];
92
+ target_health_factor?: number;
93
+ }
94
+ /**
95
+ * Per-collateral-token breakdown within a collateral simulation (backend
96
+ * `CollateralDetailsResult` schema). `chain` is the numeric August chain id.
97
+ */
98
+ export interface ICollateralDetailsResult {
99
+ chain: number;
100
+ token_address: IAddress;
101
+ price: number;
102
+ allocation: number;
103
+ collateral_value_from_redeployed_loan_usd: number;
104
+ collateral_value_usd: number;
105
+ amount_usd: number;
106
+ amount_token: number;
107
+ effective_discount_factor: number;
108
+ is_top_up: boolean;
109
+ }
110
+ /**
111
+ * Result of `POST /risk/collateral_simulation` (backend
112
+ * `CollateralSimulationResults` schema). `collateral_details` is keyed by
113
+ * `"<symbol>_<chainName>"`.
114
+ */
115
+ export interface ICollateralSimulationResults {
116
+ total_debt_usd: number;
117
+ total_required_collateral_usd: number;
118
+ total_collateral_value_from_redeployed_loan_usd: number;
119
+ health_factor: number;
120
+ collateral_details: Record<string, ICollateralDetailsResult>;
121
+ }
122
+ /**
123
+ * Result of the public `GET /revert_reason` endpoint (backend `RevertResponse`
124
+ * schema) — the decoded failure reasons for a reverted transaction, collected
125
+ * from a `debug_traceTransaction` call tree. All three arrays are empty when
126
+ * no matching signal was found in the trace.
127
+ */
128
+ export interface IRevertReason {
129
+ error_messages: string[];
130
+ revert_reasons: string[];
131
+ universal_subaccount_errors: string[];
132
+ }
133
+ /**
134
+ * One transaction record from `GET /transactions/v2` (backend
135
+ * `TransactionAPIRead` schema). `chain` is the numeric August chain id;
136
+ * `value` is decimal-adjusted; `timestamp` is a Unix epoch (seconds).
137
+ * `from_` mirrors the backend field name (`from` is reserved). Nested
138
+ * `logs` / `transfers` / `function_signature` / `otc_cashflow` are passed
139
+ * through as-is. `transaction_name` is the resolved function name (or the raw
140
+ * selector when unknown).
141
+ */
142
+ export interface ISubaccountTransaction {
143
+ id: string;
144
+ tx_hash: string;
145
+ chain: number;
146
+ from_: IAddress;
147
+ to: IAddress;
148
+ value: number;
149
+ block_number: number;
150
+ timestamp: number;
151
+ selector: string | null;
152
+ logs: unknown[];
153
+ transfers: unknown[];
154
+ function_signature: Record<string, unknown> | null;
155
+ otc_cashflow: Record<string, unknown> | null;
156
+ transaction_name: string | null;
157
+ }
158
+ /**
159
+ * DeBank positions and tokens for a single account (backend
160
+ * `DebankAccountData` schema). `positions`, `app_positions`, and `tokens`
161
+ * are passed through as raw DeBank objects.
162
+ */
163
+ export interface ISubaccountDebankData {
164
+ positions: unknown[];
165
+ app_positions: unknown[];
166
+ tokens: unknown[];
167
+ }
168
+ /**
169
+ * Cross-chain DeBank protocol positions for a subaccount and its associated
170
+ * strategies (backend `SubaccountDebankAccountData` schema). `strategies` is
171
+ * keyed by strategy address. This endpoint is slow (300-second server-side
172
+ * cache) as it fans out across every supported chain.
173
+ */
174
+ export interface ISubaccountDebank {
175
+ subaccount: ISubaccountDebankData;
176
+ strategies: Record<string, ISubaccountDebankData>;
177
+ }
178
+ /**
179
+ * A tracked position from `GET /otc/position` (backend `IPositionRead`
180
+ * schema). `configs` is a free-form JSON object of position-specific
181
+ * settings; `category` is the position category (e.g. `"otc"`).
182
+ */
183
+ export interface IOtcPositionRead {
184
+ id: string;
185
+ slug: string;
186
+ position_class: string | null;
187
+ configs: Record<string, unknown> | null;
188
+ category: string | null;
189
+ position_discount_factor: number | null;
190
+ }
191
+ /**
192
+ * An OTC margin requirement from `GET /otc/margin_requirement` (backend
193
+ * `IOTCMarginRequirementRead` schema) — the margin the `payer` must post to
194
+ * the given counterparty.
195
+ */
196
+ export interface IOtcMarginRequirement {
197
+ otc_counter_party_id: string;
198
+ margin_requirement: number;
199
+ payer: IAddress;
200
+ }
201
+ /**
202
+ * On-chain whitelist status of one subaccount linked to a vault, from
203
+ * `GET /curator/vaults/{vault_address}/whitelist` (backend
204
+ * `WhitelistStatusResponse` schema). EVM vaults only.
205
+ */
206
+ export interface ICuratorWhitelistStatus {
207
+ address: IAddress;
208
+ is_whitelisted: boolean;
209
+ }
210
+ /**
211
+ * One timelock request from `GET /timelock-requests` (backend
212
+ * `ITimelockRequestRead` schema). `chain_id` is the numeric chain id;
213
+ * `status` is one of `"scheduled" | "executed" | "cancelled"`; `params` is a
214
+ * free-form JSON object; datetime fields are ISO-8601 strings.
215
+ */
216
+ export interface ITimelockRequest {
217
+ id: string;
218
+ hash: string;
219
+ vault_address: IAddress;
220
+ timelock_address: IAddress;
221
+ chain_id: number;
222
+ action_id: string;
223
+ params: Record<string, unknown>;
224
+ status: string;
225
+ schedule_tx_hash: string;
226
+ execute_tx_hash: string | null;
227
+ cancel_tx_hash: string | null;
228
+ submitted_by: string | null;
229
+ scheduled_at: string;
230
+ resolved_at: string | null;
231
+ created_at: string | null;
232
+ updated_at: string | null;
233
+ }
234
+ /**
235
+ * Performance-fee computation for a vault from
236
+ * `GET /metrics/vault_performance_fees` (backend `UpshiftVaultPerformanceFees`
237
+ * schema). High/low water marks are share-price levels; `*_datetime` fields
238
+ * are ISO-8601 strings. `calculation_period` is `"YearToDate"` /
239
+ * `"MonthToDate"` (null when a custom date range was supplied).
240
+ */
241
+ export interface IVaultPerformanceFees {
242
+ previous_water_mark: number;
243
+ previous_water_mark_datetime: string;
244
+ last_water_mark: number;
245
+ last_water_mark_datetime: string;
246
+ is_in_drawdown: boolean;
247
+ asset_symbol: string | null;
248
+ total_pnl_in_asset: number;
249
+ total_perf_fees_asset: number;
250
+ calculation_period: string | null;
251
+ annualized_fees_pct: number;
252
+ underlying_asset_vs_native_perf: number | null;
253
+ native_token_symbol: string | null;
254
+ }
255
+ /**
256
+ * One row of a vault's NAV-oracle classification table (backend
257
+ * `OracleClassificationRow` schema) — how a single position/token is priced
258
+ * and its USD value.
259
+ */
260
+ export interface IOracleClassificationRow {
261
+ position: string;
262
+ type: string;
263
+ oracle_source: string;
264
+ usd_value: number;
265
+ }
266
+ /**
267
+ * A vault's NAV-oracle classification from the public
268
+ * `GET /upshift/oracle_classification/{vault_address}` endpoint (backend
269
+ * `OracleClassificationResponse` schema). `warnings` lists tokens that could
270
+ * not be resolved (`"unresolved:<symbol>"`). `snapshot_at` is an ISO-8601
271
+ * datetime string.
272
+ */
273
+ export interface IOracleClassification {
274
+ vault_address: IAddress;
275
+ chain_id: number;
276
+ snapshot_at: string;
277
+ methodology: string;
278
+ rows: IOracleClassificationRow[];
279
+ warnings: string[];
280
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=api.js.map
@@ -9,3 +9,4 @@ export * from './subgraph';
9
9
  export * from './vaults';
10
10
  export * from './points';
11
11
  export * from './sub-accounts';
12
+ export * from './api';
@@ -24,4 +24,5 @@ __exportStar(require("./subgraph"), exports);
24
24
  __exportStar(require("./vaults"), exports);
25
25
  __exportStar(require("./points"), exports);
26
26
  __exportStar(require("./sub-accounts"), exports);
27
+ __exportStar(require("./api"), exports);
27
28
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,40 @@
1
1
  import type { IAddress } from './web3';
2
+ /**
3
+ * Chain record attached to a subaccount directory entry, as serialized by the
4
+ * backend `IChainRead` schema.
5
+ */
6
+ export interface IWSSubaccountListChain {
7
+ id: string;
8
+ chain_id: number;
9
+ name: string;
10
+ }
11
+ /**
12
+ * One subaccount record from the admin-only `GET /subaccount` directory
13
+ * endpoint (backend `ISubaccountRead` schema). Nullable fields are optional
14
+ * metadata the operations team may not have filled in.
15
+ */
16
+ export interface IWSSubaccountListItem {
17
+ id: string;
18
+ user_id: string | null;
19
+ internal_name: string;
20
+ friendly_name: string | null;
21
+ address: IAddress;
22
+ status: string | null;
23
+ subaccount_type: string | null;
24
+ min_health_factor: number | null;
25
+ estimated_apr: number | null;
26
+ notes: string | null;
27
+ proxy_salt: string | null;
28
+ admin_salt: string | null;
29
+ disable_discount_factor: boolean | null;
30
+ turnkey_address: IAddress | null;
31
+ autopay_frequency: string | null;
32
+ implementation: string | null;
33
+ variant: string | null;
34
+ default_fee_rate_in_bips: number | null;
35
+ wallet_role: string | null;
36
+ chains: IWSSubaccountListChain[];
37
+ }
2
38
  export interface IWSSubAccountHealthFactor {
3
39
  id: IAddress;
4
40
  datetime: string;
@@ -35,6 +35,14 @@ export interface ISubgraphDeposit extends ISubgraphBase {
35
35
  owner: IAddress;
36
36
  senderAddr?: IAddress;
37
37
  amountIn?: string;
38
+ /**
39
+ * Deposit asset token address (evm-2 / pre-deposit vaults). The deposited
40
+ * asset can differ from the vault's underlying and carry different decimals
41
+ * (e.g. RLUSD at 18 into a 6-decimal sentUSD vault), so `amountIn` must be
42
+ * normalized against this token's decimals, not the vault's. Absent for
43
+ * single-asset vaults.
44
+ */
45
+ assetIn?: IAddress;
38
46
  }
39
47
  export interface ISubgraphWithdrawRequest extends ISubgraphBase {
40
48
  day: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@augustdigital/sdk",
3
- "version": "8.7.2",
3
+ "version": "8.9.0",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/sdk.d.ts",
6
6
  "keywords": [