@metamask-previews/money-account-api-data-service 0.1.0-preview-e196c24cd → 0.1.0-preview-8fd5dfabc

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/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Added
11
+
12
+ - Added optional `trace` callback to `MoneyAccountApiDataService` constructor for network request tracing ([#TBD](https://github.com/MetaMask/core/pull/TBD))
13
+ - All HTTP calls (`fetchPositions`, `fetchInterest`, `fetchHistory`, `fetchRateHistory`) emit best-effort backdated traces with `startTime`, `success`, and `errorName` attributes
14
+ - Tracing is isolated from fetch/retry logic; trace failures do not impact queries
15
+
16
+ ### Fixed
17
+
18
+ - Fixed `fetchPositions` struct validation failing when the API returns the `balance` field ([#TBD](https://github.com/MetaMask/core/pull/TBD))
19
+
10
20
  ## [0.1.0]
11
21
 
12
22
  ### Added
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uFAA8E;AAArE,4IAAA,0BAA0B,OAAA;AA8BnC,6CAAkC;AAAzB,gGAAA,GAAG,OAAA;AACZ,uCAAkE;AAAzD,gIAAA,sCAAsC,OAAA","sourcesContent":["export { MoneyAccountApiDataService } from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceActions,\n MoneyAccountApiDataServiceEvents,\n MoneyAccountApiDataServiceMessenger,\n} from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceFetchPositionsAction,\n MoneyAccountApiDataServiceFetchInterestAction,\n MoneyAccountApiDataServiceFetchHistoryAction,\n MoneyAccountApiDataServiceFetchRateHistoryAction,\n} from './money-account-api-data-service-method-action-types';\nexport type {\n PositionResponse,\n InterestResponse,\n HistoryResponse,\n RateHistoryResponse,\n VaultPosition,\n CashFlowEntry,\n RateHistoryEntry,\n DataFreshness,\n CashFlowType,\n CashFlowSource,\n} from './response.types';\nexport type {\n InterestWindow,\n InterestOptions,\n HistoryOptions,\n RateHistoryOptions,\n} from './types';\nexport { Env } from './constants';\nexport { MoneyAccountApiResponseValidationError } from './errors';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uFAA8E;AAArE,4IAAA,0BAA0B,OAAA;AAkCnC,6CAAkC;AAAzB,gGAAA,GAAG,OAAA;AACZ,uCAAkE;AAAzD,gIAAA,sCAAsC,OAAA","sourcesContent":["export { MoneyAccountApiDataService } from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceActions,\n MoneyAccountApiDataServiceEvents,\n MoneyAccountApiDataServiceMessenger,\n MoneyAccountApiDataServiceOptions,\n MoneyAccountApiDataServiceTraceCallback,\n MoneyAccountApiDataServiceTraceRequest,\n} from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceFetchPositionsAction,\n MoneyAccountApiDataServiceFetchInterestAction,\n MoneyAccountApiDataServiceFetchHistoryAction,\n MoneyAccountApiDataServiceFetchRateHistoryAction,\n} from './money-account-api-data-service-method-action-types';\nexport type {\n Balance,\n PositionResponse,\n InterestResponse,\n HistoryResponse,\n RateHistoryResponse,\n VaultPosition,\n CashFlowEntry,\n RateHistoryEntry,\n DataFreshness,\n CashFlowType,\n CashFlowSource,\n} from './response.types';\nexport type {\n InterestWindow,\n InterestOptions,\n HistoryOptions,\n RateHistoryOptions,\n} from './types';\nexport { Env } from './constants';\nexport { MoneyAccountApiResponseValidationError } from './errors';\n"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { MoneyAccountApiDataService } from "./money-account-api-data-service.cjs";
2
- export type { MoneyAccountApiDataServiceActions, MoneyAccountApiDataServiceEvents, MoneyAccountApiDataServiceMessenger, } from "./money-account-api-data-service.cjs";
2
+ export type { MoneyAccountApiDataServiceActions, MoneyAccountApiDataServiceEvents, MoneyAccountApiDataServiceMessenger, MoneyAccountApiDataServiceOptions, MoneyAccountApiDataServiceTraceCallback, MoneyAccountApiDataServiceTraceRequest, } from "./money-account-api-data-service.cjs";
3
3
  export type { MoneyAccountApiDataServiceFetchPositionsAction, MoneyAccountApiDataServiceFetchInterestAction, MoneyAccountApiDataServiceFetchHistoryAction, MoneyAccountApiDataServiceFetchRateHistoryAction, } from "./money-account-api-data-service-method-action-types.cjs";
4
- export type { PositionResponse, InterestResponse, HistoryResponse, RateHistoryResponse, VaultPosition, CashFlowEntry, RateHistoryEntry, DataFreshness, CashFlowType, CashFlowSource, } from "./response.types.cjs";
4
+ export type { Balance, PositionResponse, InterestResponse, HistoryResponse, RateHistoryResponse, VaultPosition, CashFlowEntry, RateHistoryEntry, DataFreshness, CashFlowType, CashFlowSource, } from "./response.types.cjs";
5
5
  export type { InterestWindow, InterestOptions, HistoryOptions, RateHistoryOptions, } from "./types.cjs";
6
6
  export { Env } from "./constants.cjs";
7
7
  export { MoneyAccountApiResponseValidationError } from "./errors.cjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AAC9E,YAAY,EACV,iCAAiC,EACjC,gCAAgC,EAChC,mCAAmC,GACpC,6CAAyC;AAC1C,YAAY,EACV,8CAA8C,EAC9C,6CAA6C,EAC7C,4CAA4C,EAC5C,gDAAgD,GACjD,iEAA6D;AAC9D,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,cAAc,GACf,6BAAyB;AAC1B,YAAY,EACV,cAAc,EACd,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,oBAAgB;AACjB,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AAC9E,YAAY,EACV,iCAAiC,EACjC,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,uCAAuC,EACvC,sCAAsC,GACvC,6CAAyC;AAC1C,YAAY,EACV,8CAA8C,EAC9C,6CAA6C,EAC7C,4CAA4C,EAC5C,gDAAgD,GACjD,iEAA6D;AAC9D,YAAY,EACV,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,cAAc,GACf,6BAAyB;AAC1B,YAAY,EACV,cAAc,EACd,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,oBAAgB;AACjB,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB"}
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { MoneyAccountApiDataService } from "./money-account-api-data-service.mjs";
2
- export type { MoneyAccountApiDataServiceActions, MoneyAccountApiDataServiceEvents, MoneyAccountApiDataServiceMessenger, } from "./money-account-api-data-service.mjs";
2
+ export type { MoneyAccountApiDataServiceActions, MoneyAccountApiDataServiceEvents, MoneyAccountApiDataServiceMessenger, MoneyAccountApiDataServiceOptions, MoneyAccountApiDataServiceTraceCallback, MoneyAccountApiDataServiceTraceRequest, } from "./money-account-api-data-service.mjs";
3
3
  export type { MoneyAccountApiDataServiceFetchPositionsAction, MoneyAccountApiDataServiceFetchInterestAction, MoneyAccountApiDataServiceFetchHistoryAction, MoneyAccountApiDataServiceFetchRateHistoryAction, } from "./money-account-api-data-service-method-action-types.mjs";
