@lunch-money/ethereum-to-lunch-money 1.4.0 → 2.0.1

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.
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const ethers_1 = require("ethers");
16
+ const client_1 = require("./client");
17
+ const node_fetch_1 = __importDefault(require("node-fetch"));
18
+ // Helper function to wrap promises around provider tests
19
+ const wrapPromise = (promise) => promise.then((result) => result, (error) => error);
20
+ class EthereumInitializationService {
21
+ constructor(integrations, logDebug) {
22
+ this.integrations = integrations;
23
+ this.logDebug = logDebug;
24
+ this.initialized = false;
25
+ // Helper function to extract clean error messages from API key tests
26
+ this.getCleanErrorMessage = (error) => {
27
+ const errorMessage = error instanceof Error ? error.message : String(error);
28
+ // Extract just the essential error information
29
+ if (errorMessage.includes('401')) {
30
+ return 'Authentication failed - invalid API key';
31
+ }
32
+ else if (errorMessage.includes('403')) {
33
+ return 'Access forbidden - check API key permissions';
34
+ }
35
+ else if (errorMessage.includes('429') || errorMessage.includes('rate limit')) {
36
+ return 'Rate limit exceeded - try again later';
37
+ }
38
+ else if (errorMessage.includes('network') || errorMessage.includes('connection')) {
39
+ return 'Network connection error';
40
+ }
41
+ else if (errorMessage.includes('timeout')) {
42
+ return 'Request timed out';
43
+ }
44
+ else {
45
+ // For other errors, take just the first meaningful part
46
+ const firstLine = errorMessage.split('\n')[0];
47
+ // Remove verbose details and keep just the core message
48
+ if (firstLine.includes('server response')) {
49
+ const match = firstLine.match(/server response (\d+)/);
50
+ if (match) {
51
+ return `Server error ${match[1]}`;
52
+ }
53
+ }
54
+ return firstLine;
55
+ }
56
+ };
57
+ // Define handlers to validate response from Wallet API requests
58
+ // Use arrow functions to bind 'this' to the class instance
59
+ this.handleMoralisResponse = (response) => __awaiter(this, void 0, void 0, function* () {
60
+ if (!response.ok) {
61
+ throw new Error(`Moralis API error: ${response.status} ${response.statusText}`);
62
+ }
63
+ this.logDebug('Moralis API key test: SUCCESS');
64
+ return { type: 'API Provider', name: 'Moralis', status: 'SUCCESS', apiKey: process.env.MORALIS_API_KEY };
65
+ });
66
+ this.handleEtherscanResponse = (response) => __awaiter(this, void 0, void 0, function* () {
67
+ const data = yield response.json();
68
+ if (data.status === '0' && data.message === 'NOTOK') {
69
+ throw new Error(`Etherscan API error: ${data.result}`);
70
+ }
71
+ console.log('[DEBUG_ETHEREUM] Etherscan API key test: SUCCESS');
72
+ return {
73
+ type: 'API Provider',
74
+ name: 'Etherscan',
75
+ status: 'SUCCESS',
76
+ apiKey: process.env.ETHERSCAN_API_KEY,
77
+ };
78
+ });
79
+ this.logDebug = logDebug.bind(this);
80
+ this.handleError = this.handleError.bind(this);
81
+ // TODO: this could us a little more error handling
82
+ integrations.ethereum.initialized = false;
83
+ this.ethereumIntegration = integrations.ethereum;
84
+ }
85
+ initialize() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ if (this.initialized) {
88
+ return this.ethereumIntegration;
89
+ }
90
+ try {
91
+ yield this.validateAPIKeys();
92
+ if (this.ethereumIntegration.serviceProviderInfo.length > 0) {
93
+ // Yay, we got a valid Service Provider Key!
94
+ this.ethereumIntegration.walletClient = (0, client_1.createEthereumWalletClient)(this.ethereumIntegration.serviceProviderInfo, this.ethereumIntegration.walletProviderInfo);
95
+ this.logDebug('Ethereum initialized with supplied provider(s)');
96
+ }
97
+ else {
98
+ this.ethereumIntegration.walletClient = (0, client_1.createEthereumWalletClient)();
99
+ this.logDebug('Ethereum initialized with public provider(s)');
100
+ }
101
+ this.initialized = true;
102
+ this.ethereumIntegration.initialized = true;
103
+ }
104
+ catch (error) {
105
+ const errorMessage = this.getErrorMessage(error);
106
+ console.error(`Unexpected error in Ethereum initialization: ${errorMessage}`);
107
+ throw new Error(errorMessage);
108
+ }
109
+ return this.ethereumIntegration;
110
+ });
111
+ }
112
+ validateAPIKeys() {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ try {
115
+ this.warnAboutLegacyKeys();
116
+ this.logDebug('Starting background testing of private providers and API keys');
117
+ // This is a well known test Ethereum wallet address
118
+ const testAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
119
+ const missingKeyResults = [];
120
+ let wrappedProviderPromises = [];
121
+ // Prepare private provider tests
122
+ const privateProviders = this.getPrivateProviders();
123
+ if (privateProviders.length === 0) {
124
+ this.logDebug('No Ethereum service provider keys (ALCHEMY_API_KEY or INFURA_API_KEY) are set.');
125
+ missingKeyResults.push({
126
+ type: 'Service Provider',
127
+ name: 'Ethereum Service Providers',
128
+ status: 'FAILED',
129
+ error: 'Missing required Ethereum service provider keys (ALCHEMY_API_KEY or INFURA_API_KEY)',
130
+ });
131
+ }
132
+ else {
133
+ wrappedProviderPromises = privateProviders.map((provider) => wrapPromise(this.testProvider(provider, testAddress)));
134
+ }
135
+ //Prepare API Key Tests
136
+ let wrappedApiKeyPromises = [];
137
+ const apiKeys = this.getWalletTokenApiKeyTestInfo(testAddress);
138
+ if (apiKeys.length === 0) {
139
+ missingKeyResults.push({
140
+ type: 'API Provider',
141
+ name: 'API Keys',
142
+ status: 'FAILED',
143
+ error: 'Missing required wallet token API keys (ETHERSCAN_API_KEY or MORALIS_API_KEY)',
144
+ });
145
+ }
146
+ else {
147
+ wrappedApiKeyPromises = apiKeys.map((apiKeyTestInfo) => wrapPromise(this.testApiKey(apiKeyTestInfo)));
148
+ }
149
+ // Wrap any existing results in a promise
150
+ const missingKeyResultsPromise = Promise.resolve(missingKeyResults);
151
+ // Run all tests in parallel, including the results
152
+ const allResults = yield Promise.all([
153
+ ...(yield missingKeyResultsPromise),
154
+ ...wrappedProviderPromises,
155
+ ...wrappedApiKeyPromises,
156
+ ]);
157
+ this.processResults(allResults);
158
+ }
159
+ catch (error) {
160
+ const errorMessage = this.getErrorMessage(error);
161
+ console.error(`Unexpected error in Ethereum initialization: ${errorMessage}`);
162
+ throw new Error(errorMessage);
163
+ }
164
+ });
165
+ }
166
+ processResults(allResults) {
167
+ // Process Provider results
168
+ const successfulProviders = allResults.filter((result) => result.status === 'SUCCESS' && result.type === 'Service Provider');
169
+ const failedProviders = allResults.filter((result) => result.status === 'FAILED');
170
+ if (successfulProviders.length > 0) {
171
+ this.ethereumIntegration.serviceProviderInfo = successfulProviders;
172
+ if (failedProviders.length > 0) {
173
+ this.logDebug(`Secondary provider validation failed: ${failedProviders.map((p) => `${p.name}: ${p.error}`).join(', ')}`);
174
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
175
+ this.logDebug('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
176
+ process.exit(1);
177
+ }
178
+ else {
179
+ const primaryProvider = this.integrations.ethereum.serviceProviderInfo[0];
180
+ this.logDebug(`Continuing with ${primaryProvider.name} as primary provider and no secondary provider.`);
181
+ }
182
+ }
183
+ // }
184
+ }
185
+ else {
186
+ if (failedProviders.length > 0) {
187
+ this.logDebug(`Provider validation failed: ${failedProviders.map((p) => `${p.name}: ${p.error}`).join(', ')}`);
188
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
189
+ this.logDebug('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
190
+ process.exit(1);
191
+ }
192
+ else {
193
+ console.log('[DEBUG_ETHEREUM] Will continue with the public provider. THIS IS NOT RECOMMENDED!');
194
+ }
195
+ }
196
+ // Return here since we won't bother with API key tests if the provider tests failed
197
+ return;
198
+ }
199
+ // Process API Key test results
200
+ const successfulApiKeys = allResults.filter((result) => result.status === 'SUCCESS' && result.type === 'API Provider');
201
+ const failedApiKeys = allResults.filter((result) => result.status === 'FAILED' && result.type === 'API Provider');
202
+ if (successfulApiKeys.length === 0) {
203
+ if (failedApiKeys.length === 0) {
204
+ this.logDebug('No ETHERSCAN or MORALIS wallet API keys were provided, or all API keys failed.');
205
+ }
206
+ else {
207
+ this.logDebug(`API key validation failed: ${failedApiKeys.map((p) => `${p.name}: ${p.error}`).join(', ')}`);
208
+ }
209
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
210
+ this.logDebug('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
211
+ process.exit(1);
212
+ }
213
+ else {
214
+ this.logDebug('[DEBUG_ETHEREUM] Will continue without wallet API keys. THIS MAY LEAD TO ETHEREUM SERVICE PROVIDER RATE LIMITING!');
215
+ }
216
+ }
217
+ else {
218
+ this.ethereumIntegration.walletProviderInfo = successfulApiKeys;
219
+ if (failedApiKeys.length > 0) {
220
+ this.logDebug(`API key validation failed: ${failedApiKeys.map((p) => `${p.name}: ${p.error}`).join(', ')}`);
221
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
222
+ console.error('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
223
+ process.exit(1);
224
+ }
225
+ else {
226
+ this.logDebug(`Will continue using the single ${successfulApiKeys[0].name} API key with no secondary API key.`);
227
+ }
228
+ }
229
+ }
230
+ }
231
+ // Add a utility function for error handling
232
+ handleError(providerName, error, type) {
233
+ const errorMessage = this.getCleanErrorMessage(error);
234
+ this.logDebug(`${providerName} test: FAILED - ${errorMessage}`);
235
+ return {
236
+ type,
237
+ name: providerName,
238
+ status: 'FAILED',
239
+ error: errorMessage,
240
+ };
241
+ }
242
+ // Check if the provider is valid and create a wallet client if it is
243
+ testProvider(providerInfo, testAddress) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ try {
246
+ const balance = yield providerInfo.provider.getBalance(testAddress);
247
+ const network = yield providerInfo.provider.getNetwork();
248
+ this.logDebug(`${providerInfo.name} API key test: SUCCESS - Network: ${network.name}, Test Balance returned.`);
249
+ return {
250
+ type: 'Service Provider',
251
+ provider: providerInfo.provider,
252
+ name: providerInfo.name,
253
+ status: 'SUCCESS',
254
+ network: network.name,
255
+ balance: balance.toString(),
256
+ apiKey: providerInfo.apiKey,
257
+ };
258
+ }
259
+ catch (error) {
260
+ return this.handleError(providerInfo.name, error, 'Service Provider');
261
+ }
262
+ });
263
+ }
264
+ // Check if a wallet token API key is valid
265
+ testApiKey(apiKeyTestInfo) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ try {
268
+ let response;
269
+ if (apiKeyTestInfo.headers) {
270
+ response = yield (0, node_fetch_1.default)(apiKeyTestInfo.url, {
271
+ headers: apiKeyTestInfo.headers,
272
+ });
273
+ }
274
+ else {
275
+ response = yield (0, node_fetch_1.default)(apiKeyTestInfo.url);
276
+ }
277
+ return yield apiKeyTestInfo.responseHandler(response);
278
+ }
279
+ catch (error) {
280
+ return this.handleError(apiKeyTestInfo.provider, error, 'API Provider');
281
+ }
282
+ });
283
+ }
284
+ // Helper to display masked API Keys in debug messages
285
+ maskKey(key) {
286
+ if (!key)
287
+ return 'undefined';
288
+ if (key.length <= 8)
289
+ return '*'.repeat(key.length);
290
+ return key.substring(0, 4) + '*'.repeat(key.length - 8) + key.substring(key.length - 4);
291
+ }
292
+ warnAboutLegacyKeys() {
293
+ if (process.env.DEBUG_ETHEREUM) {
294
+ if (process.env.INFURA_PROJECT_ID || process.env.INFURA_PROJECT_SECRET) {
295
+ this.logDebug('[DEBUG_ETHEREUM] Found an Infura API Project ID and/or Secret. Replace this with INFURA_API_KEY.');
296
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
297
+ this.logDebug('Remove unused INFURA_PROJECT_ID and INFURA_PROJECT_SECRET from your environment variables.');
298
+ this.logDebug('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
299
+ process.exit(1);
300
+ }
301
+ }
302
+ if (process.env.POCKET_API_KEY) {
303
+ this.logDebug('[DEBUG_ETHEREUM] Found a Pocket API key. Pocket is no longer recommended as a service node.');
304
+ if (process.env.DEBUG_ETHEREUM_FAIL_ON_ERROR === 'true') {
305
+ this.logDebug('Remove unused POCKET_API_KEY from your environment variables.');
306
+ this.logDebug('DEBUG_ETHEREUM_FAIL_ON_ERROR is set to true. Exiting...');
307
+ process.exit(1);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ // Helper to get the private providers from the environment variables
313
+ getPrivateProviders() {
314
+ const providers = [];
315
+ if (process.env.ALCHEMY_API_KEY) {
316
+ const alchemyProvider = new ethers_1.ethers.AlchemyProvider('mainnet', process.env.ALCHEMY_API_KEY);
317
+ providers.push({ name: 'Alchemy', provider: alchemyProvider, apiKey: process.env.ALCHEMY_API_KEY });
318
+ this.logDebug(`Found an Alchemy key (masked): ${this.maskKey(process.env.ALCHEMY_API_KEY)}`);
319
+ }
320
+ if (process.env.INFURA_API_KEY) {
321
+ const infuraProvider = new ethers_1.ethers.InfuraProvider('mainnet', process.env.INFURA_API_KEY);
322
+ providers.push({ name: 'Infura', provider: infuraProvider, apiKey: process.env.INFURA_API_KEY });
323
+ this.logDebug(`Found an Infura key (masked): ${this.maskKey(process.env.INFURA_API_KEY)}`);
324
+ }
325
+ return providers;
326
+ }
327
+ // Helper to get the array of wallet token API key tests
328
+ getWalletTokenApiKeyTestInfo(testAddress) {
329
+ const apiKeyTestInfo = [];
330
+ if (process.env.ETHERSCAN_API_KEY || process.env.MORALIS_API_KEY) {
331
+ if (process.env.MORALIS_API_KEY && process.env.DEBUG_ETHEREUM) {
332
+ this.logDebug(`Found a Moralis key (masked): ${this.maskKey(process.env.MORALIS_API_KEY)}`);
333
+ apiKeyTestInfo.push({
334
+ provider: 'Moralis',
335
+ url: `https://deep-index.moralis.io/api/v2/${testAddress}/balance`,
336
+ headers: { 'X-API-Key': process.env.MORALIS_API_KEY },
337
+ responseHandler: this.handleMoralisResponse,
338
+ });
339
+ }
340
+ if (process.env.ETHERSCAN_API_KEY && process.env.DEBUG_ETHEREUM) {
341
+ this.logDebug(`Found an Etherscan key (masked): ${this.maskKey(process.env.ETHERSCAN_API_KEY)}`);
342
+ apiKeyTestInfo.push({
343
+ provider: 'Etherscan',
344
+ url: `https://api.etherscan.io/api?module=account&action=balance&address=${testAddress}&tag=latest&apikey=${process.env.ETHERSCAN_API_KEY}`,
345
+ responseHandler: this.handleEtherscanResponse,
346
+ });
347
+ }
348
+ }
349
+ return apiKeyTestInfo;
350
+ }
351
+ getErrorMessage(error) {
352
+ if (error instanceof Error) {
353
+ return error.message;
354
+ }
355
+ return String(error);
356
+ }
357
+ }
358
+ exports.default = EthereumInitializationService;
359
+ //# sourceMappingURL=ethereum_init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ethereum_init.js","sourceRoot":"","sources":["../../../src/ethereum_init.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,mCAAkD;AAElD,qCAAsD;AACtD,4DAA6C;AAsB7C,yDAAyD;AACzD,MAAM,WAAW,GAAG,CAAC,OAA8B,EAAE,EAAE,CACrD,OAAO,CAAC,IAAI,CACV,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,EAClB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CACjB,CAAC;AAEJ,MAAM,6BAA6B;IAIjC,YACU,YAA0B,EAC1B,QAAmC;QADnC,iBAAY,GAAZ,YAAY,CAAc;QAC1B,aAAQ,GAAR,QAAQ,CAA2B;QALrC,gBAAW,GAAY,KAAK,CAAC;QAsOrC,qEAAqE;QAC7D,yBAAoB,GAAG,CAAC,KAAc,EAAU,EAAE;YACxD,MAAM,YAAY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,IAAI,CAAC,QAAQ,CAAC,iCAAiC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;gBAC5F,cAAc,CAAC,IAAI,CAAC;oBAClB,QAAQ,EAAE,SAAS;oBACnB,GAAG,EAAE,wCAAwC,WAAW,UAAU;oBAClE,OAAO,EAAE,EAAE,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE;oBACrD,eAAe,EAAE,IAAI,CAAC,qBAAqB;iBAC5C,CAAC,CAAC;aACJ;YACD,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE;gBAC/D,IAAI,CAAC,QAAQ,CAAC,oCAAoC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC;gBACjG,cAAc,CAAC,IAAI,CAAC;oBAClB,QAAQ,EAAE,WAAW;oBACrB,GAAG,EAAE,sEAAsE,WAAW,sBAAsB,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;oBAC3I,eAAe,EAAE,IAAI,CAAC,uBAAuB;iBAC9C,CAAC,CAAC;aACJ;SACF;QACD,OAAO,cAAc,CAAC;IACxB,CAAC;IA0BO,eAAe,CAAC,KAAc;QACpC,IAAI,KAAK,YAAY,KAAK,EAAE;YAC1B,OAAO,KAAK,CAAC,OAAO,CAAC;SACtB;QACD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;CACF;AAED,kBAAe,6BAA6B,CAAC"}
@@ -1,6 +1,8 @@
1
1
  import type { LunchMoneyCryptoConnection, LunchMoneyCryptoConnectionContext, LunchMoneyCryptoConnectionConfig } from './types.js';
2
2
  import { EthereumWalletClient } from './client.js';
3
+ import EthereumInitializationService, { EthereumIntegrationType } from './ethereum_init.js';
3
4
  export { createEthereumWalletClient } from './client.js';
5
+ export { EthereumInitializationService, EthereumIntegrationType };
4
6
  interface LunchMoneyEthereumWalletConnectionConfig extends LunchMoneyCryptoConnectionConfig {
5
7
  /** The unique ID of the user's wallet address on the blockchain. */
6
8
  walletAddress: string;
@@ -1,27 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -31,24 +8,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
9
  });
33
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
34
14
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.LunchMoneyEthereumWalletConnection = exports.createEthereumWalletClient = void 0;
36
- const client_js_1 = require("./client.js");
37
- const ethers = __importStar(require("ethers"));
38
- var client_js_2 = require("./client.js");
39
- Object.defineProperty(exports, "createEthereumWalletClient", { enumerable: true, get: function () { return client_js_2.createEthereumWalletClient; } });
15
+ exports.LunchMoneyEthereumWalletConnection = exports.EthereumInitializationService = exports.createEthereumWalletClient = void 0;
16
+ const ethereum_init_js_1 = __importDefault(require("./ethereum_init.js"));
17
+ exports.EthereumInitializationService = ethereum_init_js_1.default;
18
+ var client_js_1 = require("./client.js");
19
+ Object.defineProperty(exports, "createEthereumWalletClient", { enumerable: true, get: function () { return client_js_1.createEthereumWalletClient; } });
40
20
  /** The minimum balance (in wei) that a token should have in order to be
41
21
  * considered for returning as a balance. */
42
22
  const NEGLIGIBLE_BALANCE_THRESHOLD = 1000;
43
- /**
44
- * Debug function that logs to console.log if DEBUG_ETHEREUM environment variable is set
45
- */
46
- const debug = (...args) => {
47
- if (process.env.DEBUG_ETHEREUM) {
48
- const timestamp = new Date().toISOString();
49
- console.log(`[DEBUG_ETHEREUM] [${timestamp}]`, ...args);
50
- }
51
- };
52
23
  exports.LunchMoneyEthereumWalletConnection = {
53
24
  initiate(config, context) {
54
25
  return __awaiter(this, void 0, void 0, function* () {
@@ -57,63 +28,7 @@ exports.LunchMoneyEthereumWalletConnection = {
57
28
  },
58
29
  getBalances({ walletAddress, negligibleBalanceThreshold = NEGLIGIBLE_BALANCE_THRESHOLD }, { client }) {
59
30
  return __awaiter(this, void 0, void 0, function* () {
60
- const obscuredWalletAddress = `0x..${walletAddress.slice(-6)}`;
61
- debug('getBalances called for wallet address:', obscuredWalletAddress);
62
- // Create a timeout so we fail instead of generating a CORS errors
63
- let timeoutId;
64
- const timeoutDuration = process.env.ETHEREUM_BALANCE_TIMEOUT_MSECS
65
- ? parseInt(process.env.ETHEREUM_BALANCE_TIMEOUT_MSECS)
66
- : 60000;
67
- const timeout = new Promise((_, reject) => {
68
- timeoutId = setTimeout(() => {
69
- reject(new Error(`Ethereum connector getBalances timed out after ${timeoutDuration} milliseconds.`));
70
- }, timeoutDuration);
71
- });
72
- // Wrap all ethers calls in a single timeout
73
- const result = yield Promise.race([
74
- (() => __awaiter(this, void 0, void 0, function* () {
75
- try {
76
- const weiBalance = yield client.getWeiBalance(walletAddress);
77
- // Filter out tokens that are not on mainnet
78
- const chainId = yield client.getChainId();
79
- const chainFilteredTokensList = (yield (0, client_js_1.loadTokenList)()).filter((t) => BigInt(t.chainId) === BigInt(chainId));
80
- const map = yield client.getTokensBalance(walletAddress, chainFilteredTokensList.map((t) => t.address));
81
- return { weiBalance, chainId, map, chainFilteredTokensList };
82
- }
83
- finally {
84
- // Clear the timeout when the operation completes (success or failure)
85
- if (timeoutId) {
86
- clearTimeout(timeoutId);
87
- }
88
- }
89
- }))(),
90
- timeout,
91
- ]);
92
- const { weiBalance, chainId, map, chainFilteredTokensList } = result;
93
- debug('ethers.getTokensBalance returned for wallet address:', obscuredWalletAddress);
94
- const balances = Object.entries(map)
95
- .map(([address, balance]) => {
96
- const token = chainFilteredTokensList.find((t) => t.address === address);
97
- if (!token) {
98
- throw new Error(`Token ${address} not found in filtered token list for chainId ${chainId}`);
99
- }
100
- return {
101
- asset: token.symbol,
102
- undivisedAmount: balance,
103
- decimals: token.decimals,
104
- };
105
- })
106
- .concat({ asset: 'ETH', undivisedAmount: weiBalance, decimals: 18 })
107
- .map(({ asset, undivisedAmount, decimals }) => ({ asset, amount: ethers.formatUnits(undivisedAmount, decimals) }))
108
- // Normalize the amount to 18 decimal places (for the wei per eth standard) for filtering out negligible balances
109
- .filter((b) => ethers.parseUnits(b.amount, 18) > negligibleBalanceThreshold)
110
- .map((b) => ({ asset: b.asset, amount: String(b.amount) }))
111
- .sort((a, b) => a.asset.localeCompare(b.asset));
112
- debug(`Returning from getBalances for ${obscuredWalletAddress}:`, balances);
113
- return {
114
- providerName: 'wallet_ethereum',
115
- balances,
116
- };
31
+ return client.getBalances(walletAddress, negligibleBalanceThreshold);
117
32
  });
118
33
  },
119
34
  };
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","s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,QAAQ;aACT,CAAC;QACJ,CAAC;KAAA;CACF,CAAC"}
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../../../src/main.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,0EAA4F;AAGnF,wCAHF,0BAA6B,CAGE;AADtC,yCAAyD;AAAhD,uHAAA,0BAA0B,OAAA;AAGnC;4CAC4C;AAC5C,MAAM,4BAA4B,GAAG,IAAI,CAAC;AAY7B,QAAA,kCAAkC,GAG3C;IACI,QAAQ,CAAC,MAAM,EAAE,OAAO;;YAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC3C,CAAC;KAAA;IAEK,WAAW,CAAC,EAAE,aAAa,EAAE,0BAA0B,GAAG,4BAA4B,EAAE,EAAE,EAAE,MAAM,EAAE;;YACxG,OAAO,MAAM,CAAC,WAAW,CAAC,aAAa,EAAE,0BAA0B,CAAC,CAAC;QACvE,CAAC;KAAA;CACF,CAAC"}
@@ -1,11 +1,42 @@
1
1
  import * as ethscan from '@mycrypto/eth-scan';
2
- import * as ethers from 'ethers';
2
+ import { type Provider, type AbstractProvider } from 'ethers';
3
+ import { EthersProviderLike } from '@mycrypto/eth-scan/typings/src/providers/ethers.js';
4
+ import type { LunchMoneyCryptoConnectionBalances } from './types.js';
5
+ export type ProviderInfo = {
6
+ type: 'Service Provider' | 'API Provider';
7
+ name: string;
8
+ status: 'SUCCESS' | 'FAILED';
9
+ apiKey?: string;
10
+ provider?: Provider | AbstractProvider;
11
+ customProvider?: EthersProviderLike;
12
+ error?: string;
13
+ network?: string;
14
+ balance?: string;
15
+ };
16
+ /**
17
+ * Debug function that logs to console.log if DEBUG_ETHEREUM environment variable is set
18
+ */
19
+ export declare const debug: (...args: unknown[]) => void;
3
20
  export interface EthereumWalletClient {
4
- getChainId(): Promise<bigint>;
5
- getWeiBalance(walletAddress: string): Promise<bigint>;
6
- getTokensBalance(walletAddress: string, tokenContractAddresses: string[]): Promise<ethscan.BalanceMap<bigint>>;
21
+ getBalances(walletAddress: string, negligibleBalanceThreshold: number): Promise<LunchMoneyCryptoConnectionBalances>;
22
+ getWeiBalance(walletAddress: string, provider: AbstractProvider): Promise<bigint>;
23
+ getChainId(provider: AbstractProvider): Promise<bigint>;
24
+ getTokensBalance(walletAddress: string, tokenContractAddresses: string[], providerInfo: ProviderInfo): Promise<ethscan.BalanceMap<bigint>>;
25
+ discoverTokensHybrid(walletAddress: string, chainId: bigint): Promise<string[]>;
26
+ }
27
+ export declare class EtherscanProvider {
28
+ private apiKey;
29
+ private baseUrl;
30
+ constructor(apiKey: string);
31
+ discoverTokensForWallet(address: string, chainId?: bigint): Promise<string[]>;
32
+ }
33
+ export declare class MoralisProvider {
34
+ private apiKey;
35
+ private baseUrl;
36
+ constructor(apiKey: string);
37
+ discoverTokensForWallet(address: string, chainId?: bigint): Promise<string[]>;
7
38
  }
8
- export declare const createEthereumWalletClient: (provider: ethers.AbstractProvider) => EthereumWalletClient;
39
+ export declare const createEthereumWalletClient: (serviceProviderInfo?: ProviderInfo[], walletAPIProviderInfo?: ProviderInfo[]) => EthereumWalletClient;
9
40
  interface Token {
10
41
  address: string;
11
42
  chainId: number;