@cityofzion/bs-ethereum 3.0.3 → 3.0.5

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.
@@ -36,9 +36,9 @@ export declare class BSEthereum<N extends string = string, A extends string = TB
36
36
  validateEncrypted(json: string): boolean;
37
37
  validateKey(key: string): boolean;
38
38
  validateNameServiceDomainFormat(domainName: string): boolean;
39
- generateAccountFromMnemonic(mnemonic: string[] | string, index: number): TBSAccount<N>;
40
- generateAccountFromKey(key: string): TBSAccount<N>;
41
- generateAccountFromPublicKey(publicKey: string): TBSAccount<N>;
39
+ generateAccountFromMnemonic(mnemonic: string[] | string, index: number): Promise<TBSAccount<N>>;
40
+ generateAccountFromKey(key: string): Promise<TBSAccount<N>>;
41
+ generateAccountFromPublicKey(publicKey: string): Promise<TBSAccount<N>>;
42
42
  decrypt(json: string, password: string): Promise<TBSAccount<N>>;
43
43
  encrypt(key: string, password: string): Promise<string>;
44
44
  transfer(param: TTransferParam<N>): Promise<string[]>;
@@ -32,15 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
35
  var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
45
36
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
46
37
  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");
@@ -80,47 +71,46 @@ class BSEthereum {
80
71
  return;
81
72
  this.availableNetworks = BSEthereumConstants_1.BSEthereumConstants.NETWORKS_BY_EVM[evm];
82
73
  this.defaultNetwork = this.availableNetworks.find(network => network.type === 'mainnet');
83
- this.setNetwork(network !== null && network !== void 0 ? network : this.defaultNetwork);
74
+ this.setNetwork(network ?? this.defaultNetwork);
84
75
  }
85
- _buildTransferParams(intent) {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
88
- const amount = ethersBigNumber.parseFixed(intent.amount, intent.token.decimals);
89
- const gasPrice = yield provider.getGasPrice();
90
- let transactionParams = {
91
- type: 2,
92
- };
93
- const isNative = this.tokenService.predicateByHash(this.feeToken, intent.token.hash);
94
- if (isNative) {
95
- transactionParams.to = intent.receiverAddress;
96
- transactionParams.value = amount;
97
- }
98
- else {
99
- const contract = new ethers_1.ethers.Contract(intent.token.hash, [
100
- 'function transfer(address to, uint amount) returns (bool)',
101
- ]);
102
- const populatedTransaction = yield contract.populateTransaction.transfer(intent.receiverAddress, amount);
103
- transactionParams = Object.assign(Object.assign({}, populatedTransaction), transactionParams);
104
- }
105
- return {
106
- transactionParams,
107
- gasPrice,
76
+ async _buildTransferParams(intent) {
77
+ const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
78
+ const amount = ethersBigNumber.parseFixed(intent.amount, intent.token.decimals);
79
+ const gasPrice = await provider.getGasPrice();
80
+ let transactionParams = {
81
+ type: 2,
82
+ };
83
+ const isNative = this.tokenService.predicateByHash(this.feeToken, intent.token.hash);
84
+ if (isNative) {
85
+ transactionParams.to = intent.receiverAddress;
86
+ transactionParams.value = amount;
87
+ }
88
+ else {
89
+ const contract = new ethers_1.ethers.Contract(intent.token.hash, [
90
+ 'function transfer(address to, uint amount) returns (bool)',
91
+ ]);
92
+ const populatedTransaction = await contract.populateTransaction.transfer(intent.receiverAddress, amount);
93
+ transactionParams = {
94
+ ...populatedTransaction,
95
+ ...transactionParams,
108
96
  };
109
- });
97
+ }
98
+ return {
99
+ transactionParams,
100
+ gasPrice,
101
+ };
110
102
  }