4
- export type { PositionResponse, InterestResponse, HistoryResponse, RateHistoryResponse, VaultPosition, CashFlowEntry, RateHistoryEntry, DataFreshness, CashFlowType, CashFlowSource, } from "./response.types.mjs";
4
+ export type { Balance, PositionResponse, InterestResponse, HistoryResponse, RateHistoryResponse, VaultPosition, CashFlowEntry, RateHistoryEntry, DataFreshness, CashFlowType, CashFlowSource, } from "./response.types.mjs";
5
5
  export type { InterestWindow, InterestOptions, HistoryOptions, RateHistoryOptions, } from "./types.mjs";
6
6
  export { Env } from "./constants.mjs";
7
7
  export { MoneyAccountApiResponseValidationError } from "./errors.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AAC9E,YAAY,EACV,iCAAiC,EACjC,gCAAgC,EAChC,mCAAmC,GACpC,6CAAyC;AAC1C,YAAY,EACV,8CAA8C,EAC9C,6CAA6C,EAC7C,4CAA4C,EAC5C,gDAAgD,GACjD,iEAA6D;AAC9D,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,cAAc,GACf,6BAAyB;AAC1B,YAAY,EACV,cAAc,EACd,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,oBAAgB;AACjB,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AAC9E,YAAY,EACV,iCAAiC,EACjC,gCAAgC,EAChC,mCAAmC,EACnC,iCAAiC,EACjC,uCAAuC,EACvC,sCAAsC,GACvC,6CAAyC;AAC1C,YAAY,EACV,8CAA8C,EAC9C,6CAA6C,EAC7C,4CAA4C,EAC5C,gDAAgD,GACjD,iEAA6D;AAC9D,YAAY,EACV,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,cAAc,GACf,6BAAyB;AAC1B,YAAY,EACV,cAAc,EACd,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,oBAAgB;AACjB,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AA8B9E,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB","sourcesContent":["export { MoneyAccountApiDataService } from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceActions,\n MoneyAccountApiDataServiceEvents,\n MoneyAccountApiDataServiceMessenger,\n} from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceFetchPositionsAction,\n MoneyAccountApiDataServiceFetchInterestAction,\n MoneyAccountApiDataServiceFetchHistoryAction,\n MoneyAccountApiDataServiceFetchRateHistoryAction,\n} from './money-account-api-data-service-method-action-types';\nexport type {\n PositionResponse,\n InterestResponse,\n HistoryResponse,\n RateHistoryResponse,\n VaultPosition,\n CashFlowEntry,\n RateHistoryEntry,\n DataFreshness,\n CashFlowType,\n CashFlowSource,\n} from './response.types';\nexport type {\n InterestWindow,\n InterestOptions,\n HistoryOptions,\n RateHistoryOptions,\n} from './types';\nexport { Env } from './constants';\nexport { MoneyAccountApiResponseValidationError } from './errors';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,6CAAyC;AAkC9E,OAAO,EAAE,GAAG,EAAE,wBAAoB;AAClC,OAAO,EAAE,sCAAsC,EAAE,qBAAiB","sourcesContent":["export { MoneyAccountApiDataService } from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceActions,\n MoneyAccountApiDataServiceEvents,\n MoneyAccountApiDataServiceMessenger,\n MoneyAccountApiDataServiceOptions,\n MoneyAccountApiDataServiceTraceCallback,\n MoneyAccountApiDataServiceTraceRequest,\n} from './money-account-api-data-service';\nexport type {\n MoneyAccountApiDataServiceFetchPositionsAction,\n MoneyAccountApiDataServiceFetchInterestAction,\n MoneyAccountApiDataServiceFetchHistoryAction,\n MoneyAccountApiDataServiceFetchRateHistoryAction,\n} from './money-account-api-data-service-method-action-types';\nexport type {\n Balance,\n PositionResponse,\n InterestResponse,\n HistoryResponse,\n RateHistoryResponse,\n VaultPosition,\n CashFlowEntry,\n RateHistoryEntry,\n DataFreshness,\n CashFlowType,\n CashFlowSource,\n} from './response.types';\nexport type {\n InterestWindow,\n InterestOptions,\n HistoryOptions,\n RateHistoryOptions,\n} from './types';\nexport { Env } from './constants';\nexport { MoneyAccountApiResponseValidationError } from './errors';\n"]}
@@ -10,9 +10,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _MoneyAccountApiDataService_baseUrl;
13
+ var _MoneyAccountApiDataService_instances, _MoneyAccountApiDataService_baseUrl, _MoneyAccountApiDataService_trace, _MoneyAccountApiDataService_traceNetworkRequest;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.MoneyAccountApiDataService = exports.serviceName = void 0;
15
+ exports.MoneyAccountApiDataService = exports.TRACES = exports.serviceName = void 0;
16
16
  const base_data_service_1 = require("@metamask/base-data-service");
17
17
  const controller_utils_1 = require("@metamask/controller-utils");
18
18
  const superstruct_1 = require("@metamask/superstruct");
@@ -27,6 +27,13 @@ const structs_1 = require("./structs.cjs");
27
27
  */
28
28
  exports.serviceName = 'MoneyAccountApiDataService';
29
29
  const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, exports.serviceName);
30
+ const traceLogger = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'trace');
31
+ exports.TRACES = {
32
+ POSITIONS_API: 'Money Account API Fetch Positions',
33
+ INTEREST_API: 'Money Account API Fetch Interest',
34
+ HISTORY_API: 'Money Account API Fetch History',
35
+ RATE_HISTORY_API: 'Money Account API Fetch Rate History',
36
+ };
30
37
  // === MESSENGER ===
