@octaflowlabs/onchain-sdk 1.0.0-test9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/blockchain/broadcastTransaction.d.ts +1 -1
  2. package/dist/blockchain/broadcastTransaction.js +2 -2
  3. package/dist/blockchain/buildUnsignedTransferTx.d.ts +2 -1
  4. package/dist/blockchain/buildUnsignedTransferTx.js +38 -1
  5. package/dist/blockchain/estimateGasLimitFromProvider.js +15 -2
  6. package/dist/blockchain/getProvider.js +4 -2
  7. package/dist/cjs/blockchain/broadcastTransaction.d.ts +1 -1
  8. package/dist/cjs/blockchain/broadcastTransaction.js +2 -2
  9. package/dist/cjs/blockchain/buildUnsignedTransferTx.d.ts +2 -1
  10. package/dist/cjs/blockchain/buildUnsignedTransferTx.js +39 -1
  11. package/dist/cjs/blockchain/estimateGasLimitFromProvider.js +15 -2
  12. package/dist/cjs/blockchain/getProvider.js +4 -2
  13. package/dist/cjs/index.d.ts +7 -2
  14. package/dist/cjs/index.js +12 -1
  15. package/dist/cjs/services/evm-wallet-core/entropy.d.ts +3 -0
  16. package/dist/cjs/services/evm-wallet-core/entropy.js +2 -0
  17. package/dist/cjs/services/evm-wallet-core/evmWalletService.d.ts +27 -0
  18. package/dist/cjs/services/evm-wallet-core/evmWalletService.js +90 -0
  19. package/dist/cjs/services/evm-wallet-core/signer.d.ts +7 -0
  20. package/dist/cjs/services/evm-wallet-core/signer.js +17 -0
  21. package/dist/cjs/types/common.d.ts +18 -0
  22. package/dist/cjs/utils/formatAmount.d.ts +6 -0
  23. package/dist/cjs/utils/formatAmount.js +55 -0
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +5 -1
  26. package/dist/services/evm-wallet-core/entropy.d.ts +3 -0
  27. package/dist/services/evm-wallet-core/entropy.js +1 -0
  28. package/dist/services/evm-wallet-core/evmWalletService.d.ts +27 -0
  29. package/dist/services/evm-wallet-core/evmWalletService.js +86 -0
  30. package/dist/services/evm-wallet-core/signer.d.ts +7 -0
  31. package/dist/services/evm-wallet-core/signer.js +11 -0
  32. package/dist/types/common.d.ts +18 -0
  33. package/dist/utils/formatAmount.d.ts +6 -0
  34. package/dist/utils/formatAmount.js +50 -0
  35. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
1
  import { BroadcastTransactionOptions } from '../types/common';