111
- generateSigner(account) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
114
- if (account.isHardware) {
115
- if (!this.ledgerService.getLedgerTransport)
116
- throw new Error('You must provide getLedgerTransport function to use Ledger');
117
- if (typeof account.bip44Path !== 'string')
118
- throw new Error('Your account must have bip44 path to use Ledger');
119
- const ledgerTransport = yield this.ledgerService.getLedgerTransport(account);
120
- return this.ledgerService.getSigner(ledgerTransport, account.bip44Path, provider);
121
- }
122
- return new ethers_1.ethers.Wallet(account.key, provider);
123
- });
103
+ async generateSigner(account) {
104
+ const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
105
+ if (account.isHardware) {
106
+ if (!this.ledgerService.getLedgerTransport)
107
+ throw new Error('You must provide getLedgerTransport function to use Ledger');
108
+ if (typeof account.bip44Path !== 'string')
109
+ throw new Error('Your account must have bip44 path to use Ledger');
110
+ const ledgerTransport = await this.ledgerService.getLedgerTransport(account);
111
+ return this.ledgerService.getSigner(ledgerTransport, account.bip44Path, provider);
112
+ }
113
+ return new ethers_1.ethers.Wallet(account.key, provider);
124
114
  }
125
115
  setNetwork(network) {
126
116
  const rpcNetworkUrls = BSEthereumConstants_1.BSEthereumConstants.RPC_LIST_BY_NETWORK_ID[network.id] || [];
@@ -140,22 +130,20 @@ class BSEthereum {
140
130
  this.fullTransactionsDataService = new MoralisFullTransactionsDataServiceEthereum_1.MoralisFullTransactionsDataServiceEthereum(this);
141
131
  }
142
132
  // This method is done manually because we need to ensure that the request is aborted after timeout
143
- pingNode(url) {
144
- return __awaiter(this, void 0, void 0, function* () {
145
- const abortController = new AbortController();
146
- const timeout = setTimeout(() => {
147
- abortController.abort();
148
- }, 5000);
149
- const timeStart = Date.now();
150
- const response = yield axios_1.default.post(url, { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1234 }, { timeout: 5000, signal: abortController.signal });
151
- clearTimeout(timeout);
152
- const latency = Date.now() - timeStart;
153
- return {
154
- latency,
155
- url,
156
- height: ethers_1.ethers.BigNumber.from(response.data.result).toNumber(),
157
- };
158
- });
133
+ async pingNode(url) {
134
+ const abortController = new AbortController();
135
+ const timeout = setTimeout(() => {
136
+ abortController.abort();
137
+ }, 5000);
138
+ const timeStart = Date.now();
139
+ const response = await axios_1.default.post(url, { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1234 }, { timeout: 5000, signal: abortController.signal });
140
+ clearTimeout(timeout);
141
+ const latency = Date.now() - timeStart;
142
+ return {
143
+ latency,
144
+ url,
145
+ height: ethers_1.ethers.BigNumber.from(response.data.result).toNumber(),
146
+ };
159
147
  }
160
148
  validateAddress(address) {
161
149
  return ethers_1.ethers.utils.isAddress(address);
@@ -170,14 +158,14 @@ class BSEthereum {
170
158
  }
171
159
  return ethersBytes.hexDataLength(key) === 32;
172
160
  }
173
- catch (_a) {
161
+ catch {
174
162
  return false;
175
163
  }
176
164
  }
177
165
  validateNameServiceDomainFormat(domainName) {
178
166
  return domainName.endsWith('.eth');
179
167
  }
180
- generateAccountFromMnemonic(mnemonic, index) {
168
+ async generateAccountFromMnemonic(mnemonic, index) {
181
169
  const bip44Path = this.bip44DerivationPath.replace('?', index.toString());
182
170
  const hd = ethers_1.ethers.utils.HDNode.fromMnemonic(Array.isArray(mnemonic) ? mnemonic.join(' ') : mnemonic).derivePath(bip44Path);
183
171
  return {
@@ -188,7 +176,7 @@ class BSEthereum {
188
176
  blockchain: this.name,
189
177
  };
190
178
  }
191
- generateAccountFromKey(key) {
179
+ async generateAccountFromKey(key) {
192
180
  const wallet = new ethers_1.ethers.Wallet(key);
193
181
  return {
194
182
  address: wallet.address,
@@ -197,7 +185,7 @@ class BSEthereum {
197
185
  blockchain: this.name,
198
186
  };
199
187
  }
200
- generateAccountFromPublicKey(publicKey) {
188
+ async generateAccountFromPublicKey(publicKey) {
201
189
  const address = ethers_1.ethers.utils.computeAddress(publicKey);
202
190
  return {
203
191
  address,
@@ -206,75 +194,70 @@ class BSEthereum {
206
194
  blockchain: this.name,
207
195
  };
208
196
  }
209
- decrypt(json, password) {
210
- return __awaiter(this, void 0, void 0, function* () {
211
- const wallet = yield ethers_1.ethers.Wallet.fromEncryptedJson(json, password);
212
- return {
213
- address: wallet.address,
214
- key: wallet.privateKey,
215
- type: 'privateKey',
216
- blockchain: this.name,
217
- };
218
- });
197
+ async decrypt(json, password) {
198
+ const wallet = await ethers_1.ethers.Wallet.fromEncryptedJson(json, password);
199
+ return {
200
+ address: wallet.address,
201
+ key: wallet.privateKey,
202
+ type: 'privateKey',
203
+ blockchain: this.name,
204
+ };
219
205
  }
220
- encrypt(key, password) {
221
- return __awaiter(this, void 0, void 0, function* () {
222
- const wallet = new ethers_1.ethers.Wallet(key);
223
- return wallet.encrypt(password);
224
- });
206
+ async encrypt(key, password) {
207
+ const wallet = new ethers_1.ethers.Wallet(key);
208
+ return wallet.encrypt(password);
225
209
  }
226
- transfer(param) {
227
- return __awaiter(this, void 0, void 0, function* () {
228
- const signer = yield this.generateSigner(param.senderAccount);
229
- const sentTransactionHashes = [];
230
- let error;
231
- for (const intent of param.intents) {
232
- let transactionHash = '';
210
+ async transfer(param) {
211
+ const signer = await this.generateSigner(param.senderAccount);
212
+ const sentTransactionHashes = [];
213
+ let error;
214
+ for (const intent of param.intents) {
215
+ let transactionHash = '';
216
+ try {
217
+ const { transactionParams, gasPrice } = await this._buildTransferParams(intent);
218
+ let gasLimit;
233
219
  try {
234
- const { transactionParams, gasPrice } = yield this._buildTransferParams(intent);
235
- let gasLimit;
236
- try {
237
- gasLimit = yield signer.estimateGas(transactionParams);
238
- }
239
- catch (_a) {
240
- gasLimit = BSEthereumConstants_1.BSEthereumConstants.DEFAULT_GAS_LIMIT;
241
- }
242
- const transaction = yield signer.sendTransaction(Object.assign(Object.assign({}, transactionParams), { gasLimit, maxPriorityFeePerGas: gasPrice, maxFeePerGas: gasPrice }));
243
- transactionHash = transaction.hash;
220
+ gasLimit = await signer.estimateGas(transactionParams);
244
221
  }
245
- catch (err) {
246
- if (!error)
247
- error = err;
222
+ catch {
223
+ gasLimit = BSEthereumConstants_1.BSEthereumConstants.DEFAULT_GAS_LIMIT;
248
224
  }
249
- sentTransactionHashes.push(transactionHash);
225
+ const transaction = await signer.sendTransaction({
226
+ ...transactionParams,
227
+ gasLimit,
228
+ maxPriorityFeePerGas: gasPrice,
229
+ maxFeePerGas: gasPrice,
230
+ });
231
+ transactionHash = transaction.hash;
250
232
  }
251
- if (error && sentTransactionHashes.every(hash => !hash)) {
252
- throw error;
233
+ catch (err) {
234
+ if (!error)
235
+ error = err;
253
236
  }
254
- return sentTransactionHashes;
255
- });
237
+ sentTransactionHashes.push(transactionHash);
238
+ }
239
+ if (error && sentTransactionHashes.every(hash => !hash)) {
240
+ throw error;
241
+ }
242
+ return sentTransactionHashes;
256
243
  }
257
- calculateTransferFee(param) {
258
- return __awaiter(this, void 0, void 0, function* () {
259
- const signer = yield this.generateSigner(param.senderAccount);
260
- let fee = ethers_1.ethers.utils.parseEther('0');
261
- for (const intent of param.intents) {
262
- const { gasPrice, transactionParams } = yield this._buildTransferParams(intent);
263
- const estimated = yield signer.estimateGas(transactionParams);
264
- const intentFee = gasPrice.mul(estimated);
265
- fee = fee.add(intentFee);
266
- }
267
- return ethers_1.ethers.utils.formatEther(fee);
268
- });
244
+ async calculateTransferFee(param) {
245
+ const signer = await this.generateSigner(param.senderAccount);
246
+ let fee = ethers_1.ethers.utils.parseEther('0');
247
+ for (const intent of param.intents) {
248
+ const { gasPrice, transactionParams } = await this._buildTransferParams(intent);
249
+ const estimated = await signer.estimateGas(transactionParams);
250
+ const intentFee = gasPrice.mul(estimated);
251
+ fee = fee.add(intentFee);
252
+ }
253
+ return ethers_1.ethers.utils.formatEther(fee);
269
254
  }
270
- resolveNameServiceDomain(domainName) {
271
- return __awaiter(this, void 0, void 0, function* () {
272
- const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
273
- const address = yield provider.resolveName(domainName);
274
- if (!address)
275
- throw new Error('No address found for domain name');
276
- return address;
277
- });
255
+ async resolveNameServiceDomain(domainName) {
256
+ const provider = new ethers_1.ethers.providers.JsonRpcProvider(this.network.url);
257
+ const address = await provider.resolveName(domainName);
258
+ if (!address)
259
+ throw new Error('No address found for domain name');
260
+ return address;
278
261
  }
279
262
  }
280
263
  exports.BSEthereum = BSEthereum;
@@ -4,8 +4,7 @@ exports.BSEthereumHelper = void 0;
4
4
  const BSEthereumConstants_1 = require("../constants/BSEthereumConstants");
5
5
  class BSEthereumHelper {
6
6
  static getNativeAsset(network) {
7
- var _a;
8
- const symbol = (_a = BSEthereumConstants_1.BSEthereumConstants.NATIVE_SYMBOL_BY_NETWORK_ID[network.id]) !== null && _a !== void 0 ? _a : 'ETH';
7
+ const symbol = BSEthereumConstants_1.BSEthereumConstants.NATIVE_SYMBOL_BY_NETWORK_ID[network.id] ?? 'ETH';
9
8
  return { symbol, name: symbol, decimals: 18, hash: '0x' };
10
9
  }
11
10
  static isMainnetNetwork(service) {
@@ -1,12 +1,12 @@
1
1
  import { TBalanceResponse, TBSToken, TBSNetwork, TBSNetworkId, type TContractResponse, type TTransaction, type TGetTransactionsByAddressResponse, type TGetTransactionsByAddressParams } from '@cityofzion/blockchain-service';
2
- import { AxiosInstance } from 'axios';
2
+ import axios from 'axios';
3
3
  import { IBSEthereum, TBSEthereumNetworkId } from '../../types';
4
4
  import { RpcBDSEthereum } from './RpcBDSEthereum';
5
5
  export declare class MoralisBDSEthereum<N extends string, A extends TBSNetworkId> extends RpcBDSEthereum<N, A> {
6
6
  #private;
7
7
  static readonly BASE_URL: string;
8
8
  static readonly MORALIS_SUPPORTED_NETWORKS_IDS: TBSEthereumNetworkId[];
9
- static getClient(network: TBSNetwork<TBSEthereumNetworkId>): AxiosInstance;
9
+ static getClient(network: TBSNetwork<TBSEthereumNetworkId>): axios.AxiosInstance;
10
10
  static isSupported(network: TBSNetwork<TBSEthereumNetworkId>): boolean;
11
11
  constructor(service: IBSEthereum<N, A>);
12
12
  getBalance(address: string): Promise<TBalanceResponse[]>;