31
38
  const MESSENGER_EXPOSED_METHODS = [
32
39
  'fetchPositions',
@@ -34,7 +41,6 @@ const MESSENGER_EXPOSED_METHODS = [
34
41
  'fetchHistory',
35
42
  'fetchRateHistory',
36
43
  ];
37
- // === SERVICE DEFINITION ===
38
44
  /**
39
45
  * Data service responsible for fetching positions, interest, cash-flow
40
46
  * history, and vault rate history from the Money Account APY Tracking API.
@@ -43,14 +49,15 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
43
49
  /**
44
50
  * Constructs a new MoneyAccountApiDataService.
45
51
  *
46
- * @param args - The constructor arguments.
47
- * @param args.messenger - The messenger suited for this service.
48
- * @param args.env - The target environment. Defaults to production.
49
- * @param args.queryClientConfig - Configuration for the underlying TanStack
50
- * Query client.
51
- * @param args.policyOptions - Options to pass to `createServicePolicy`.
52
+ * @param options - The constructor arguments.
53
+ * @param options.messenger - The messenger suited for this service.
54
+ * @param options.env - The target environment. Defaults to production.
55
+ * @param options.queryClientConfig - Configuration for the underlying
56
+ * TanStack Query client.
57
+ * @param options.policyOptions - Options to pass to `createServicePolicy`.
58
+ * @param options.trace - Optional callback to trace network requests.
52
59
  */
53
- constructor({ messenger, env = constants_1.Env.PRD, queryClientConfig = {}, policyOptions = {}, }) {
60
+ constructor({ messenger, env = constants_1.Env.PRD, queryClientConfig = {}, policyOptions = {}, trace, }) {
54
61
  super({
55
62
  name: exports.serviceName,
56
63
  messenger,
@@ -60,8 +67,14 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
60
67
  ...policyOptions,
61
68
  },
62
69
  });
70
+ _MoneyAccountApiDataService_instances.add(this);
63
71
  _MoneyAccountApiDataService_baseUrl.set(this, void 0);
72
+ _MoneyAccountApiDataService_trace.set(this, void 0);
64
73
  __classPrivateFieldSet(this, _MoneyAccountApiDataService_baseUrl, constants_1.MONEY_ACCOUNT_API_URL_MAP[env], "f");
74
+ __classPrivateFieldSet(this, _MoneyAccountApiDataService_trace, trace ??
75
+ (async (_request, fn) => {
76
+ return await Promise.resolve(fn?.());
77
+ }), "f");
65
78
  this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
66
79
  log('Initialized', { env, baseUrl: __classPrivateFieldGet(this, _MoneyAccountApiDataService_baseUrl, "f") });
67
80
  }
@@ -77,16 +90,21 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
77
90
  queryKey: [`${this.name}:fetchPositions`, address.toLowerCase()],
78
91
  staleTime: constants_1.DEFAULT_STALE_TIME_MS,
79
92
  queryFn: async () => {
80
- const response = await fetch(url);
81
- if (!response.ok) {
82
- throw new controller_utils_1.HttpError(response.status, `Money Account API positions request failed with status '${response.status}'`);
83
- }
84
- const json = await response.json();
85
- const [error, validated] = (0, superstruct_1.validate)(json, structs_1.PositionResponseStruct);
86
- if (error) {
87
- throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from positions endpoint: ${error.message}`);
88
- }
89
- return validated;
93
+ return __classPrivateFieldGet(this, _MoneyAccountApiDataService_instances, "m", _MoneyAccountApiDataService_traceNetworkRequest).call(this, {
94
+ name: exports.TRACES.POSITIONS_API,
95
+ data: { operation: 'fetchPositions' },
96
+ }, async () => {
97
+ const response = await fetch(url);
98
+ if (!response.ok) {
99
+ throw new controller_utils_1.HttpError(response.status, `Money Account API positions request failed with status '${response.status}'`);
100
+ }
101
+ const json = await response.json();
102
+ const [error, validated] = (0, superstruct_1.validate)(json, structs_1.PositionResponseStruct);
103
+ if (error) {
104
+ throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from positions endpoint: ${error.message}`);
105
+ }
106
+ return validated;
107
+ });
90
108
  },
91
109
  });
92
110
  }
@@ -115,16 +133,21 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
115
133
  ],
116
134
  staleTime: constants_1.DEFAULT_STALE_TIME_MS,
117
135
  queryFn: async () => {
118
- const response = await fetch(url);
119
- if (!response.ok) {
120
- throw new controller_utils_1.HttpError(response.status, `Money Account API interest request failed with status '${response.status}'`);
121
- }
122
- const json = await response.json();
123
- const [error, validated] = (0, superstruct_1.validate)(json, structs_1.InterestResponseStruct);
124
- if (error) {
125
- throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from interest endpoint: ${error.message}`);
126
- }
127
- return validated;
136
+ return __classPrivateFieldGet(this, _MoneyAccountApiDataService_instances, "m", _MoneyAccountApiDataService_traceNetworkRequest).call(this, {
137
+ name: exports.TRACES.INTEREST_API,
138
+ data: { operation: 'fetchInterest' },
139
+ }, async () => {
140
+ const response = await fetch(url);
141
+ if (!response.ok) {
142
+ throw new controller_utils_1.HttpError(response.status, `Money Account API interest request failed with status '${response.status}'`);
143
+ }
144
+ const json = await response.json();
145
+ const [error, validated] = (0, superstruct_1.validate)(json, structs_1.InterestResponseStruct);
146
+ if (error) {
147
+ throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from interest endpoint: ${error.message}`);
148
+ }
149
+ return validated;
150
+ });
128
151
  },
129
152
  });
130
153
  }
@@ -168,16 +191,21 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
168
191
  if (options?.limit !== undefined) {
169
192
  url.searchParams.append('limit', String(options.limit));
170
193
  }
171
- const response = await fetch(url);
172
- if (!response.ok) {
173
- throw new controller_utils_1.HttpError(response.status, `Money Account API history request failed with status '${response.status}'`);
174
- }
175
- const json = await response.json();
176
- const [error, validated] = (0, superstruct_1.validate)(json, structs_1.HistoryResponseStruct);
177
- if (error) {
178
- throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from history endpoint: ${error.message}`);
179
- }
180
- return validated;
194
+ return __classPrivateFieldGet(this, _MoneyAccountApiDataService_instances, "m", _MoneyAccountApiDataService_traceNetworkRequest).call(this, {
195
+ name: exports.TRACES.HISTORY_API,
196
+ data: { operation: 'fetchHistory' },
197
+ }, async () => {
198
+ const response = await fetch(url);
199
+ if (!response.ok) {
200
+ throw new controller_utils_1.HttpError(response.status, `Money Account API history request failed with status '${response.status}'`);
201
+ }
202
+ const json = await response.json();
203
+ const [error, validated] = (0, superstruct_1.validate)(json, structs_1.HistoryResponseStruct);
204
+ if (error) {
205
+ throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from history endpoint: ${error.message}`);
206
+ }
207
+ return validated;
208
+ });
181
209
  },
182
210
  }, options?.cursor ?? undefined);
183
211
  }
@@ -209,20 +237,69 @@ class MoneyAccountApiDataService extends base_data_service_1.BaseDataService {
209
237
  ],
210
238
  staleTime: constants_1.RATE_HISTORY_STALE_TIME_MS,