2
- export declare const broadcastTransaction: ({ signedTx, rpcUrl, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
2
+ export declare const broadcastTransaction: ({ signedTx, rpcUrl, chainId, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
@@ -2,8 +2,8 @@
2
2
  import { Transaction } from 'ethers';
3
3
  /** local imports */
4
4
  import { getProvider } from './getProvider';
5
- export const broadcastTransaction = async ({ signedTx, rpcUrl, waitConfirmations = 0, }) => {
6
- const provider = getProvider(rpcUrl);
5
+ export const broadcastTransaction = async ({ signedTx, rpcUrl, chainId, waitConfirmations = 0, }) => {
6
+ const provider = getProvider(rpcUrl, chainId);
7
7
  if (!provider)
8
8
  throw new Error('Could not create provider with given rpcUrl');
9
9
  try {
@@ -1,2 +1,3 @@
1
- import { BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
1
+ import { BuildMaxNativeTransferTxOptions, BuildMaxNativeTransferTxResponse, BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
2
2
  export declare const buildUnsignedTransferTx: (options: BuildUnsignedTransferTxOptions) => Promise<UnsignedTransferTxResponse>;
3
+ export declare const buildMaxNativeTransferTx: (options: BuildMaxNativeTransferTxOptions) => Promise<BuildMaxNativeTransferTxResponse>;
@@ -1,9 +1,10 @@
1
1
  /** npm imports */
2
- import { Interface, parseUnits } from 'ethers';
2
+ import { Interface, formatUnits, parseUnits } from 'ethers';
3
3
  /** local imports */
4
4
  import { getProvider } from './getProvider';
5
5
  import { estimateGasLimitFromProvider } from './estimateGasLimitFromProvider';
6
6
  export const buildUnsignedTransferTx = async (options) => {
7
+ console.log({ options });
7
8
  const provider = getProvider(options.rpcUrl, options.chainId);
8
9
  if (!provider)
9
10
  throw new Error('Could not create provider with given rpcUrl and chainId');
@@ -60,6 +61,12 @@ export const buildUnsignedTransferTx = async (options) => {
60
61
  };
61
62
  if (estimateGas.feeData.gasPrice)
62
63
  unsignedTxToReturn.gasPrice = estimateGas.feeData.gasPrice.toString();
64
+ const gasReserve = estimateGas.feeData.maxFeePerGas
65
+ ? estimateGas.gasLimit * estimateGas.feeData.maxFeePerGas
66
+ : estimateGas.feeData.gasPrice
67
+ ? estimateGas.gasLimit * estimateGas.feeData.gasPrice
68
+ : undefined;
69
+ console.log({ gasReserve: gasReserve?.toString() });
63
70
  try {
64
71
  await provider.call({
65
72
  from: options.fromAddress,
@@ -78,6 +85,7 @@ export const buildUnsignedTransferTx = async (options) => {
78
85
  nonce,
79
86
  gasEstimated: estimateGas.gasEstimated.toString(),
80
87
  gasLimit: estimateGas.gasLimit.toString(),
88
+ gasReserve: gasReserve?.toString(),
81
89
  bufferPercentage: estimateGas.bufferPercentage,
82
90
  feeData: {
83
91
  maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
@@ -93,3 +101,32 @@ export const buildUnsignedTransferTx = async (options) => {
93
101
  throw error;
94
102
  }
95
103
  };
104
+ export const buildMaxNativeTransferTx = async (options) => {
105
+ const isNativeToken = !options.tokenAddress ||
106
+ options.tokenAddress?.toLowerCase() === '0x0000000000000000000000000000000000000000' ||
107
+ options.tokenAddress?.toLowerCase() === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
108
+ if (!isNativeToken)
109
+ throw new Error('Max native transfer requires a native token address');
110
+ const provisionalTx = await buildUnsignedTransferTx({
111
+ ...options,
112
+ value: '0',
113
+ tokenAddress: options.tokenAddress,
114
+ });
115
+ if (!provisionalTx.gasReserve)
116
+ throw new Error('Could not determine gas reserve for max send');
117
+ const balanceWei = parseUnits(options.balance, 18);
118
+ const gasReserveWei = BigInt(provisionalTx.gasReserve);
119
+ const sendableWei = balanceWei - gasReserveWei;
120
+ if (sendableWei <= 0n)
121
+ throw new Error('Insufficient balance to cover gas reserve');
122
+ const sendableValue = formatUnits(sendableWei, 18);
123
+ const finalTx = await buildUnsignedTransferTx({
124
+ ...options,
125
+ value: sendableValue,
126
+ tokenAddress: options.tokenAddress,
127
+ });
128
+ return {
129
+ ...finalTx,
130
+ sendableValue,
131
+ };
132
+ };
@@ -1,6 +1,9 @@
1
1
  export const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddress, defaultGasLimit, }) => {
2
+ let lastFeeData = null;
3
+ let lastGasEstimated = null;
2
4
  try {
3
5
  const feeData = await provider.getFeeData();
6
+ lastFeeData = feeData;
4
7
  const txForEstimation = { ...unsignedTx, from: walletAddress };
5
8
  if (feeData.maxFeePerGas !== undefined)
6
9
  txForEstimation.maxFeePerGas = feeData.maxFeePerGas;
@@ -8,7 +11,9 @@ export const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walle
8
11
  txForEstimation.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
9
12
  if (feeData.gasPrice !== undefined && txForEstimation.maxFeePerGas === undefined)
10
13
  txForEstimation.gasPrice = feeData.gasPrice;
14
+ console.log('Estimating gas with transaction:!!!!!! ', txForEstimation);
11
15
  const gasEstimated = await provider.estimateGas(txForEstimation);
16
+ lastGasEstimated = gasEstimated;
12
17
  let congestionFactor = 1.5;
13
18
  if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) {
14
19
  try {
@@ -40,12 +45,20 @@ export const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walle
40
45
  catch (error) {
41
46
  console.error('Unable to estimate gas limit: ', error);
42
47
  console.log(`Setting default gas limit to: ${defaultGasLimit}`);
48
+ const feeData = lastFeeData;
49
+ const gasEstimated = lastGasEstimated ?? defaultGasLimit;
43
50
  return {
44
- gasEstimated: defaultGasLimit,
51
+ gasEstimated,
45
52
  gasLimit: defaultGasLimit,
46
53
  bufferPercentage: 0,
47
54
  fallbackUsed: true,
48
- feeData: {},
55
+ feeData: feeData
56
+ ? {
57
+ maxFeePerGas: feeData.maxFeePerGas ?? undefined,
58
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined,
59
+ gasPrice: feeData.gasPrice ?? undefined,
60
+ }
61
+ : {},
49
62
  };
50
63
  }
51
64
  };
@@ -4,8 +4,10 @@ export const getProvider = (rpcUrl, chainId) => {
4
4
  try {
5
5
  if (chainId) {
6
6
  const network = Network.from(chainId);
7
- const provider = new JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
8
- return provider;
7
+ return new JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
8
+ }
9
+ else {
10
+ return new JsonRpcProvider(rpcUrl);
9
11
  }
10
12
  }
11
13
  catch (error) {
@@ -1,2 +1,2 @@
1
1
  import { BroadcastTransactionOptions } from '../types/common';
2
- export declare const broadcastTransaction: ({ signedTx, rpcUrl, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
2
+ export declare const broadcastTransaction: ({ signedTx, rpcUrl, chainId, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
@@ -5,8 +5,8 @@ exports.broadcastTransaction = void 0;
5
5
  const ethers_1 = require("ethers");
6
6
  /** local imports */
7
7
  const getProvider_1 = require("./getProvider");
8
- const broadcastTransaction = async ({ signedTx, rpcUrl, waitConfirmations = 0, }) => {
9
- const provider = (0, getProvider_1.getProvider)(rpcUrl);
8
+ const broadcastTransaction = async ({ signedTx, rpcUrl, chainId, waitConfirmations = 0, }) => {
9
+ const provider = (0, getProvider_1.getProvider)(rpcUrl, chainId);
10
10
  if (!provider)
11
11
  throw new Error('Could not create provider with given rpcUrl');
12
12
  try {
@@ -1,2 +1,3 @@
1
- import { BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
1
+ import { BuildMaxNativeTransferTxOptions, BuildMaxNativeTransferTxResponse, BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
2
2
  export declare const buildUnsignedTransferTx: (options: BuildUnsignedTransferTxOptions) => Promise<UnsignedTransferTxResponse>;
3
+ export declare const buildMaxNativeTransferTx: (options: BuildMaxNativeTransferTxOptions) => Promise<BuildMaxNativeTransferTxResponse>;
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildUnsignedTransferTx = void 0;
3
+ exports.buildMaxNativeTransferTx = exports.buildUnsignedTransferTx = void 0;
4
4
  /** npm imports */
5
5
  const ethers_1 = require("ethers");
6
6
  /** local imports */
7
7
  const getProvider_1 = require("./getProvider");
8
8
  const estimateGasLimitFromProvider_1 = require("./estimateGasLimitFromProvider");
9
9
  const buildUnsignedTransferTx = async (options) => {
10
+ console.log({ options });
10
11
  const provider = (0, getProvider_1.getProvider)(options.rpcUrl, options.chainId);
11
12
  if (!provider)
12
13
  throw new Error('Could not create provider with given rpcUrl and chainId');
@@ -63,6 +64,12 @@ const buildUnsignedTransferTx = async (options) => {
63
64
  };
64
65
  if (estimateGas.feeData.gasPrice)
65
66
  unsignedTxToReturn.gasPrice = estimateGas.feeData.gasPrice.toString();
67
+ const gasReserve = estimateGas.feeData.maxFeePerGas
68
+ ? estimateGas.gasLimit * estimateGas.feeData.maxFeePerGas
69
+ : estimateGas.feeData.gasPrice
70
+ ? estimateGas.gasLimit * estimateGas.feeData.gasPrice
71
+ : undefined;
72
+ console.log({ gasReserve: gasReserve?.toString() });
66
73
  try {
67
74
  await provider.call({
68
75
  from: options.fromAddress,
@@ -81,6 +88,7 @@ const buildUnsignedTransferTx = async (options) => {
81
88
  nonce,
82
89
  gasEstimated: estimateGas.gasEstimated.toString(),
83
90
  gasLimit: estimateGas.gasLimit.toString(),
91
+ gasReserve: gasReserve?.toString(),
84
92
  bufferPercentage: estimateGas.bufferPercentage,
85
93
  feeData: {
86
94
  maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
@@ -97,3 +105,33 @@ const buildUnsignedTransferTx = async (options) => {
97
105
  }
98
106
  };
99
107
  exports.buildUnsignedTransferTx = buildUnsignedTransferTx;
108
+ const buildMaxNativeTransferTx = async (options) => {
109
+ const isNativeToken = !options.tokenAddress ||
110
+ options.tokenAddress?.toLowerCase() === '0x0000000000000000000000000000000000000000' ||
111
+ options.tokenAddress?.toLowerCase() === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
112
+ if (!isNativeToken)
113
+ throw new Error('Max native transfer requires a native token address');
114
+ const provisionalTx = await (0, exports.buildUnsignedTransferTx)({
115
+ ...options,
116
+ value: '0',
117
+ tokenAddress: options.tokenAddress,
118
+ });
119
+ if (!provisionalTx.gasReserve)
120
+ throw new Error('Could not determine gas reserve for max send');
121
+ const balanceWei = (0, ethers_1.parseUnits)(options.balance, 18);
122
+ const gasReserveWei = BigInt(provisionalTx.gasReserve);
123
+ const sendableWei = balanceWei - gasReserveWei;
124
+ if (sendableWei <= 0n)
125
+ throw new Error('Insufficient balance to cover gas reserve');
126
+ const sendableValue = (0, ethers_1.formatUnits)(sendableWei, 18);
127
+ const finalTx = await (0, exports.buildUnsignedTransferTx)({
128
+ ...options,
129
+ value: sendableValue,
130
+ tokenAddress: options.tokenAddress,
131
+ });
132
+ return {
133
+ ...finalTx,
134
+ sendableValue,
135
+ };
136
+ };
137
+ exports.buildMaxNativeTransferTx = buildMaxNativeTransferTx;
@@ -2,8 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.estimateGasLimitFromProvider = void 0;
4
4
  const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddress, defaultGasLimit, }) => {
5
+ let lastFeeData = null;
6
+ let lastGasEstimated = null;
5
7
  try {
6
8
  const feeData = await provider.getFeeData();
9
+ lastFeeData = feeData;
7
10
  const txForEstimation = { ...unsignedTx, from: walletAddress };
8
11
  if (feeData.maxFeePerGas !== undefined)
9
12
  txForEstimation.maxFeePerGas = feeData.maxFeePerGas;
@@ -11,7 +14,9 @@ const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddres
11
14
  txForEstimation.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
12
15
  if (feeData.gasPrice !== undefined && txForEstimation.maxFeePerGas === undefined)
13
16
  txForEstimation.gasPrice = feeData.gasPrice;
17
+ console.log('Estimating gas with transaction:!!!!!! ', txForEstimation);
14
18
  const gasEstimated = await provider.estimateGas(txForEstimation);
19
+ lastGasEstimated = gasEstimated;
15
20
  let congestionFactor = 1.5;
16
21
  if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) {
17
22
  try {
@@ -43,12 +48,20 @@ const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddres
43
48
  catch (error) {
44
49
  console.error('Unable to estimate gas limit: ', error);
45
50
  console.log(`Setting default gas limit to: ${defaultGasLimit}`);
51
+ const feeData = lastFeeData;
52
+ const gasEstimated = lastGasEstimated ?? defaultGasLimit;
46
53
  return {
47
- gasEstimated: defaultGasLimit,
54
+ gasEstimated,
48
55
  gasLimit: defaultGasLimit,
49
56
  bufferPercentage: 0,
50
57
  fallbackUsed: true,
51
- feeData: {},
58
+ feeData: feeData
59
+ ? {
60
+ maxFeePerGas: feeData.maxFeePerGas ?? undefined,
61
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined,
62
+ gasPrice: feeData.gasPrice ?? undefined,
63
+ }
64
+ : {},
52
65
  };
53
66
  }
54
67
  };
@@ -7,8 +7,10 @@ const getProvider = (rpcUrl, chainId) => {
7
7
  try {
8
8
  if (chainId) {
9
9
  const network = ethers_1.Network.from(chainId);
10
- const provider = new ethers_1.JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
11
- return provider;
10
+ return new ethers_1.JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
11
+ }
12
+ else {
13
+ return new ethers_1.JsonRpcProvider(rpcUrl);
12
14
  }
13
15
  }
14
16
  catch (error) {
@@ -4,15 +4,20 @@ export { ERC20_TOKEN_CONTRACT_ABI };
4
4
  /** constants exports */
5
5
  export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
6
  /** basic blockchain exports */
7
- export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
7
+ export { buildMaxNativeTransferTx, buildUnsignedTransferTx, } from './blockchain/buildUnsignedTransferTx';
8
8
  export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
9
  export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
10
  export { getProvider } from './blockchain/getProvider';
11
11
  export { txStatus } from './blockchain/txStatus';
12
+ /** services exports */
13
+ export { EvmWalletService, EvmGeneratedWallet, EvmDerivedWallet, } from './services/evm-wallet-core/evmWalletService';
14
+ export { EntropySource } from './services/evm-wallet-core/entropy';
15
+ export { createWallet, signMessage, signTransaction } from './services/evm-wallet-core/signer';
12
16
  /** utils exports */
13
17
  export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
18
  export { transformBigInt } from './utils/transformBigInt';
15
19
  import NATIVE_TOKENS from './utils/tokens';
16
20
  export { NATIVE_TOKENS };
21
+ export { formattedAmountForDisplay, parsedAmount } from './utils/formatAmount';
17
22
  /** types exports */
18
- export { BroadcastTransactionOptions, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, } from './types/common';
23
+ export { BroadcastTransactionOptions, BuildMaxNativeTransferTxOptions, BuildMaxNativeTransferTxResponse, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, FormatAmountOptions, TransactionRequest, } from './types/common';
package/dist/cjs/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.NATIVE_TOKENS = exports.transformBigInt = exports.getShortenTransactionHash = exports.txStatus = exports.getProvider = exports.estimateGasLimitFromProvider = exports.broadcastTransaction = exports.buildUnsignedTransferTx = exports.GAS_LIMIT_PER_TX_TYPE = exports.ERC20_TOKEN_CONTRACT_ABI = void 0;
6
+ exports.parsedAmount = exports.formattedAmountForDisplay = exports.NATIVE_TOKENS = exports.transformBigInt = exports.getShortenTransactionHash = exports.signTransaction = exports.signMessage = exports.createWallet = exports.EvmWalletService = exports.txStatus = exports.getProvider = exports.estimateGasLimitFromProvider = exports.broadcastTransaction = exports.buildUnsignedTransferTx = exports.buildMaxNativeTransferTx = exports.GAS_LIMIT_PER_TX_TYPE = exports.ERC20_TOKEN_CONTRACT_ABI = void 0;
7
7
  /** ABIs exports */
8
8
  const ERC20_TOKEN_CONTRACT_ABI_1 = __importDefault(require("./ABIs/ERC20_TOKEN_CONTRACT_ABI"));
9
9
  exports.ERC20_TOKEN_CONTRACT_ABI = ERC20_TOKEN_CONTRACT_ABI_1.default;
@@ -12,6 +12,7 @@ var constants_1 = require("./constants/constants");
12
12
  Object.defineProperty(exports, "GAS_LIMIT_PER_TX_TYPE", { enumerable: true, get: function () { return constants_1.GAS_LIMIT_PER_TX_TYPE; } });
13
13
  /** basic blockchain exports */
14
14
  var buildUnsignedTransferTx_1 = require("./blockchain/buildUnsignedTransferTx");
15
+ Object.defineProperty(exports, "buildMaxNativeTransferTx", { enumerable: true, get: function () { return buildUnsignedTransferTx_1.buildMaxNativeTransferTx; } });
15
16
  Object.defineProperty(exports, "buildUnsignedTransferTx", { enumerable: true, get: function () { return buildUnsignedTransferTx_1.buildUnsignedTransferTx; } });
16
17
  var broadcastTransaction_1 = require("./blockchain/broadcastTransaction");
17
18
  Object.defineProperty(exports, "broadcastTransaction", { enumerable: true, get: function () { return broadcastTransaction_1.broadcastTransaction; } });
@@ -21,6 +22,13 @@ var getProvider_1 = require("./blockchain/getProvider");
21
22
  Object.defineProperty(exports, "getProvider", { enumerable: true, get: function () { return getProvider_1.getProvider; } });
22
23
  var txStatus_1 = require("./blockchain/txStatus");
23
24
  Object.defineProperty(exports, "txStatus", { enumerable: true, get: function () { return txStatus_1.txStatus; } });
25
+ /** services exports */
26
+ var evmWalletService_1 = require("./services/evm-wallet-core/evmWalletService");
27
+ Object.defineProperty(exports, "EvmWalletService", { enumerable: true, get: function () { return evmWalletService_1.EvmWalletService; } });
28
+ var signer_1 = require("./services/evm-wallet-core/signer");
29
+ Object.defineProperty(exports, "createWallet", { enumerable: true, get: function () { return signer_1.createWallet; } });
30
+ Object.defineProperty(exports, "signMessage", { enumerable: true, get: function () { return signer_1.signMessage; } });
31
+ Object.defineProperty(exports, "signTransaction", { enumerable: true, get: function () { return signer_1.signTransaction; } });
24
32
  /** utils exports */
25
33
  var getShortenTxHash_1 = require("./utils/getShortenTxHash");
26
34
  Object.defineProperty(exports, "getShortenTransactionHash", { enumerable: true, get: function () { return getShortenTxHash_1.getShortenTransactionHash; } });
@@ -28,3 +36,6 @@ var transformBigInt_1 = require("./utils/transformBigInt");
28
36
  Object.defineProperty(exports, "transformBigInt", { enumerable: true, get: function () { return transformBigInt_1.transformBigInt; } });
29
37
  const tokens_1 = __importDefault(require("./utils/tokens"));
30
38
  exports.NATIVE_TOKENS = tokens_1.default;
39
+ var formatAmount_1 = require("./utils/formatAmount");
40
+ Object.defineProperty(exports, "formattedAmountForDisplay", { enumerable: true, get: function () { return formatAmount_1.formattedAmountForDisplay; } });
41
+ Object.defineProperty(exports, "parsedAmount", { enumerable: true, get: function () { return formatAmount_1.parsedAmount; } });
@@ -0,0 +1,3 @@
1
+ export interface EntropySource {
2
+ randomBytes(length: number): Uint8Array;
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,27 @@
1
+ /** local imports */
2
+ import { EntropySource } from './entropy';
3
+ export interface EvmGeneratedWallet {
4
+ address: string;
5
+ mnemonic: string;
6
+ privateKey: string;
7
+ path: string;
8
+ }
9
+ export interface EvmDerivedWallet {
10
+ address: string;
11
+ privateKey: string;
12
+ path: string;
13
+ publicKey: string;
14
+ }
15
+ export declare class EvmWalletService {
16
+ private entropy;
17
+ private readonly DEFAULT_DERIVATION_PATH;
18
+ constructor(entropy: EntropySource);
19
+ generateNewWallet(accountIndex?: number, wordCount?: 12 | 15 | 18 | 21 | 24): EvmGeneratedWallet;
20
+ generateMultipleWallets(mnemonic: string, count: number, startIndex?: number): EvmDerivedWallet[];
21
+ deriveWalletFromMnemonic(mnemonic: string, accountIndex?: number, customPath?: string): EvmDerivedWallet;
22
+ deriveFromPrivateKey(privateKey: string): Omit<EvmDerivedWallet, 'path'>;
23
+ signMessage(privateKey: string, message: string): Promise<string>;
24
+ isValidMnemonic(mnemonic: string): boolean;
25
+ private validateMnemonic;
26
+ private getEntropyForWordCount;
27
+ }
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EvmWalletService = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ class EvmWalletService {
7
+ constructor(entropy) {
8
+ this.entropy = entropy;
9
+ this.DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0";
10
+ }
11
+ generateNewWallet(accountIndex = 0, wordCount = 12) {
12
+ const entropy = this.getEntropyForWordCount(wordCount);
13
+ const randomBytesArray = this.entropy.randomBytes(entropy);
14
+ const customMnemonic = ethers_1.Mnemonic.fromEntropy(randomBytesArray);
15
+ const path = `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
16
+ const hdNode = ethers_1.HDNodeWallet.fromMnemonic(customMnemonic, path);
17
+ return {
18
+ address: hdNode.address,
19
+ mnemonic: customMnemonic.phrase,
20
+ privateKey: hdNode.privateKey,
21
+ path,
22
+ };
23
+ }
24
+ generateMultipleWallets(mnemonic, count, startIndex = 0) {
25
+ this.validateMnemonic(mnemonic);
26
+ const wallets = [];
27
+ const mnemonicObject = ethers_1.Mnemonic.fromPhrase(mnemonic);
28
+ for (let i = 0; i < count; i++) {
29
+ const accountIndex = startIndex + i;
30
+ const path = `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
31
+ const hdNode = ethers_1.HDNodeWallet.fromMnemonic(mnemonicObject, path);
32
+ wallets.push({
33
+ address: hdNode.address,
34
+ privateKey: hdNode.privateKey,
35
+ path,
36
+ publicKey: hdNode.publicKey,
37
+ });
38
+ }
39
+ return wallets;
40
+ }
41
+ deriveWalletFromMnemonic(mnemonic, accountIndex = 0, customPath) {
42
+ this.validateMnemonic(mnemonic);
43
+ const path = customPath || `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
44
+ const mnemonicObject = ethers_1.Mnemonic.fromPhrase(mnemonic);
45
+ const hdNode = ethers_1.HDNodeWallet.fromMnemonic(mnemonicObject, path);
46
+ return {
47
+ address: hdNode.address,
48
+ privateKey: hdNode.privateKey,
49
+ path,
50
+ publicKey: hdNode.publicKey,
51
+ };
52
+ }
53
+ deriveFromPrivateKey(privateKey) {
54
+ const wallet = new ethers_1.Wallet(privateKey);
55
+ return {
56
+ address: wallet.address,
57
+ privateKey: wallet.privateKey,
58
+ publicKey: wallet.signingKey.publicKey,
59
+ };
60
+ }
61
+ async signMessage(privateKey, message) {
62
+ const wallet = new ethers_1.Wallet(privateKey);
63
+ return await wallet.signMessage(message);
64
+ }
65
+ isValidMnemonic(mnemonic) {
66
+ try {
67
+ ethers_1.Mnemonic.fromPhrase(mnemonic);
68
+ return true;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ validateMnemonic(mnemonic) {
75
+ if (!this.isValidMnemonic(mnemonic)) {
76
+ throw new Error('Invalid mnemonic phrase');
77
+ }
78
+ }
79
+ getEntropyForWordCount(wordCount) {
80
+ const entropyMap = {
81
+ 12: 16, // 128 bits
82
+ 15: 20, // 160 bits
83
+ 18: 24, // 192 bits
84
+ 21: 28, // 224 bits
85
+ 24: 32, // 256 bits
86
+ };
87
+ return entropyMap[wordCount];
88
+ }
89
+ }
90
+ exports.EvmWalletService = EvmWalletService;
@@ -0,0 +1,7 @@
1
+ /** npm imports */
2
+ import { Wallet } from 'ethers';
3
+ /** local imports */
4
+ import { TransactionRequest } from '../../types/common';
5
+ export declare const createWallet: (privateKey: string, rpcUrl?: string) => Wallet;
6
+ export declare const signMessage: (privateKey: string, message: string) => Promise<string>;
7
+ export declare const signTransaction: (privateKey: string, tx: TransactionRequest, rpcUrl?: string) => Promise<string>;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signTransaction = exports.signMessage = exports.createWallet = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ const createWallet = (privateKey, rpcUrl) => new ethers_1.Wallet(privateKey, rpcUrl ? new ethers_1.JsonRpcProvider(rpcUrl) : undefined);
7
+ exports.createWallet = createWallet;
8
+ const signMessage = async (privateKey, message) => {
9
+ const wallet = (0, exports.createWallet)(privateKey);
10
+ return wallet.signMessage(message);
11
+ };
12
+ exports.signMessage = signMessage;
13
+ const signTransaction = async (privateKey, tx, rpcUrl) => {
14
+ const wallet = (0, exports.createWallet)(privateKey, rpcUrl);
15
+ return wallet.signTransaction(tx);
16
+ };
17
+ exports.signTransaction = signTransaction;
@@ -33,6 +33,7 @@ export interface UnsignedTransferTxResponse {
33
33
  nonce: number;
34
34
  gasEstimated: string;
35
35
  gasLimit: string;
36
+ gasReserve?: string;
36
37
  bufferPercentage: number;
37
38
  feeData: {
38
39
  maxFeePerGas?: string;
@@ -40,9 +41,17 @@ export interface UnsignedTransferTxResponse {
40
41
  gasPrice?: string;
41
42
  };
42
43
  }
44
+ export interface BuildMaxNativeTransferTxOptions extends Omit<BuildUnsignedTransferTxOptions, 'value' | 'tokenAddress' | 'tokenDecimals'> {
45
+ balance: string;
46
+ tokenAddress?: string;
47
+ }
48
+ export interface BuildMaxNativeTransferTxResponse extends UnsignedTransferTxResponse {
49
+ sendableValue: string;
50
+ }
43
51
  export interface BroadcastTransactionOptions {
44
52
  signedTx: string;
45
53
  rpcUrl: string;
54
+ chainId?: number;
46
55
  waitConfirmations?: number;
47
56
  }
48
57
  export interface TxStatusOptions {
@@ -54,3 +63,12 @@ export interface TxStatusResponse {
54
63
  success: boolean;
55
64
  receipt: TransactionReceipt | null;
56
65
  }
66
+ export interface FormatAmountOptions {
67
+ decimalsToShow?: number;
68
+ useGroupSeparator?: boolean;
69
+ locale?: string;
70
+ minimumFractionDigits?: number;
71
+ minDisplayDecimals?: number;
72
+ maxDisplayDigits?: number;
73
+ }
74
+ export type { TransactionRequest };
@@ -0,0 +1,6 @@
1
+ /** npm imports */
2
+ import { BigNumberish } from 'ethers';
3
+ /** local imports */
4
+ import { FormatAmountOptions } from '../types/common';
5
+ export declare const formattedAmountForDisplay: (amount: BigNumberish, decimals: number, options?: FormatAmountOptions) => string;
6
+ export declare const parsedAmount: (amount: string, decimals: number) => bigint;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parsedAmount = exports.formattedAmountForDisplay = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ const formattedAmountForDisplay = (amount, decimals, options = {}) => {
7
+ const { decimalsToShow = 0, useGroupSeparator = true, locale = 'en-US', minimumFractionDigits, minDisplayDecimals = 9, maxDisplayDigits = 16, } = options;
8
+ const formattedAmount = (0, ethers_1.formatUnits)(amount, decimals);
9
+ if (formattedAmount.startsWith('-')) {
10
+ throw new Error('Negative balances are not supported');
11
+ }
12
+ const [wholePart = '0', fractionPart = ''] = formattedAmount.split('.');
13
+ if (wholePart.length >= maxDisplayDigits) {
14
+ const mantissaWhole = wholePart[0] ?? '0';
15
+ const mantissaFraction = (wholePart.slice(1) + fractionPart).slice(0, decimalsToShow);
16
+ const exponent = wholePart.length - 1;
17
+ const rawMantissa = mantissaFraction ? `${mantissaWhole}.${mantissaFraction}` : mantissaWhole;
18
+ const trimmedMantissa = rawMantissa.replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, '').replace(/\.$/, '');
19
+ return `${trimmedMantissa}e${exponent}`;
20
+ }
21
+ const firstNonZeroIndex = fractionPart.split('').findIndex((digit) => digit !== '0');
22
+ const hasNonZeroFraction = firstNonZeroIndex !== -1;
23
+ if (hasNonZeroFraction && wholePart === '0' && firstNonZeroIndex >= minDisplayDecimals) {
24
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
25
+ const decimalSeparator = sample.replace(/\d/g, '').slice(-1) ?? '.';
26
+ const minValue = `0${decimalSeparator}${'0'.repeat(Math.max(0, minDisplayDecimals - 1))}1`;
27
+ return `< ${minValue}`;
28
+ }
29
+ if (!hasNonZeroFraction) {
30
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
31
+ const groupSeparator = sample.replace(/\d/g, '')[0] ?? ',';
32
+ const groupedWhole = useGroupSeparator
33
+ ? (wholePart || '0').replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator)
34
+ : wholePart;
35
+ return groupedWhole;
36
+ }
37
+ const maxDecimals = decimalsToShow ?? fractionPart.length;
38
+ let trimmedFraction = fractionPart.slice(0, Math.max(0, maxDecimals));
39
+ const minDecimals = minimumFractionDigits ?? 0;
40
+ if (trimmedFraction.length < minDecimals) {
41
+ trimmedFraction = trimmedFraction.padEnd(minDecimals, '0');
42
+ }
43
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
44
+ const groupSeparator = sample.replace(/\d/g, '')[0] ?? ',';
45
+ const decimalSeparator = sample.replace(/\d/g, '').slice(-1) ?? '.';
46
+ const groupedWhole = useGroupSeparator
47
+ ? (wholePart || '0').replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator)
48
+ : wholePart;
49
+ if (!trimmedFraction)
50
+ return groupedWhole;
51
+ return `${groupedWhole}${decimalSeparator}${trimmedFraction}`;
52
+ };
53
+ exports.formattedAmountForDisplay = formattedAmountForDisplay;
54
+ const parsedAmount = (amount, decimals) => (0, ethers_1.parseUnits)(amount, decimals);
55
+ exports.parsedAmount = parsedAmount;
package/dist/index.d.ts CHANGED
@@ -4,15 +4,20 @@ export { ERC20_TOKEN_CONTRACT_ABI };
4
4
  /** constants exports */
5
5
  export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
6
  /** basic blockchain exports */
7
- export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
7
+ export { buildMaxNativeTransferTx, buildUnsignedTransferTx, } from './blockchain/buildUnsignedTransferTx';
8
8
  export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
9
  export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
10
  export { getProvider } from './blockchain/getProvider';
11
11
  export { txStatus } from './blockchain/txStatus';
12
+ /** services exports */
13
+ export { EvmWalletService, EvmGeneratedWallet, EvmDerivedWallet, } from './services/evm-wallet-core/evmWalletService';
14
+ export { EntropySource } from './services/evm-wallet-core/entropy';
15
+ export { createWallet, signMessage, signTransaction } from './services/evm-wallet-core/signer';
12
16
  /** utils exports */
13
17
  export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
18
  export { transformBigInt } from './utils/transformBigInt';
15
19
  import NATIVE_TOKENS from './utils/tokens';
16
20
  export { NATIVE_TOKENS };
21
+ export { formattedAmountForDisplay, parsedAmount } from './utils/formatAmount';
17
22
  /** types exports */
18
- export { BroadcastTransactionOptions, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, } from './types/common';
23
+ export { BroadcastTransactionOptions, BuildMaxNativeTransferTxOptions, BuildMaxNativeTransferTxResponse, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, FormatAmountOptions, TransactionRequest, } from './types/common';
package/dist/index.js CHANGED
@@ -4,13 +4,17 @@ export { ERC20_TOKEN_CONTRACT_ABI };
4
4
  /** constants exports */
5
5
  export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
6
  /** basic blockchain exports */
7
- export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
7
+ export { buildMaxNativeTransferTx, buildUnsignedTransferTx, } from './blockchain/buildUnsignedTransferTx';
8
8
  export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
9
  export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
10
  export { getProvider } from './blockchain/getProvider';
11
11
  export { txStatus } from './blockchain/txStatus';
12
+ /** services exports */
13
+ export { EvmWalletService, } from './services/evm-wallet-core/evmWalletService';
14
+ export { createWallet, signMessage, signTransaction } from './services/evm-wallet-core/signer';
12
15
  /** utils exports */
13
16
  export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
17
  export { transformBigInt } from './utils/transformBigInt';
15
18
  import NATIVE_TOKENS from './utils/tokens';
16
19
  export { NATIVE_TOKENS };
20
+ export { formattedAmountForDisplay, parsedAmount } from './utils/formatAmount';
@@ -0,0 +1,3 @@
1
+ export interface EntropySource {
2
+ randomBytes(length: number): Uint8Array;
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ /** local imports */
2
+ import { EntropySource } from './entropy';
3
+ export interface EvmGeneratedWallet {
4
+ address: string;
5
+ mnemonic: string;
6
+ privateKey: string;
7
+ path: string;
8
+ }
9
+ export interface EvmDerivedWallet {
10
+ address: string;
11
+ privateKey: string;
12
+ path: string;
13
+ publicKey: string;
14
+ }
15
+ export declare class EvmWalletService {
16
+ private entropy;
17
+ private readonly DEFAULT_DERIVATION_PATH;
18
+ constructor(entropy: EntropySource);
19
+ generateNewWallet(accountIndex?: number, wordCount?: 12 | 15 | 18 | 21 | 24): EvmGeneratedWallet;
20
+ generateMultipleWallets(mnemonic: string, count: number, startIndex?: number): EvmDerivedWallet[];
21
+ deriveWalletFromMnemonic(mnemonic: string, accountIndex?: number, customPath?: string): EvmDerivedWallet;
22
+ deriveFromPrivateKey(privateKey: string): Omit<EvmDerivedWallet, 'path'>;
23
+ signMessage(privateKey: string, message: string): Promise<string>;
24
+ isValidMnemonic(mnemonic: string): boolean;
25
+ private validateMnemonic;
26
+ private getEntropyForWordCount;
27
+ }
@@ -0,0 +1,86 @@
1
+ /** npm imports */
2
+ import { Wallet, HDNodeWallet, Mnemonic } from 'ethers';
3
+ export class EvmWalletService {
4
+ constructor(entropy) {
5
+ this.entropy = entropy;
6
+ this.DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0";
7
+ }
8
+ generateNewWallet(accountIndex = 0, wordCount = 12) {
9
+ const entropy = this.getEntropyForWordCount(wordCount);
10
+ const randomBytesArray = this.entropy.randomBytes(entropy);
11
+ const customMnemonic = Mnemonic.fromEntropy(randomBytesArray);
12
+ const path = `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
13
+ const hdNode = HDNodeWallet.fromMnemonic(customMnemonic, path);
14
+ return {
15
+ address: hdNode.address,
16
+ mnemonic: customMnemonic.phrase,
17
+ privateKey: hdNode.privateKey,
18
+ path,
19
+ };
20
+ }
21
+ generateMultipleWallets(mnemonic, count, startIndex = 0) {
22
+ this.validateMnemonic(mnemonic);
23
+ const wallets = [];
24
+ const mnemonicObject = Mnemonic.fromPhrase(mnemonic);
25
+ for (let i = 0; i < count; i++) {
26
+ const accountIndex = startIndex + i;
27
+ const path = `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
28
+ const hdNode = HDNodeWallet.fromMnemonic(mnemonicObject, path);
29
+ wallets.push({
30
+ address: hdNode.address,
31
+ privateKey: hdNode.privateKey,
32
+ path,
33
+ publicKey: hdNode.publicKey,
34
+ });
35
+ }
36
+ return wallets;
37
+ }
38
+ deriveWalletFromMnemonic(mnemonic, accountIndex = 0, customPath) {
39
+ this.validateMnemonic(mnemonic);
40
+ const path = customPath || `${this.DEFAULT_DERIVATION_PATH}/${accountIndex}`;
41
+ const mnemonicObject = Mnemonic.fromPhrase(mnemonic);
42
+ const hdNode = HDNodeWallet.fromMnemonic(mnemonicObject, path);
43
+ return {
44
+ address: hdNode.address,
45
+ privateKey: hdNode.privateKey,
46
+ path,
47
+ publicKey: hdNode.publicKey,
48
+ };
49
+ }
50
+ deriveFromPrivateKey(privateKey) {
51
+ const wallet = new Wallet(privateKey);
52
+ return {
53
+ address: wallet.address,
54
+ privateKey: wallet.privateKey,
55
+ publicKey: wallet.signingKey.publicKey,
56
+ };
57
+ }
58
+ async signMessage(privateKey, message) {
59
+ const wallet = new Wallet(privateKey);
60
+ return await wallet.signMessage(message);
61
+ }
62
+ isValidMnemonic(mnemonic) {
63
+ try {
64
+ Mnemonic.fromPhrase(mnemonic);
65
+ return true;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
71
+ validateMnemonic(mnemonic) {
72
+ if (!this.isValidMnemonic(mnemonic)) {
73
+ throw new Error('Invalid mnemonic phrase');
74
+ }
75
+ }
76
+ getEntropyForWordCount(wordCount) {
77
+ const entropyMap = {
78
+ 12: 16, // 128 bits
79
+ 15: 20, // 160 bits
80
+ 18: 24, // 192 bits
81
+ 21: 28, // 224 bits
82
+ 24: 32, // 256 bits
83
+ };
84
+ return entropyMap[wordCount];
85
+ }
86
+ }
@@ -0,0 +1,7 @@
1
+ /** npm imports */
2
+ import { Wallet } from 'ethers';
3
+ /** local imports */
4
+ import { TransactionRequest } from '../../types/common';
5
+ export declare const createWallet: (privateKey: string, rpcUrl?: string) => Wallet;
6
+ export declare const signMessage: (privateKey: string, message: string) => Promise<string>;
7
+ export declare const signTransaction: (privateKey: string, tx: TransactionRequest, rpcUrl?: string) => Promise<string>;
@@ -0,0 +1,11 @@
1
+ /** npm imports */
2
+ import { Wallet, JsonRpcProvider } from 'ethers';
3
+ export const createWallet = (privateKey, rpcUrl) => new Wallet(privateKey, rpcUrl ? new JsonRpcProvider(rpcUrl) : undefined);
4
+ export const signMessage = async (privateKey, message) => {
5
+ const wallet = createWallet(privateKey);
6
+ return wallet.signMessage(message);
7
+ };
8
+ export const signTransaction = async (privateKey, tx, rpcUrl) => {
9
+ const wallet = createWallet(privateKey, rpcUrl);
10
+ return wallet.signTransaction(tx);
11
+ };
@@ -33,6 +33,7 @@ export interface UnsignedTransferTxResponse {
33
33
  nonce: number;
34
34
  gasEstimated: string;
35
35
  gasLimit: string;
36
+ gasReserve?: string;
36
37
  bufferPercentage: number;
37
38
  feeData: {
38
39
  maxFeePerGas?: string;
@@ -40,9 +41,17 @@ export interface UnsignedTransferTxResponse {
40
41
  gasPrice?: string;
41
42
  };
42
43
  }
44
+ export interface BuildMaxNativeTransferTxOptions extends Omit<BuildUnsignedTransferTxOptions, 'value' | 'tokenAddress' | 'tokenDecimals'> {
45
+ balance: string;
46
+ tokenAddress?: string;
47
+ }
48
+ export interface BuildMaxNativeTransferTxResponse extends UnsignedTransferTxResponse {
49
+ sendableValue: string;
50
+ }
43
51
  export interface BroadcastTransactionOptions {
44
52
  signedTx: string;
45
53
  rpcUrl: string;
54
+ chainId?: number;
46
55
  waitConfirmations?: number;
47
56
  }
48
57
  export interface TxStatusOptions {
@@ -54,3 +63,12 @@ export interface TxStatusResponse {
54
63
  success: boolean;
55
64
  receipt: TransactionReceipt | null;
56
65
  }
66
+ export interface FormatAmountOptions {
67
+ decimalsToShow?: number;
68
+ useGroupSeparator?: boolean;
69
+ locale?: string;
70
+ minimumFractionDigits?: number;
71
+ minDisplayDecimals?: number;
72
+ maxDisplayDigits?: number;
73
+ }
74
+ export type { TransactionRequest };
@@ -0,0 +1,6 @@
1
+ /** npm imports */
2
+ import { BigNumberish } from 'ethers';
3
+ /** local imports */
4
+ import { FormatAmountOptions } from '../types/common';
5
+ export declare const formattedAmountForDisplay: (amount: BigNumberish, decimals: number, options?: FormatAmountOptions) => string;
6
+ export declare const parsedAmount: (amount: string, decimals: number) => bigint;
@@ -0,0 +1,50 @@
1
+ /** npm imports */
2
+ import { formatUnits, parseUnits } from 'ethers';
3
+ export const formattedAmountForDisplay = (amount, decimals, options = {}) => {
4
+ const { decimalsToShow = 0, useGroupSeparator = true, locale = 'en-US', minimumFractionDigits, minDisplayDecimals = 9, maxDisplayDigits = 16, } = options;
5
+ const formattedAmount = formatUnits(amount, decimals);
6
+ if (formattedAmount.startsWith('-')) {
7
+ throw new Error('Negative balances are not supported');
8
+ }
9
+ const [wholePart = '0', fractionPart = ''] = formattedAmount.split('.');
10
+ if (wholePart.length >= maxDisplayDigits) {
11
+ const mantissaWhole = wholePart[0] ?? '0';
12
+ const mantissaFraction = (wholePart.slice(1) + fractionPart).slice(0, decimalsToShow);
13
+ const exponent = wholePart.length - 1;
14
+ const rawMantissa = mantissaFraction ? `${mantissaWhole}.${mantissaFraction}` : mantissaWhole;
15
+ const trimmedMantissa = rawMantissa.replace(/\.0+$|(?<=\.[0-9]*?)0+$/g, '').replace(/\.$/, '');
16
+ return `${trimmedMantissa}e${exponent}`;
17
+ }
18
+ const firstNonZeroIndex = fractionPart.split('').findIndex((digit) => digit !== '0');
19
+ const hasNonZeroFraction = firstNonZeroIndex !== -1;
20
+ if (hasNonZeroFraction && wholePart === '0' && firstNonZeroIndex >= minDisplayDecimals) {
21
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
22
+ const decimalSeparator = sample.replace(/\d/g, '').slice(-1) ?? '.';
23
+ const minValue = `0${decimalSeparator}${'0'.repeat(Math.max(0, minDisplayDecimals - 1))}1`;
24
+ return `< ${minValue}`;
25
+ }
26
+ if (!hasNonZeroFraction) {
27
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
28
+ const groupSeparator = sample.replace(/\d/g, '')[0] ?? ',';
29
+ const groupedWhole = useGroupSeparator
30
+ ? (wholePart || '0').replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator)
31
+ : wholePart;
32
+ return groupedWhole;
33
+ }
34
+ const maxDecimals = decimalsToShow ?? fractionPart.length;
35
+ let trimmedFraction = fractionPart.slice(0, Math.max(0, maxDecimals));
36
+ const minDecimals = minimumFractionDigits ?? 0;
37
+ if (trimmedFraction.length < minDecimals) {
38
+ trimmedFraction = trimmedFraction.padEnd(minDecimals, '0');
39
+ }
40
+ const sample = new Intl.NumberFormat(locale).format(1000.1);
41
+ const groupSeparator = sample.replace(/\d/g, '')[0] ?? ',';
42
+ const decimalSeparator = sample.replace(/\d/g, '').slice(-1) ?? '.';
43
+ const groupedWhole = useGroupSeparator
44
+ ? (wholePart || '0').replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator)
45
+ : wholePart;
46
+ if (!trimmedFraction)
47
+ return groupedWhole;
48
+ return `${groupedWhole}${decimalSeparator}${trimmedFraction}`;
49
+ };
50
+ export const parsedAmount = (amount, decimals) => parseUnits(amount, decimals);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octaflowlabs/onchain-sdk",
3
- "version": "1.0.0-test9",
3
+ "version": "1.1.0",
4
4
  "description": "onchain methods for web3",
5
5
  "repository": "https://github.com/crisramb665/onchain-sdk.git",
6
6
  "license": "MIT",