211
239
  queryFn: async () => {
212
- const response = await fetch(url);
213
- if (!response.ok) {
214
- throw new controller_utils_1.HttpError(response.status, `Money Account API rate-history request failed with status '${response.status}'`);
215
- }
216
- const json = await response.json();
217
- const [error, validated] = (0, superstruct_1.validate)(json, structs_1.RateHistoryResponseStruct);
218
- if (error) {
219
- throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from rate-history endpoint: ${error.message}`);
220
- }
221
- return validated;
240
+ return __classPrivateFieldGet(this, _MoneyAccountApiDataService_instances, "m", _MoneyAccountApiDataService_traceNetworkRequest).call(this, {
241
+ name: exports.TRACES.RATE_HISTORY_API,
242
+ data: { operation: 'fetchRateHistory' },
243
+ }, async () => {
244
+ const response = await fetch(url);
245
+ if (!response.ok) {
246
+ throw new controller_utils_1.HttpError(response.status, `Money Account API rate-history request failed with status '${response.status}'`);
247
+ }
248
+ const json = await response.json();
249
+ const [error, validated] = (0, superstruct_1.validate)(json, structs_1.RateHistoryResponseStruct);
250
+ if (error) {
251
+ throw new errors_1.MoneyAccountApiResponseValidationError(`Malformed response from rate-history endpoint: ${error.message}`);
252
+ }
253
+ return validated;
254
+ });
222
255
  },
223
256
  });
224
257
  }
225
258
  }
226
259
  exports.MoneyAccountApiDataService = MoneyAccountApiDataService;
227
- _MoneyAccountApiDataService_baseUrl = new WeakMap();
260
+ _MoneyAccountApiDataService_baseUrl = new WeakMap(), _MoneyAccountApiDataService_trace = new WeakMap(), _MoneyAccountApiDataService_instances = new WeakSet(), _MoneyAccountApiDataService_traceNetworkRequest =
261
+ /**
262
+ * Runs a network request and emits a best-effort backdated trace.
263
+ *
264
+ * @param request - Trace metadata for the network request.
265
+ * @param fn - Network request to execute.
266
+ * @returns The network request result.
267
+ */
268
+ async function _MoneyAccountApiDataService_traceNetworkRequest(request, fn) {
269
+ const startTime = Date.now();
270
+ let success = false;
271
+ let errorName;
272
+ try {
273
+ const result = await fn();
274
+ success = true;
275
+ return result;
276
+ }
277
+ catch (error) {
278
+ errorName = error instanceof Error ? error.name : typeof error;
279
+ throw error;
280
+ }
281
+ finally {
282
+ const traceRequest = {
283
+ ...request,
284
+ startTime,
285
+ data: {
286
+ ...request.data,
287
+ success,
288
+ ...(errorName ? { errorName } : {}),
289
+ },
290
+ };
291
+ const onTraceError = (traceError) => {
292
+ traceLogger('Failed to emit trace', {
293
+ traceName: request.name,
294
+ traceError,
295
+ });
296
+ };
297
+ try {
298
+ Promise.resolve(__classPrivateFieldGet(this, _MoneyAccountApiDataService_trace, "f").call(this, traceRequest, () => undefined)).catch(onTraceError);
299
+ }
300
+ catch (traceError) {
301
+ onTraceError(traceError);
302
+ }
303
+ }
304
+ };
228
305
  //# sourceMappingURL=money-account-api-data-service.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"money-account-api-data-service.cjs","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,mEAA8D;AAE9D,iEAAmE;AAEnE,uDAAiD;AAIjD,+CAKqB;AACrB,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OAAO,CAAC,OAAO,CAAC,CAAC;gBAChE,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;gBAC5C,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;aACzC;YACD,SAAS,EAAE,sCAA0B;YACrC,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;gBAElC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;oBACjB,MAAM,IAAI,4BAAS,CACjB,QAAQ,CAAC,MAAM,EACf,8DAA8D,QAAQ,CAAC,MAAM,GAAG,CACjF,CAAC;gBACJ,CAAC;gBAED,MAAM,IAAI,GAAS,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;gBAEzC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,GAAG,IAAA,sBAAQ,EAAC,IAAI,EAAE,mCAAyB,CAAC,CAAC;gBACrE,IAAI,KAAK,EAAE,CAAC;oBACV,MAAM,IAAI,+CAAsC,CAC9C,kDAAkD,KAAK,CAAC,OAAO,EAAE,CAClE,CAAC;gBACJ,CAAC;gBAED,OAAO,SAA2C,CAAC;YACrD,CAAC;SACF,CAAC,CAAC;IACL,CAAC;CACF;AAtRD,gEAsRC","sourcesContent":["import type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { BaseDataService } from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { handleWhen, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport { validate } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport {\n DEFAULT_STALE_TIME_MS,\n Env,\n MONEY_ACCOUNT_API_URL_MAP,\n RATE_HISTORY_STALE_TIME_MS,\n} from './constants';\nimport { MoneyAccountApiResponseValidationError } from './errors';\nimport { projectLogger, createModuleLogger } from './logger';\nimport type { MoneyAccountApiDataServiceMethodActions } from './money-account-api-data-service-method-action-types';\nimport type {\n HistoryResponse,\n InterestResponse,\n PositionResponse,\n RateHistoryResponse,\n} from './response.types';\nimport {\n HistoryResponseStruct,\n InterestResponseStruct,\n PositionResponseStruct,\n RateHistoryResponseStruct,\n} from './structs';\nimport type {\n HistoryOptions,\n InterestOptions,\n RateHistoryOptions,\n} from './types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link MoneyAccountApiDataService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'MoneyAccountApiDataService';\n\nconst log = createModuleLogger(projectLogger, serviceName);\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'fetchPositions',\n 'fetchInterest',\n 'fetchHistory',\n 'fetchRateHistory',\n] as const;\n\n/**\n * Invalidates cached queries for {@link MoneyAccountApiDataService}.\n */\nexport type MoneyAccountApiDataServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link MoneyAccountApiDataService} exposes to other consumers.\n */\nexport type MoneyAccountApiDataServiceActions =\n | MoneyAccountApiDataServiceMethodActions\n | MoneyAccountApiDataServiceInvalidateQueriesAction;\n\n/**\n * Actions from other messengers that {@link MoneyAccountApiDataService} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Published when {@link MoneyAccountApiDataService}'s cache is updated.\n */\nexport type MoneyAccountApiDataServiceCacheUpdatedEvent =\n DataServiceCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Published when a key within {@link MoneyAccountApiDataService}'s cache is\n * updated.\n */\nexport type MoneyAccountApiDataServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link MoneyAccountApiDataService} exposes to other consumers.\n */\nexport type MoneyAccountApiDataServiceEvents =\n | MoneyAccountApiDataServiceCacheUpdatedEvent\n | MoneyAccountApiDataServiceGranularCacheUpdatedEvent;\n\n/**\n * Events from other messengers that {@link MoneyAccountApiDataService}\n * subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link MoneyAccountApiDataService}.\n */\nexport type MoneyAccountApiDataServiceMessenger = Messenger<\n typeof serviceName,\n MoneyAccountApiDataServiceActions | AllowedActions,\n MoneyAccountApiDataServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Data service responsible for fetching positions, interest, cash-flow\n * history, and vault rate history from the Money Account APY Tracking API.\n */\nexport class MoneyAccountApiDataService extends BaseDataService<\n typeof serviceName,\n MoneyAccountApiDataServiceMessenger\n> {\n readonly #baseUrl: string;\n\n /**\n * Constructs a new MoneyAccountApiDataService.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.env - The target environment. Defaults to production.\n * @param args.queryClientConfig - Configuration for the underlying TanStack\n * Query client.\n * @param args.policyOptions - Options to pass to `createServicePolicy`.\n */\n constructor({\n messenger,\n env = Env.PRD,\n queryClientConfig = {},\n policyOptions = {},\n }: {\n messenger: MoneyAccountApiDataServiceMessenger;\n env?: Env;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions: {\n retryFilterPolicy: handleWhen(\n (error) => !(error instanceof MoneyAccountApiResponseValidationError),\n ),\n ...policyOptions,\n },\n });\n\n this.#baseUrl = MONEY_ACCOUNT_API_URL_MAP[env];\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('Initialized', { env, baseUrl: this.#baseUrl });\n }\n\n /**\n * Fetches the current vault positions for a given user address.\n *\n * @param address - The user's Ethereum address.\n * @returns The position response containing vault positions.\n */\n async fetchPositions(address: string): Promise<PositionResponse> {\n const url = new URL(\n `/v1/positions/${address.toLowerCase()}`,\n this.#baseUrl,\n );\n\n return this.fetchQuery({\n queryKey: [`${this.name}:fetchPositions`, address.toLowerCase()],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API positions request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, PositionResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from positions endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as PositionResponse;\n },\n });\n }\n\n /**\n * Fetches the interest earned for a given address and vault over a\n * specified time window.\n *\n * @param address - The user's Ethereum address.\n * @param options - Options specifying vault, window, and optional chain ID.\n * @returns The interest response.\n */\n async fetchInterest(\n address: string,\n options: InterestOptions,\n ): Promise<InterestResponse> {\n const url = new URL(\n `/v1/positions/${address.toLowerCase()}/interest`,\n this.#baseUrl,\n );\n url.searchParams.append(\n 'vault_address',\n options.vaultAddress.toLowerCase(),\n );\n url.searchParams.append('window', options.window);\n if (options.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n\n return this.fetchQuery({\n queryKey: [\n `${this.name}:fetchInterest`,\n address.toLowerCase(),\n options.vaultAddress.toLowerCase(),\n options.window,\n ...(options.chainId === undefined ? [] : [options.chainId]),\n ],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API interest request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, InterestResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from interest endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as InterestResponse;\n },\n });\n }\n\n /**\n * Fetches cursor-paginated cash-flow history for a given address.\n * Uses `fetchInfiniteQuery` for proper TanStack Query pagination semantics.\n *\n * When paginating, consumers must re-pass the same filter options\n * (`vaultAddress`, `chainId`, `limit`) alongside `cursor` on every page\n * request. This ensures the query key matches the original infinite query\n * and that the HTTP request includes the correct filters.\n *\n * @param address - The user's Ethereum address.\n * @param options - Optional filtering and pagination options.\n * @returns The history response containing cash-flow entries for the requested page.\n */\n async fetchHistory(\n address: string,\n options?: HistoryOptions,\n ): Promise<HistoryResponse> {\n const normalizedAddress = address.toLowerCase();\n const normalizedVault = options?.vaultAddress?.toLowerCase() ?? null;\n\n return this.fetchInfiniteQuery(\n {\n queryKey: [\n `${this.name}:fetchHistory`,\n normalizedAddress,\n normalizedVault,\n options?.chainId ?? null,\n options?.limit ?? null,\n ],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async (context) => {\n const cursor = context.pageParam as string | null | undefined;\n\n const url = new URL(\n `/v1/positions/${normalizedAddress}/history`,\n this.#baseUrl,\n );\n if (normalizedVault) {\n url.searchParams.append('vault_address', normalizedVault);\n }\n if (options?.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n if (cursor) {\n url.searchParams.append('cursor', cursor);\n }\n if (options?.limit !== undefined) {\n url.searchParams.append('limit', String(options.limit));\n }\n\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API history request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, HistoryResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from history endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as HistoryResponse;\n },\n },\n options?.cursor ?? undefined,\n );\n }\n\n /**\n * Fetches the exchange-rate time series for a given vault.\n *\n * @param vaultAddress - The vault's Ethereum address.\n * @param options - Optional range and chain ID filters.\n * @returns The rate history response.\n */\n async fetchRateHistory(\n vaultAddress: string,\n options?: RateHistoryOptions,\n ): Promise<RateHistoryResponse> {\n const url = new URL(\n `/v1/vaults/${vaultAddress.toLowerCase()}/rate-history`,\n this.#baseUrl,\n );\n if (options?.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n if (options?.from) {\n url.searchParams.append('from', options.from);\n }\n if (options?.to) {\n url.searchParams.append('to', options.to);\n }\n\n return this.fetchQuery({\n queryKey: [\n `${this.name}:fetchRateHistory`,\n vaultAddress.toLowerCase(),\n ...(options?.chainId === undefined ? [null] : [options.chainId]),\n ...(options?.from ? [options.from] : [null]),\n ...(options?.to ? [options.to] : [null]),\n ],\n staleTime: RATE_HISTORY_STALE_TIME_MS,\n queryFn: async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API rate-history request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, RateHistoryResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from rate-history endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as RateHistoryResponse;\n },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"money-account-api-data-service.cjs","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,mEAA8D;AAM9D,iEAAmE;AAEnE,uDAAiD;AAIjD,+CAKqB;AACrB,yCAAkE;AAClE,yCAA6D;AAQ7D,2CAKmB;AAOnB,kBAAkB;AAElB;;;GAGG;AACU,QAAA,WAAW,GAAG,4BAA4B,CAAC;AAExD,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,mBAAW,CAAC,CAAC;AAC3D,MAAM,WAAW,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAElD,QAAA,MAAM,GAAG;IACpB,aAAa,EAAE,mCAAmC;IAClD,YAAY,EAAE,kCAAkC;IACh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AC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACpC;SACF,CAAC;QACF,MAAM,YAAY,GAAG,CAAC,UAAmB,EAAQ,EAAE;YACjD,WAAW,CAAC,sBAAsB,EAAE;gBAClC,SAAS,EAAE,OAAO,CAAC,IAAI;gBACvB,UAAU;aACX,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,IAAI,CAAC;YACH,OAAO,CAAC,OAAO,CAAC,uBAAA,IAAI,yCAAO,MAAX,IAAI,EAAQ,YAAY,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAC/D,YAAY,CACb,CAAC;QACJ,CAAC;QAAC,OAAO,UAAU,EAAE,CAAC;YACpB,YAAY,CAAC,UAAU,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { BaseDataService } from '@metamask/base-data-service';\nimport type {\n CreateServicePolicyOptions,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport { handleWhen, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport { validate } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport {\n DEFAULT_STALE_TIME_MS,\n Env,\n MONEY_ACCOUNT_API_URL_MAP,\n RATE_HISTORY_STALE_TIME_MS,\n} from './constants';\nimport { MoneyAccountApiResponseValidationError } from './errors';\nimport { projectLogger, createModuleLogger } from './logger';\nimport type { MoneyAccountApiDataServiceMethodActions } from './money-account-api-data-service-method-action-types';\nimport type {\n HistoryResponse,\n InterestResponse,\n PositionResponse,\n RateHistoryResponse,\n} from './response.types';\nimport {\n HistoryResponseStruct,\n InterestResponseStruct,\n PositionResponseStruct,\n RateHistoryResponseStruct,\n} from './structs';\nimport type {\n HistoryOptions,\n InterestOptions,\n RateHistoryOptions,\n} from './types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link MoneyAccountApiDataService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'MoneyAccountApiDataService';\n\nconst log = createModuleLogger(projectLogger, serviceName);\nconst traceLogger = createModuleLogger(projectLogger, 'trace');\n\nexport const TRACES = {\n POSITIONS_API: 'Money Account API Fetch Positions',\n INTEREST_API: 'Money Account API Fetch Interest',\n HISTORY_API: 'Money Account API Fetch History',\n RATE_HISTORY_API: 'Money Account API Fetch Rate History',\n} as const;\n\nexport type MoneyAccountApiDataServiceTraceName =\n (typeof TRACES)[keyof typeof TRACES];\n\nexport type MoneyAccountApiDataServiceTraceRequest = Omit<\n TraceRequest,\n 'name'\n> & {\n name: MoneyAccountApiDataServiceTraceName;\n startTime?: number;\n};\n\nexport type MoneyAccountApiDataServiceTraceCallback = <ReturnType>(\n request: MoneyAccountApiDataServiceTraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n) => Promise<ReturnType>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'fetchPositions',\n 'fetchInterest',\n 'fetchHistory',\n 'fetchRateHistory',\n] as const;\n\n/**\n * Invalidates cached queries for {@link MoneyAccountApiDataService}.\n */\nexport type MoneyAccountApiDataServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link MoneyAccountApiDataService} exposes to other consumers.\n */\nexport type MoneyAccountApiDataServiceActions =\n | MoneyAccountApiDataServiceMethodActions\n | MoneyAccountApiDataServiceInvalidateQueriesAction;\n\n/**\n * Actions from other messengers that {@link MoneyAccountApiDataService} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Published when {@link MoneyAccountApiDataService}'s cache is updated.\n */\nexport type MoneyAccountApiDataServiceCacheUpdatedEvent =\n DataServiceCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Published when a key within {@link MoneyAccountApiDataService}'s cache is\n * updated.\n */\nexport type MoneyAccountApiDataServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link MoneyAccountApiDataService} exposes to other consumers.\n */\nexport type MoneyAccountApiDataServiceEvents =\n | MoneyAccountApiDataServiceCacheUpdatedEvent\n | MoneyAccountApiDataServiceGranularCacheUpdatedEvent;\n\n/**\n * Events from other messengers that {@link MoneyAccountApiDataService}\n * subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link MoneyAccountApiDataService}.\n */\nexport type MoneyAccountApiDataServiceMessenger = Messenger<\n typeof serviceName,\n MoneyAccountApiDataServiceActions | AllowedActions,\n MoneyAccountApiDataServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\nexport type MoneyAccountApiDataServiceOptions = {\n messenger: MoneyAccountApiDataServiceMessenger;\n env?: Env;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n trace?: MoneyAccountApiDataServiceTraceCallback;\n};\n\n/**\n * Data service responsible for fetching positions, interest, cash-flow\n * history, and vault rate history from the Money Account APY Tracking API.\n */\nexport class MoneyAccountApiDataService extends BaseDataService<\n typeof serviceName,\n MoneyAccountApiDataServiceMessenger\n> {\n readonly #baseUrl: string;\n\n readonly #trace: MoneyAccountApiDataServiceTraceCallback;\n\n /**\n * Constructs a new MoneyAccountApiDataService.\n *\n * @param options - The constructor arguments.\n * @param options.messenger - The messenger suited for this service.\n * @param options.env - The target environment. Defaults to production.\n * @param options.queryClientConfig - Configuration for the underlying\n * TanStack Query client.\n * @param options.policyOptions - Options to pass to `createServicePolicy`.\n * @param options.trace - Optional callback to trace network requests.\n */\n constructor({\n messenger,\n env = Env.PRD,\n queryClientConfig = {},\n policyOptions = {},\n trace,\n }: MoneyAccountApiDataServiceOptions) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions: {\n retryFilterPolicy: handleWhen(\n (error) => !(error instanceof MoneyAccountApiResponseValidationError),\n ),\n ...policyOptions,\n },\n });\n\n this.#baseUrl = MONEY_ACCOUNT_API_URL_MAP[env];\n\n this.#trace =\n trace ??\n (async <Result>(\n _request: MoneyAccountApiDataServiceTraceRequest,\n fn?: (context?: TraceContext) => Result,\n ): Promise<Result> => {\n return await Promise.resolve(fn?.() as Result);\n });\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('Initialized', { env, baseUrl: this.#baseUrl });\n }\n\n /**\n * Fetches the current vault positions for a given user address.\n *\n * @param address - The user's Ethereum address.\n * @returns The position response containing vault positions.\n */\n async fetchPositions(address: string): Promise<PositionResponse> {\n const url = new URL(\n `/v1/positions/${address.toLowerCase()}`,\n this.#baseUrl,\n );\n\n return this.fetchQuery({\n queryKey: [`${this.name}:fetchPositions`, address.toLowerCase()],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async () => {\n return this.#traceNetworkRequest(\n {\n name: TRACES.POSITIONS_API,\n data: { operation: 'fetchPositions' },\n },\n async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API positions request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, PositionResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from positions endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as PositionResponse;\n },\n );\n },\n });\n }\n\n /**\n * Fetches the interest earned for a given address and vault over a\n * specified time window.\n *\n * @param address - The user's Ethereum address.\n * @param options - Options specifying vault, window, and optional chain ID.\n * @returns The interest response.\n */\n async fetchInterest(\n address: string,\n options: InterestOptions,\n ): Promise<InterestResponse> {\n const url = new URL(\n `/v1/positions/${address.toLowerCase()}/interest`,\n this.#baseUrl,\n );\n url.searchParams.append(\n 'vault_address',\n options.vaultAddress.toLowerCase(),\n );\n url.searchParams.append('window', options.window);\n if (options.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n\n return this.fetchQuery({\n queryKey: [\n `${this.name}:fetchInterest`,\n address.toLowerCase(),\n options.vaultAddress.toLowerCase(),\n options.window,\n ...(options.chainId === undefined ? [] : [options.chainId]),\n ],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async () => {\n return this.#traceNetworkRequest(\n {\n name: TRACES.INTEREST_API,\n data: { operation: 'fetchInterest' },\n },\n async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API interest request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, InterestResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from interest endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as InterestResponse;\n },\n );\n },\n });\n }\n\n /**\n * Fetches cursor-paginated cash-flow history for a given address.\n * Uses `fetchInfiniteQuery` for proper TanStack Query pagination semantics.\n *\n * When paginating, consumers must re-pass the same filter options\n * (`vaultAddress`, `chainId`, `limit`) alongside `cursor` on every page\n * request. This ensures the query key matches the original infinite query\n * and that the HTTP request includes the correct filters.\n *\n * @param address - The user's Ethereum address.\n * @param options - Optional filtering and pagination options.\n * @returns The history response containing cash-flow entries for the requested page.\n */\n async fetchHistory(\n address: string,\n options?: HistoryOptions,\n ): Promise<HistoryResponse> {\n const normalizedAddress = address.toLowerCase();\n const normalizedVault = options?.vaultAddress?.toLowerCase() ?? null;\n\n return this.fetchInfiniteQuery(\n {\n queryKey: [\n `${this.name}:fetchHistory`,\n normalizedAddress,\n normalizedVault,\n options?.chainId ?? null,\n options?.limit ?? null,\n ],\n staleTime: DEFAULT_STALE_TIME_MS,\n queryFn: async (context) => {\n const cursor = context.pageParam as string | null | undefined;\n\n const url = new URL(\n `/v1/positions/${normalizedAddress}/history`,\n this.#baseUrl,\n );\n if (normalizedVault) {\n url.searchParams.append('vault_address', normalizedVault);\n }\n if (options?.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n if (cursor) {\n url.searchParams.append('cursor', cursor);\n }\n if (options?.limit !== undefined) {\n url.searchParams.append('limit', String(options.limit));\n }\n\n return this.#traceNetworkRequest(\n {\n name: TRACES.HISTORY_API,\n data: { operation: 'fetchHistory' },\n },\n async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API history request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(json, HistoryResponseStruct);\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from history endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as HistoryResponse;\n },\n );\n },\n },\n options?.cursor ?? undefined,\n );\n }\n\n /**\n * Fetches the exchange-rate time series for a given vault.\n *\n * @param vaultAddress - The vault's Ethereum address.\n * @param options - Optional range and chain ID filters.\n * @returns The rate history response.\n */\n async fetchRateHistory(\n vaultAddress: string,\n options?: RateHistoryOptions,\n ): Promise<RateHistoryResponse> {\n const url = new URL(\n `/v1/vaults/${vaultAddress.toLowerCase()}/rate-history`,\n this.#baseUrl,\n );\n if (options?.chainId !== undefined) {\n url.searchParams.append('chain_id', String(options.chainId));\n }\n if (options?.from) {\n url.searchParams.append('from', options.from);\n }\n if (options?.to) {\n url.searchParams.append('to', options.to);\n }\n\n return this.fetchQuery({\n queryKey: [\n `${this.name}:fetchRateHistory`,\n vaultAddress.toLowerCase(),\n ...(options?.chainId === undefined ? [null] : [options.chainId]),\n ...(options?.from ? [options.from] : [null]),\n ...(options?.to ? [options.to] : [null]),\n ],\n staleTime: RATE_HISTORY_STALE_TIME_MS,\n queryFn: async () => {\n return this.#traceNetworkRequest(\n {\n name: TRACES.RATE_HISTORY_API,\n data: { operation: 'fetchRateHistory' },\n },\n async () => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Money Account API rate-history request failed with status '${response.status}'`,\n );\n }\n\n const json: Json = await response.json();\n\n const [error, validated] = validate(\n json,\n RateHistoryResponseStruct,\n );\n if (error) {\n throw new MoneyAccountApiResponseValidationError(\n `Malformed response from rate-history endpoint: ${error.message}`,\n );\n }\n\n return validated as unknown as RateHistoryResponse;\n },\n );\n },\n });\n }\n\n /**\n * Runs a network request and emits a best-effort backdated trace.\n *\n * @param request - Trace metadata for the network request.\n * @param fn - Network request to execute.\n * @returns The network request result.\n */\n async #traceNetworkRequest<Result>(\n request: MoneyAccountApiDataServiceTraceRequest,\n fn: () => Promise<Result>,\n ): Promise<Result> {\n const startTime = Date.now();\n let success = false;\n let errorName: string | undefined;\n\n try {\n const result = await fn();\n success = true;\n return result;\n } catch (error) {\n errorName = error instanceof Error ? error.name : typeof error;\n throw error;\n } finally {\n const traceRequest = {\n ...request,\n startTime,\n data: {\n ...request.data,\n success,\n ...(errorName ? { errorName } : {}),\n },\n };\n const onTraceError = (traceError: unknown): void => {\n traceLogger('Failed to emit trace', {\n traceName: request.name,\n traceError,\n });\n };\n\n try {\n Promise.resolve(this.#trace(traceRequest, () => undefined)).catch(\n onTraceError,\n );\n } catch (traceError) {\n onTraceError(traceError);\n }\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction } from "@metamask/base-data-service";
2
2
  import { BaseDataService } from "@metamask/base-data-service";
3
- import type { CreateServicePolicyOptions } from "@metamask/controller-utils";
3
+ import type { CreateServicePolicyOptions, TraceContext, TraceRequest } from "@metamask/controller-utils";
4
4
  import type { Messenger } from "@metamask/messenger";
5
5
  import type { QueryClientConfig } from "@tanstack/query-core";
6
6
  import { Env } from "./constants.cjs";
@@ -12,6 +12,18 @@ import type { HistoryOptions, InterestOptions, RateHistoryOptions } from "./type
12
12
  * service's actions and events.
13
13
  */
14
14
  export declare const serviceName = "MoneyAccountApiDataService";
15
+ export declare const TRACES: {
16
+ readonly POSITIONS_API: "Money Account API Fetch Positions";
17
+ readonly INTEREST_API: "Money Account API Fetch Interest";
18
+ readonly HISTORY_API: "Money Account API Fetch History";
19
+ readonly RATE_HISTORY_API: "Money Account API Fetch Rate History";
20
+ };
21
+ export type MoneyAccountApiDataServiceTraceName = (typeof TRACES)[keyof typeof TRACES];
22
+ export type MoneyAccountApiDataServiceTraceRequest = Omit<TraceRequest, 'name'> & {
23
+ name: MoneyAccountApiDataServiceTraceName;
24
+ startTime?: number;
25
+ };
26
+ export type MoneyAccountApiDataServiceTraceCallback = <ReturnType>(request: MoneyAccountApiDataServiceTraceRequest, fn?: (context?: TraceContext) => ReturnType) => Promise<ReturnType>;
15
27
  /**
16
28
  * Invalidates cached queries for {@link MoneyAccountApiDataService}.
17
29
  */
@@ -47,6 +59,13 @@ type AllowedEvents = never;
47
59
  * {@link MoneyAccountApiDataService}.
48
60
  */
49
61
  export type MoneyAccountApiDataServiceMessenger = Messenger<typeof serviceName, MoneyAccountApiDataServiceActions | AllowedActions, MoneyAccountApiDataServiceEvents | AllowedEvents>;
62
+ export type MoneyAccountApiDataServiceOptions = {
63
+ messenger: MoneyAccountApiDataServiceMessenger;
64
+ env?: Env;
65
+ queryClientConfig?: QueryClientConfig;
66
+ policyOptions?: CreateServicePolicyOptions;
67
+ trace?: MoneyAccountApiDataServiceTraceCallback;
68
+ };
50
69
  /**
51
70
  * Data service responsible for fetching positions, interest, cash-flow
52
71
  * history, and vault rate history from the Money Account APY Tracking API.
@@ -56,19 +75,15 @@ export declare class MoneyAccountApiDataService extends BaseDataService<typeof s
56
75
  /**
57
76
  * Constructs a new MoneyAccountApiDataService.
58
77
  *
59
- * @param args - The constructor arguments.
60
- * @param args.messenger - The messenger suited for this service.
61
- * @param args.env - The target environment. Defaults to production.
62
- * @param args.queryClientConfig - Configuration for the underlying TanStack
63
- * Query client.
64
- * @param args.policyOptions - Options to pass to `createServicePolicy`.
78
+ * @param options - The constructor arguments.
79
+ * @param options.messenger - The messenger suited for this service.
80
+ * @param options.env - The target environment. Defaults to production.
81
+ * @param options.queryClientConfig - Configuration for the underlying
82
+ * TanStack Query client.
83
+ * @param options.policyOptions - Options to pass to `createServicePolicy`.
84
+ * @param options.trace - Optional callback to trace network requests.
65
85
  */
66
- constructor({ messenger, env, queryClientConfig, policyOptions, }: {
67
- messenger: MoneyAccountApiDataServiceMessenger;
68
- env?: Env;
69
- queryClientConfig?: QueryClientConfig;
70
- policyOptions?: CreateServicePolicyOptions;
71
- });
86
+ constructor({ messenger, env, queryClientConfig, policyOptions, trace, }: MoneyAccountApiDataServiceOptions);
72
87
  /**
73
88
  * Fetches the current vault positions for a given user address.
74
89
  *
@@ -1 +1 @@
1
- {"version":3,"file":"money-account-api-data-service.d.cts","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EAEL,GAAG,EAGJ,wBAAoB;AAGrB,OAAO,KAAK,EAAE,uCAAuC,EAAE,iEAA6D;AACpH,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACpB,6BAAyB;AAO1B,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,kBAAkB,EACnB,oBAAgB;AAIjB;;;GAGG;AACH,eAAO,MAAM,WAAW,+BAA+B,CAAC;AAaxD;;GAEG;AACH,MAAM,MAAM,iDAAiD,GAC3D,kCAAkC,CAAC,OAAO,WAAW,CAAC,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,iCAAiC,GACzC,uCAAuC,GACvC,iDAAiD,CAAC;AAEtD;;GAEG;AACH,KAAK,cAAc,GA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+ {"version":3,"file":"money-account-api-data-service.d.cts","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EACV,0BAA0B,EAC1B,YAAY,EACZ,YAAY,EACb,mCAAmC;AAEpC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EAEL,GAAG,EAGJ,wBAAoB;AAGrB,OAAO,KAAK,EAAE,uCAAuC,EAAE,iEAA6D;AACpH,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACpB,6BAAyB;AAO1B,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,kBAAkB,EACnB,oBAAgB;AAIjB;;;GAGG;AACH,eAAO,MAAM,WAAW,+BAA+B,CAAC;AAKxD,eAAO,MAAM,MAAM;;;;;CAKT,CAAC;AAEX,MAAM,MAAM,mCAAmC,GAC7C,CAAC,OAAO,MAAM,CAAC,CAAC,MAAM,OAAO,MAAM,CAAC,CAAC;AAEvC,MAAM,MAAM,sCAAsC,GAAG,IAAI,CACvD,YAAY,EACZ,MAAM,CACP,GAAG;IACF,IAAI,EAAE,mCAAmC,CAAC;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,uCAAuC,GAAG,CAAC,UAAU,EAC/D,OAAO,EAAE,sCAAsC,EAC/C,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,YAAY,KAAK,UAAU,KACxC,OAAO,CAAC,UAAU,CAAC,CAAC;AAWzB;;GAEG;AACH,MAAM,MAAM,iDAAiD,GAC3D,kCAAkC,CAAC,OAAO,WAAW,CAAC,CAAC;AAEzD;;GAEG;AACH,MAA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O,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,eAAe,CAAC;IAmE3B;;;;;;OAMG;IACG,gBAAgB,CACpB,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,kBAAkB,GAC3B,OAAO,CAAC,mBAAmB,CAAC;CA2GhC"}
@@ -1,6 +1,6 @@
1
1
  import type { DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction } from "@metamask/base-data-service";
2
2
  import { BaseDataService } from "@metamask/base-data-service";
3
- import type { CreateServicePolicyOptions } from "@metamask/controller-utils";
3
+ import type { CreateServicePolicyOptions, TraceContext, TraceRequest } from "@metamask/controller-utils";
4
4
  import type { Messenger } from "@metamask/messenger";
5
5
  import type { QueryClientConfig } from "@tanstack/query-core";
6
6
  import { Env } from "./constants.mjs";
@@ -12,6 +12,18 @@ import type { HistoryOptions, InterestOptions, RateHistoryOptions } from "./type
12
12
  * service's actions and events.
13
13
  */
14
14
  export declare const serviceName = "MoneyAccountApiDataService";
15
+ export declare const TRACES: {
16
+ readonly POSITIONS_API: "Money Account API Fetch Positions";
17
+ readonly INTEREST_API: "Money Account API Fetch Interest";
18
+ readonly HISTORY_API: "Money Account API Fetch History";
19
+ readonly RATE_HISTORY_API: "Money Account API Fetch Rate History";
20
+ };
21
+ export type MoneyAccountApiDataServiceTraceName = (typeof TRACES)[keyof typeof TRACES];
22
+ export type MoneyAccountApiDataServiceTraceRequest = Omit<TraceRequest, 'name'> & {
23
+ name: MoneyAccountApiDataServiceTraceName;
24
+ startTime?: number;
25
+ };
26
+ export type MoneyAccountApiDataServiceTraceCallback = <ReturnType>(request: MoneyAccountApiDataServiceTraceRequest, fn?: (context?: TraceContext) => ReturnType) => Promise<ReturnType>;
15
27
  /**
16
28
  * Invalidates cached queries for {@link MoneyAccountApiDataService}.
17
29
  */
@@ -47,6 +59,13 @@ type AllowedEvents = never;
47
59
  * {@link MoneyAccountApiDataService}.
48
60
  */
49
61
  export type MoneyAccountApiDataServiceMessenger = Messenger<typeof serviceName, MoneyAccountApiDataServiceActions | AllowedActions, MoneyAccountApiDataServiceEvents | AllowedEvents>;
62
+ export type MoneyAccountApiDataServiceOptions = {
63
+ messenger: MoneyAccountApiDataServiceMessenger;
64
+ env?: Env;
65
+ queryClientConfig?: QueryClientConfig;
66
+ policyOptions?: CreateServicePolicyOptions;
67
+ trace?: MoneyAccountApiDataServiceTraceCallback;
68
+ };
50
69
  /**
51
70
  * Data service responsible for fetching positions, interest, cash-flow
52
71
  * history, and vault rate history from the Money Account APY Tracking API.
@@ -56,19 +75,15 @@ export declare class MoneyAccountApiDataService extends BaseDataService<typeof s
56
75
  /**
57
76
  * Constructs a new MoneyAccountApiDataService.
58
77
  *
59
- * @param args - The constructor arguments.
60
- * @param args.messenger - The messenger suited for this service.
61
- * @param args.env - The target environment. Defaults to production.
62
- * @param args.queryClientConfig - Configuration for the underlying TanStack
63
- * Query client.
64
- * @param args.policyOptions - Options to pass to `createServicePolicy`.
78
+ * @param options - The constructor arguments.
79
+ * @param options.messenger - The messenger suited for this service.
80
+ * @param options.env - The target environment. Defaults to production.
81
+ * @param options.queryClientConfig - Configuration for the underlying
82
+ * TanStack Query client.
83
+ * @param options.policyOptions - Options to pass to `createServicePolicy`.
84
+ * @param options.trace - Optional callback to trace network requests.
65
85
  */
66
- constructor({ messenger, env, queryClientConfig, policyOptions, }: {
67
- messenger: MoneyAccountApiDataServiceMessenger;
68
- env?: Env;
69
- queryClientConfig?: QueryClientConfig;
70
- policyOptions?: CreateServicePolicyOptions;
71
- });
86
+ constructor({ messenger, env, queryClientConfig, policyOptions, trace, }: MoneyAccountApiDataServiceOptions);
72
87
  /**
73
88
  * Fetches the current vault positions for a given user address.
74
89
  *
@@ -1 +1 @@
1
- {"version":3,"file":"money-account-api-data-service.d.mts","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAk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;;;;;;OASG;gBACS,EACV,SAAS,EACT,GAAa,EACb,iBAAsB,EACtB,aAAkB,GACnB,EAAE;QACD,SAAS,EAAE,mCAAmC,CAAC;QAC/C,GAAG,CAAC,EAAE,GAAG,CAAC;QACV,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;QACtC,aAAa,CAAC,EAAE,0BAA0B,CAAC;KAC5C;IAuBD;;;;;OAKG;IACG,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAiChE;;;;;;;OAOG;IACG,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,gBAAgB,CAAC;IA+C5B;;;;;;;;;;;;OAYG;IACG,YAAY,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,eAAe,CAAC;IA2D3B;;;;;;OAMG;IACG,gBAAgB,CACpB,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,kBAAkB,GAC3B,OAAO,CAAC,mBAAmB,CAAC;CA+ChC"}
1
+ {"version":3,"file":"money-account-api-data-service.d.mts","sourceRoot":"","sources":["../src/money-account-api-data-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EACV,0BAA0B,EAC1B,YAAY,EACZ,YAAY,EACb,mCAAmC;AAEpC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,EAEL,GAAG,EAGJ,wBAAoB;AAGrB,OAAO,KAAK,EAAE,uCAAuC,EAAE,iEAA6D;AACpH,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACpB,6BAAyB;AAO1B,OA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