@octaflowlabs/onchain-sdk 1.0.0-test10

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 (54) hide show
  1. package/README.md +1 -0
  2. package/dist/ABIs/ERC20_TOKEN_CONTRACT_ABI.d.ts +29 -0
  3. package/dist/ABIs/ERC20_TOKEN_CONTRACT_ABI.js +105 -0
  4. package/dist/blockchain/broadcastTransaction.d.ts +2 -0
  5. package/dist/blockchain/broadcastTransaction.js +27 -0
  6. package/dist/blockchain/buildUnsignedTransferTx.d.ts +2 -0
  7. package/dist/blockchain/buildUnsignedTransferTx.js +95 -0
  8. package/dist/blockchain/estimateGasLimitFromProvider.d.ts +3 -0
  9. package/dist/blockchain/estimateGasLimitFromProvider.js +51 -0
  10. package/dist/blockchain/getProvider.d.ts +3 -0
  11. package/dist/blockchain/getProvider.js +16 -0
  12. package/dist/blockchain/txStatus.d.ts +2 -0
  13. package/dist/blockchain/txStatus.js +17 -0
  14. package/dist/cjs/ABIs/ERC20_TOKEN_CONTRACT_ABI.d.ts +29 -0
  15. package/dist/cjs/ABIs/ERC20_TOKEN_CONTRACT_ABI.js +107 -0
  16. package/dist/cjs/blockchain/broadcastTransaction.d.ts +2 -0
  17. package/dist/cjs/blockchain/broadcastTransaction.js +31 -0
  18. package/dist/cjs/blockchain/buildUnsignedTransferTx.d.ts +2 -0
  19. package/dist/cjs/blockchain/buildUnsignedTransferTx.js +99 -0
  20. package/dist/cjs/blockchain/estimateGasLimitFromProvider.d.ts +3 -0
  21. package/dist/cjs/blockchain/estimateGasLimitFromProvider.js +55 -0
  22. package/dist/cjs/blockchain/getProvider.d.ts +3 -0
  23. package/dist/cjs/blockchain/getProvider.js +20 -0
  24. package/dist/cjs/blockchain/txStatus.d.ts +2 -0
  25. package/dist/cjs/blockchain/txStatus.js +21 -0
  26. package/dist/cjs/constants/constants.d.ts +5 -0
  27. package/dist/cjs/constants/constants.js +8 -0
  28. package/dist/cjs/index.d.ts +18 -0
  29. package/dist/cjs/index.js +30 -0
  30. package/dist/cjs/types/common.d.ts +57 -0
  31. package/dist/cjs/types/common.js +2 -0
  32. package/dist/cjs/utils/getShortenTxHash.d.ts +1 -0
  33. package/dist/cjs/utils/getShortenTxHash.js +9 -0
  34. package/dist/cjs/utils/handleErrorMessages.d.ts +2 -0
  35. package/dist/cjs/utils/handleErrorMessages.js +25 -0
  36. package/dist/cjs/utils/tokens.d.ts +9 -0
  37. package/dist/cjs/utils/tokens.js +9 -0
  38. package/dist/cjs/utils/transformBigInt.d.ts +20 -0
  39. package/dist/cjs/utils/transformBigInt.js +12 -0
  40. package/dist/constants/constants.d.ts +5 -0
  41. package/dist/constants/constants.js +5 -0
  42. package/dist/index.d.ts +18 -0
  43. package/dist/index.js +16 -0
  44. package/dist/types/common.d.ts +57 -0
  45. package/dist/types/common.js +1 -0
  46. package/dist/utils/getShortenTxHash.d.ts +1 -0
  47. package/dist/utils/getShortenTxHash.js +5 -0
  48. package/dist/utils/handleErrorMessages.d.ts +2 -0
  49. package/dist/utils/handleErrorMessages.js +22 -0
  50. package/dist/utils/tokens.d.ts +9 -0
  51. package/dist/utils/tokens.js +7 -0
  52. package/dist/utils/transformBigInt.d.ts +20 -0
  53. package/dist/utils/transformBigInt.js +8 -0
  54. package/package.json +29 -0
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # onchain-sdk
@@ -0,0 +1,29 @@
1
+ declare const _default: ({
2
+ inputs: {
3
+ internalType: string;
4
+ name: string;
5
+ type: string;
6
+ }[];
7
+ name: string;
8
+ outputs: {
9
+ internalType: string;
10
+ name: string;
11
+ type: string;
12
+ }[];
13
+ stateMutability: string;
14
+ type: string;
15
+ constant?: undefined;
16
+ payable?: undefined;
17
+ } | {
18
+ constant: boolean;
19
+ inputs: {
20
+ name: string;
21
+ type: string;
22
+ }[];
23
+ name: string;
24
+ outputs: never[];
25
+ payable: boolean;
26
+ stateMutability: string;
27
+ type: string;
28
+ })[];
29
+ export default _default;
@@ -0,0 +1,105 @@
1
+ export default [
2
+ {
3
+ inputs: [
4
+ {
5
+ internalType: 'address',
6
+ name: 'account',
7
+ type: 'address',
8
+ },
9
+ ],
10
+ name: 'balanceOf',
11
+ outputs: [
12
+ {
13
+ internalType: 'uint256',
14
+ name: '',
15
+ type: 'uint256',
16
+ },
17
+ ],
18
+ stateMutability: 'view',
19
+ type: 'function',
20
+ },
21
+ {
22
+ inputs: [
23
+ {
24
+ internalType: 'address',
25
+ name: 'spender',
26
+ type: 'address',
27
+ },
28
+ {
29
+ internalType: 'uint256',
30
+ name: 'value',
31
+ type: 'uint256',
32
+ },
33
+ ],
34
+ name: 'approve',
35
+ outputs: [
36
+ {
37
+ internalType: 'bool',
38
+ name: '',
39
+ type: 'bool',
40
+ },
41
+ ],
42
+ stateMutability: 'nonpayable',
43
+ type: 'function',
44
+ },
45
+ {
46
+ constant: false,
47
+ inputs: [],
48
+ name: 'deposit',
49
+ outputs: [],
50
+ payable: true,
51
+ stateMutability: 'payable',
52
+ type: 'function',
53
+ },
54
+ {
55
+ constant: false,
56
+ inputs: [
57
+ {
58
+ name: 'wad',
59
+ type: 'uint256',
60
+ },
61
+ ],
62
+ name: 'withdraw',
63
+ outputs: [],
64
+ payable: false,
65
+ stateMutability: 'nonpayable',
66
+ type: 'function',
67
+ },
68
+ {
69
+ inputs: [
70
+ {
71
+ internalType: 'address',
72
+ name: 'owner',
73
+ type: 'address',
74
+ },
75
+ {
76
+ internalType: 'address',
77
+ name: 'spender',
78
+ type: 'address',
79
+ },
80
+ ],
81
+ name: 'allowance',
82
+ outputs: [
83
+ {
84
+ internalType: 'uint256',
85
+ name: '',
86
+ type: 'uint256',
87
+ },
88
+ ],
89
+ stateMutability: 'view',
90
+ type: 'function',
91
+ },
92
+ {
93
+ inputs: [],
94
+ name: 'decimals',
95
+ outputs: [
96
+ {
97
+ internalType: 'uint8',
98
+ name: '',
99
+ type: 'uint8',
100
+ },
101
+ ],
102
+ stateMutability: 'view',
103
+ type: 'function',
104
+ },
105
+ ];
@@ -0,0 +1,2 @@
1
+ import { BroadcastTransactionOptions } from '../types/common';
2
+ export declare const broadcastTransaction: ({ signedTx, rpcUrl, chainId, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
@@ -0,0 +1,27 @@
1
+ /** npm imports */
2
+ import { Transaction } from 'ethers';
3
+ /** local imports */
4
+ import { getProvider } from './getProvider';
5
+ export const broadcastTransaction = async ({ signedTx, rpcUrl, chainId, waitConfirmations = 0, }) => {
6
+ const provider = getProvider(rpcUrl, chainId);
7
+ if (!provider)
8
+ throw new Error('Could not create provider with given rpcUrl');
9
+ try {
10
+ Transaction.from(signedTx);
11
+ }
12
+ catch (error) {
13
+ console.error('Invalid signed transaction format:', error);
14
+ throw new Error('Invalid signed transaction format' + (error?.message || error || ''));
15
+ }
16
+ try {
17
+ const txResponse = await provider.broadcastTransaction(signedTx);
18
+ const txHash = txResponse.hash;
19
+ if (waitConfirmations && waitConfirmations > 0)
20
+ await txResponse.wait(waitConfirmations);
21
+ return txHash;
22
+ }
23
+ catch (error) {
24
+ console.error('Error computing transaction hash:', error);
25
+ throw new Error(error?.message || error || 'Failed to broadcast transaction');
26
+ }
27
+ };
@@ -0,0 +1,2 @@
1
+ import { BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
2
+ export declare const buildUnsignedTransferTx: (options: BuildUnsignedTransferTxOptions) => Promise<UnsignedTransferTxResponse>;
@@ -0,0 +1,95 @@
1
+ /** npm imports */
2
+ import { Interface, parseUnits } from 'ethers';
3
+ /** local imports */
4
+ import { getProvider } from './getProvider';
5
+ import { estimateGasLimitFromProvider } from './estimateGasLimitFromProvider';
6
+ export const buildUnsignedTransferTx = async (options) => {
7
+ const provider = getProvider(options.rpcUrl, options.chainId);
8
+ if (!provider)
9
+ throw new Error('Could not create provider with given rpcUrl and chainId');
10
+ try {
11
+ let unsignedTx = { to: options.tokenAddress };
12
+ const isNativeToken = !options.tokenAddress ||
13
+ options.tokenAddress?.toLowerCase() === '0x0000000000000000000000000000000000000000' ||
14
+ options.tokenAddress?.toLowerCase() === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
15
+ if (!isNativeToken) {
16
+ if (!options.tokenAddress)
17
+ throw new Error('Token address is required for token transfer');
18
+ const code = await provider.getCode(options.tokenAddress);
19
+ if (code === '0x' || code === '0x0')
20
+ throw new Error('Invalid token address');
21
+ const erc20Interface = new Interface(['function transfer(address to, uint256 amount)']);
22
+ const decimals = options.tokenDecimals ?? 18;
23
+ if (!options.value)
24
+ throw new Error('Value is required for token transfer');
25
+ const amountParsed = parseUnits(options.value, decimals);
26
+ unsignedTx = {
27
+ ...unsignedTx,
28
+ data: erc20Interface.encodeFunctionData('transfer', [options.toAddress, amountParsed]),
29
+ value: 0n,
30
+ };
31
+ }
32
+ else {
33
+ if (!options.value)
34
+ throw new Error('Native transfer requires value');
35
+ unsignedTx = {
36
+ to: options.toAddress,
37
+ data: '0x',
38
+ value: parseUnits(options.value, 18),
39
+ };
40
+ }
41
+ if (options.chainId)
42
+ unsignedTx.chainId = options.chainId;
43
+ const nonce = await provider.getTransactionCount(options.fromAddress, 'pending');
44
+ const estimateGas = await estimateGasLimitFromProvider({
45
+ provider: provider,
46
+ unsignedTx,
47
+ walletAddress: options.fromAddress,
48
+ defaultGasLimit: options.defaultGasLimit,
49
+ });
50
+ const unsignedTxToReturn = {
51
+ from: options.fromAddress,
52
+ to: unsignedTx.to,
53
+ data: unsignedTx.data,
54
+ value: unsignedTx.value?.toString(),
55
+ gasLimit: estimateGas.gasLimit.toString(),
56
+ chainId: unsignedTx.chainId,
57
+ nonce,
58
+ maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
59
+ maxPriorityFeePerGas: estimateGas.feeData.maxPriorityFeePerGas?.toString(),
60
+ };
61
+ if (estimateGas.feeData.gasPrice)
62
+ unsignedTxToReturn.gasPrice = estimateGas.feeData.gasPrice.toString();
63
+ try {
64
+ await provider.call({
65
+ from: options.fromAddress,
66
+ to: unsignedTx.to,
67
+ data: unsignedTx.data,
68
+ value: unsignedTx.value,
69
+ gasLimit: estimateGas.gasLimit,
70
+ });
71
+ }
72
+ catch (error) {
73
+ throw new Error('Transaction would revert, provider call unsuccessful: ' + error.message || error);
74
+ }
75
+ console.log('Built unsigned transfer transaction:', unsignedTxToReturn);
76
+ return {
77
+ unsignedTx: unsignedTxToReturn,
78
+ nonce,
79
+ gasEstimated: estimateGas.gasEstimated.toString(),
80
+ gasLimit: estimateGas.gasLimit.toString(),
81
+ bufferPercentage: estimateGas.bufferPercentage,
82
+ feeData: {
83
+ maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
84
+ maxPriorityFeePerGas: estimateGas.feeData.maxPriorityFeePerGas?.toString(),
85
+ gasPrice: estimateGas.feeData.gasPrice?.toString(),
86
+ },
87
+ // suggestedGasFees: estimateGas.suggestedGasFees,
88
+ // humanReadableFees: humanReadableGasEstimation,
89
+ };
90
+ }
91
+ catch (error) {
92
+ console.error('Error building unsigned transfer transaction:', error);
93
+ throw error;
94
+ }
95
+ };
@@ -0,0 +1,3 @@
1
+ /** local imports */
2
+ import { EstimateGasLimitFromProviderProps, GasEstimateResult } from '../types/common';
3
+ export declare const estimateGasLimitFromProvider: ({ provider, unsignedTx, walletAddress, defaultGasLimit, }: EstimateGasLimitFromProviderProps) => Promise<GasEstimateResult>;
@@ -0,0 +1,51 @@
1
+ export const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddress, defaultGasLimit, }) => {
2
+ try {
3
+ const feeData = await provider.getFeeData();
4
+ const txForEstimation = { ...unsignedTx, from: walletAddress };
5
+ if (feeData.maxFeePerGas !== undefined)
6
+ txForEstimation.maxFeePerGas = feeData.maxFeePerGas;
7
+ if (feeData.maxPriorityFeePerGas !== undefined)
8
+ txForEstimation.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
9
+ if (feeData.gasPrice !== undefined && txForEstimation.maxFeePerGas === undefined)
10
+ txForEstimation.gasPrice = feeData.gasPrice;
11
+ const gasEstimated = await provider.estimateGas(txForEstimation);
12
+ let congestionFactor = 1.5;
13
+ if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) {
14
+ try {
15
+ const maxFee = Number(feeData.maxFeePerGas);
16
+ const maxPriorityFee = Math.max(Number(feeData.maxPriorityFeePerGas), 1);
17
+ const ratio = maxFee / maxPriorityFee;
18
+ if (isFinite(ratio) && ratio > 0)
19
+ congestionFactor = ratio;
20
+ }
21
+ catch {
22
+ congestionFactor = 1.5;
23
+ }
24
+ }
25
+ const bufferPercentage = Math.min(Math.max(Math.round(congestionFactor * 5), 5), 30); // 5% to 30% buffer
26
+ const newGasLimit = gasEstimated + (gasEstimated * BigInt(bufferPercentage)) / BigInt(100);
27
+ return {
28
+ gasEstimated,
29
+ gasLimit: newGasLimit,
30
+ bufferPercentage,
31
+ fallbackUsed: false,
32
+ feeData: {
33
+ maxFeePerGas: feeData.maxFeePerGas ?? undefined,
34
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined,
35
+ gasPrice: feeData.gasPrice ?? undefined,
36
+ },
37
+ // suggestedGasFees: suggested,
38
+ };
39
+ }
40
+ catch (error) {
41
+ console.error('Unable to estimate gas limit: ', error);
42
+ console.log(`Setting default gas limit to: ${defaultGasLimit}`);
43
+ return {
44
+ gasEstimated: defaultGasLimit,
45
+ gasLimit: defaultGasLimit,
46
+ bufferPercentage: 0,
47
+ fallbackUsed: true,
48
+ feeData: {},
49
+ };
50
+ }
51
+ };
@@ -0,0 +1,3 @@
1
+ /** npm imports */
2
+ import { JsonRpcProvider } from 'ethers';
3
+ export declare const getProvider: (rpcUrl: string, chainId?: number) => JsonRpcProvider | undefined;
@@ -0,0 +1,16 @@
1
+ /** npm imports */
2
+ import { JsonRpcProvider, Network } from 'ethers';
3
+ export const getProvider = (rpcUrl, chainId) => {
4
+ try {
5
+ if (chainId) {
6
+ const network = Network.from(chainId);
7
+ return new JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
8
+ }
9
+ else {
10
+ return new JsonRpcProvider(rpcUrl);
11
+ }
12
+ }
13
+ catch (error) {
14
+ console.warn('Could not create provider with chainId, falling back to rpcUrl only:', error);
15
+ }
16
+ };
@@ -0,0 +1,2 @@
1
+ import { TxStatusOptions, TxStatusResponse } from '../types/common';
2
+ export declare const txStatus: ({ rpcUrl, txHash, chainId, }: TxStatusOptions) => Promise<TxStatusResponse>;
@@ -0,0 +1,17 @@
1
+ /** local imports */
2
+ import { getProvider } from './getProvider';
3
+ export const txStatus = async ({ rpcUrl, txHash, chainId, }) => {
4
+ const provider = getProvider(rpcUrl, chainId);
5
+ if (!provider)
6
+ throw new Error('Could not create provider with given rpcUrl and chainId');
7
+ try {
8
+ const receipt = await provider.getTransactionReceipt(txHash);
9
+ if (!receipt)
10
+ return { success: false, receipt: null };
11
+ return { success: receipt.status === 1, receipt };
12
+ }
13
+ catch (error) {
14
+ console.log('Error checking transaction status:', error);
15
+ return { success: false, receipt: null };
16
+ }
17
+ };
@@ -0,0 +1,29 @@
1
+ declare const _default: ({
2
+ inputs: {
3
+ internalType: string;
4
+ name: string;
5
+ type: string;
6
+ }[];
7
+ name: string;
8
+ outputs: {
9
+ internalType: string;
10
+ name: string;
11
+ type: string;
12
+ }[];
13
+ stateMutability: string;
14
+ type: string;
15
+ constant?: undefined;
16
+ payable?: undefined;
17
+ } | {
18
+ constant: boolean;
19
+ inputs: {
20
+ name: string;
21
+ type: string;
22
+ }[];
23
+ name: string;
24
+ outputs: never[];
25
+ payable: boolean;
26
+ stateMutability: string;
27
+ type: string;
28
+ })[];
29
+ export default _default;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = [
4
+ {
5
+ inputs: [
6
+ {
7
+ internalType: 'address',
8
+ name: 'account',
9
+ type: 'address',
10
+ },
11
+ ],
12
+ name: 'balanceOf',
13
+ outputs: [
14
+ {
15
+ internalType: 'uint256',
16
+ name: '',
17
+ type: 'uint256',
18
+ },
19
+ ],
20
+ stateMutability: 'view',
21
+ type: 'function',
22
+ },
23
+ {
24
+ inputs: [
25
+ {
26
+ internalType: 'address',
27
+ name: 'spender',
28
+ type: 'address',
29
+ },
30
+ {
31
+ internalType: 'uint256',
32
+ name: 'value',
33
+ type: 'uint256',
34
+ },
35
+ ],
36
+ name: 'approve',
37
+ outputs: [
38
+ {
39
+ internalType: 'bool',
40
+ name: '',
41
+ type: 'bool',
42
+ },
43
+ ],
44
+ stateMutability: 'nonpayable',
45
+ type: 'function',
46
+ },
47
+ {
48
+ constant: false,
49
+ inputs: [],
50
+ name: 'deposit',
51
+ outputs: [],
52
+ payable: true,
53
+ stateMutability: 'payable',
54
+ type: 'function',
55
+ },
56
+ {
57
+ constant: false,
58
+ inputs: [
59
+ {
60
+ name: 'wad',
61
+ type: 'uint256',
62
+ },
63
+ ],
64
+ name: 'withdraw',
65
+ outputs: [],
66
+ payable: false,
67
+ stateMutability: 'nonpayable',
68
+ type: 'function',
69
+ },
70
+ {
71
+ inputs: [
72
+ {
73
+ internalType: 'address',
74
+ name: 'owner',
75
+ type: 'address',
76
+ },
77
+ {
78
+ internalType: 'address',
79
+ name: 'spender',
80
+ type: 'address',
81
+ },
82
+ ],
83
+ name: 'allowance',
84
+ outputs: [
85
+ {
86
+ internalType: 'uint256',
87
+ name: '',
88
+ type: 'uint256',
89
+ },
90
+ ],
91
+ stateMutability: 'view',
92
+ type: 'function',
93
+ },
94
+ {
95
+ inputs: [],
96
+ name: 'decimals',
97
+ outputs: [
98
+ {
99
+ internalType: 'uint8',
100
+ name: '',
101
+ type: 'uint8',
102
+ },
103
+ ],
104
+ stateMutability: 'view',
105
+ type: 'function',
106
+ },
107
+ ];
@@ -0,0 +1,2 @@
1
+ import { BroadcastTransactionOptions } from '../types/common';
2
+ export declare const broadcastTransaction: ({ signedTx, rpcUrl, chainId, waitConfirmations, }: BroadcastTransactionOptions) => Promise<string>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.broadcastTransaction = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ /** local imports */
7
+ const getProvider_1 = require("./getProvider");
8
+ const broadcastTransaction = async ({ signedTx, rpcUrl, chainId, waitConfirmations = 0, }) => {
9
+ const provider = (0, getProvider_1.getProvider)(rpcUrl, chainId);
10
+ if (!provider)
11
+ throw new Error('Could not create provider with given rpcUrl');
12
+ try {
13
+ ethers_1.Transaction.from(signedTx);
14
+ }
15
+ catch (error) {
16
+ console.error('Invalid signed transaction format:', error);
17
+ throw new Error('Invalid signed transaction format' + (error?.message || error || ''));
18
+ }
19
+ try {
20
+ const txResponse = await provider.broadcastTransaction(signedTx);
21
+ const txHash = txResponse.hash;
22
+ if (waitConfirmations && waitConfirmations > 0)
23
+ await txResponse.wait(waitConfirmations);
24
+ return txHash;
25
+ }
26
+ catch (error) {
27
+ console.error('Error computing transaction hash:', error);
28
+ throw new Error(error?.message || error || 'Failed to broadcast transaction');
29
+ }
30
+ };
31
+ exports.broadcastTransaction = broadcastTransaction;
@@ -0,0 +1,2 @@
1
+ import { BuildUnsignedTransferTxOptions, UnsignedTransferTxResponse } from '../types/common';
2
+ export declare const buildUnsignedTransferTx: (options: BuildUnsignedTransferTxOptions) => Promise<UnsignedTransferTxResponse>;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildUnsignedTransferTx = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ /** local imports */
7
+ const getProvider_1 = require("./getProvider");
8
+ const estimateGasLimitFromProvider_1 = require("./estimateGasLimitFromProvider");
9
+ const buildUnsignedTransferTx = async (options) => {
10
+ const provider = (0, getProvider_1.getProvider)(options.rpcUrl, options.chainId);
11
+ if (!provider)
12
+ throw new Error('Could not create provider with given rpcUrl and chainId');
13
+ try {
14
+ let unsignedTx = { to: options.tokenAddress };
15
+ const isNativeToken = !options.tokenAddress ||
16
+ options.tokenAddress?.toLowerCase() === '0x0000000000000000000000000000000000000000' ||
17
+ options.tokenAddress?.toLowerCase() === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
18
+ if (!isNativeToken) {
19
+ if (!options.tokenAddress)
20
+ throw new Error('Token address is required for token transfer');
21
+ const code = await provider.getCode(options.tokenAddress);
22
+ if (code === '0x' || code === '0x0')
23
+ throw new Error('Invalid token address');
24
+ const erc20Interface = new ethers_1.Interface(['function transfer(address to, uint256 amount)']);
25
+ const decimals = options.tokenDecimals ?? 18;
26
+ if (!options.value)
27
+ throw new Error('Value is required for token transfer');
28
+ const amountParsed = (0, ethers_1.parseUnits)(options.value, decimals);
29
+ unsignedTx = {
30
+ ...unsignedTx,
31
+ data: erc20Interface.encodeFunctionData('transfer', [options.toAddress, amountParsed]),
32
+ value: 0n,
33
+ };
34
+ }
35
+ else {
36
+ if (!options.value)
37
+ throw new Error('Native transfer requires value');
38
+ unsignedTx = {
39
+ to: options.toAddress,
40
+ data: '0x',
41
+ value: (0, ethers_1.parseUnits)(options.value, 18),
42
+ };
43
+ }
44
+ if (options.chainId)
45
+ unsignedTx.chainId = options.chainId;
46
+ const nonce = await provider.getTransactionCount(options.fromAddress, 'pending');
47
+ const estimateGas = await (0, estimateGasLimitFromProvider_1.estimateGasLimitFromProvider)({
48
+ provider: provider,
49
+ unsignedTx,
50
+ walletAddress: options.fromAddress,
51
+ defaultGasLimit: options.defaultGasLimit,
52
+ });
53
+ const unsignedTxToReturn = {
54
+ from: options.fromAddress,
55
+ to: unsignedTx.to,
56
+ data: unsignedTx.data,
57
+ value: unsignedTx.value?.toString(),
58
+ gasLimit: estimateGas.gasLimit.toString(),
59
+ chainId: unsignedTx.chainId,
60
+ nonce,
61
+ maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
62
+ maxPriorityFeePerGas: estimateGas.feeData.maxPriorityFeePerGas?.toString(),
63
+ };
64
+ if (estimateGas.feeData.gasPrice)
65
+ unsignedTxToReturn.gasPrice = estimateGas.feeData.gasPrice.toString();
66
+ try {
67
+ await provider.call({
68
+ from: options.fromAddress,
69
+ to: unsignedTx.to,
70
+ data: unsignedTx.data,
71
+ value: unsignedTx.value,
72
+ gasLimit: estimateGas.gasLimit,
73
+ });
74
+ }
75
+ catch (error) {
76
+ throw new Error('Transaction would revert, provider call unsuccessful: ' + error.message || error);
77
+ }
78
+ console.log('Built unsigned transfer transaction:', unsignedTxToReturn);
79
+ return {
80
+ unsignedTx: unsignedTxToReturn,
81
+ nonce,
82
+ gasEstimated: estimateGas.gasEstimated.toString(),
83
+ gasLimit: estimateGas.gasLimit.toString(),
84
+ bufferPercentage: estimateGas.bufferPercentage,
85
+ feeData: {
86
+ maxFeePerGas: estimateGas.feeData.maxFeePerGas?.toString(),
87
+ maxPriorityFeePerGas: estimateGas.feeData.maxPriorityFeePerGas?.toString(),
88
+ gasPrice: estimateGas.feeData.gasPrice?.toString(),
89
+ },
90
+ // suggestedGasFees: estimateGas.suggestedGasFees,
91
+ // humanReadableFees: humanReadableGasEstimation,
92
+ };
93
+ }
94
+ catch (error) {
95
+ console.error('Error building unsigned transfer transaction:', error);
96
+ throw error;
97
+ }
98
+ };
99
+ exports.buildUnsignedTransferTx = buildUnsignedTransferTx;
@@ -0,0 +1,3 @@
1
+ /** local imports */
2
+ import { EstimateGasLimitFromProviderProps, GasEstimateResult } from '../types/common';
3
+ export declare const estimateGasLimitFromProvider: ({ provider, unsignedTx, walletAddress, defaultGasLimit, }: EstimateGasLimitFromProviderProps) => Promise<GasEstimateResult>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.estimateGasLimitFromProvider = void 0;
4
+ const estimateGasLimitFromProvider = async ({ provider, unsignedTx, walletAddress, defaultGasLimit, }) => {
5
+ try {
6
+ const feeData = await provider.getFeeData();
7
+ const txForEstimation = { ...unsignedTx, from: walletAddress };
8
+ if (feeData.maxFeePerGas !== undefined)
9
+ txForEstimation.maxFeePerGas = feeData.maxFeePerGas;
10
+ if (feeData.maxPriorityFeePerGas !== undefined)
11
+ txForEstimation.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
12
+ if (feeData.gasPrice !== undefined && txForEstimation.maxFeePerGas === undefined)
13
+ txForEstimation.gasPrice = feeData.gasPrice;
14
+ const gasEstimated = await provider.estimateGas(txForEstimation);
15
+ let congestionFactor = 1.5;
16
+ if (feeData.maxFeePerGas && feeData.maxPriorityFeePerGas) {
17
+ try {
18
+ const maxFee = Number(feeData.maxFeePerGas);
19
+ const maxPriorityFee = Math.max(Number(feeData.maxPriorityFeePerGas), 1);
20
+ const ratio = maxFee / maxPriorityFee;
21
+ if (isFinite(ratio) && ratio > 0)
22
+ congestionFactor = ratio;
23
+ }
24
+ catch {
25
+ congestionFactor = 1.5;
26
+ }
27
+ }
28
+ const bufferPercentage = Math.min(Math.max(Math.round(congestionFactor * 5), 5), 30); // 5% to 30% buffer
29
+ const newGasLimit = gasEstimated + (gasEstimated * BigInt(bufferPercentage)) / BigInt(100);
30
+ return {
31
+ gasEstimated,
32
+ gasLimit: newGasLimit,
33
+ bufferPercentage,
34
+ fallbackUsed: false,
35
+ feeData: {
36
+ maxFeePerGas: feeData.maxFeePerGas ?? undefined,
37
+ maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ?? undefined,
38
+ gasPrice: feeData.gasPrice ?? undefined,
39
+ },
40
+ // suggestedGasFees: suggested,
41
+ };
42
+ }
43
+ catch (error) {
44
+ console.error('Unable to estimate gas limit: ', error);
45
+ console.log(`Setting default gas limit to: ${defaultGasLimit}`);
46
+ return {
47
+ gasEstimated: defaultGasLimit,
48
+ gasLimit: defaultGasLimit,
49
+ bufferPercentage: 0,
50
+ fallbackUsed: true,
51
+ feeData: {},
52
+ };
53
+ }
54
+ };
55
+ exports.estimateGasLimitFromProvider = estimateGasLimitFromProvider;
@@ -0,0 +1,3 @@
1
+ /** npm imports */
2
+ import { JsonRpcProvider } from 'ethers';
3
+ export declare const getProvider: (rpcUrl: string, chainId?: number) => JsonRpcProvider | undefined;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getProvider = void 0;
4
+ /** npm imports */
5
+ const ethers_1 = require("ethers");
6
+ const getProvider = (rpcUrl, chainId) => {
7
+ try {
8
+ if (chainId) {
9
+ const network = ethers_1.Network.from(chainId);
10
+ return new ethers_1.JsonRpcProvider(rpcUrl, network, { staticNetwork: network });
11
+ }
12
+ else {
13
+ return new ethers_1.JsonRpcProvider(rpcUrl);
14
+ }
15
+ }
16
+ catch (error) {
17
+ console.warn('Could not create provider with chainId, falling back to rpcUrl only:', error);
18
+ }
19
+ };
20
+ exports.getProvider = getProvider;
@@ -0,0 +1,2 @@
1
+ import { TxStatusOptions, TxStatusResponse } from '../types/common';
2
+ export declare const txStatus: ({ rpcUrl, txHash, chainId, }: TxStatusOptions) => Promise<TxStatusResponse>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.txStatus = void 0;
4
+ /** local imports */
5
+ const getProvider_1 = require("./getProvider");
6
+ const txStatus = async ({ rpcUrl, txHash, chainId, }) => {
7
+ const provider = (0, getProvider_1.getProvider)(rpcUrl, chainId);
8
+ if (!provider)
9
+ throw new Error('Could not create provider with given rpcUrl and chainId');
10
+ try {
11
+ const receipt = await provider.getTransactionReceipt(txHash);
12
+ if (!receipt)
13
+ return { success: false, receipt: null };
14
+ return { success: receipt.status === 1, receipt };
15
+ }
16
+ catch (error) {
17
+ console.log('Error checking transaction status:', error);
18
+ return { success: false, receipt: null };
19
+ }
20
+ };
21
+ exports.txStatus = txStatus;
@@ -0,0 +1,5 @@
1
+ export declare const GAS_LIMIT_PER_TX_TYPE: {
2
+ DEFAULT_TRANSFER_NATIVE: bigint;
3
+ DEFAULT_TRANSFER_ERC20: bigint;
4
+ DEFAULT_APPROVAL: bigint;
5
+ };
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GAS_LIMIT_PER_TX_TYPE = void 0;
4
+ exports.GAS_LIMIT_PER_TX_TYPE = {
5
+ DEFAULT_TRANSFER_NATIVE: 21000n,
6
+ DEFAULT_TRANSFER_ERC20: 65000n,
7
+ DEFAULT_APPROVAL: 100000n,
8
+ };
@@ -0,0 +1,18 @@
1
+ /** ABIs exports */
2
+ import ERC20_TOKEN_CONTRACT_ABI from './ABIs/ERC20_TOKEN_CONTRACT_ABI';
3
+ export { ERC20_TOKEN_CONTRACT_ABI };
4
+ /** constants exports */
5
+ export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
+ /** basic blockchain exports */
7
+ export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
8
+ export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
+ export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
+ export { getProvider } from './blockchain/getProvider';
11
+ export { txStatus } from './blockchain/txStatus';
12
+ /** utils exports */
13
+ export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
+ export { transformBigInt } from './utils/transformBigInt';
15
+ import NATIVE_TOKENS from './utils/tokens';
16
+ export { NATIVE_TOKENS };
17
+ /** types exports */
18
+ export { BroadcastTransactionOptions, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, } from './types/common';
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
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;
7
+ /** ABIs exports */
8
+ const ERC20_TOKEN_CONTRACT_ABI_1 = __importDefault(require("./ABIs/ERC20_TOKEN_CONTRACT_ABI"));
9
+ exports.ERC20_TOKEN_CONTRACT_ABI = ERC20_TOKEN_CONTRACT_ABI_1.default;
10
+ /** constants exports */
11
+ var constants_1 = require("./constants/constants");
12
+ Object.defineProperty(exports, "GAS_LIMIT_PER_TX_TYPE", { enumerable: true, get: function () { return constants_1.GAS_LIMIT_PER_TX_TYPE; } });
13
+ /** basic blockchain exports */
14
+ var buildUnsignedTransferTx_1 = require("./blockchain/buildUnsignedTransferTx");
15
+ Object.defineProperty(exports, "buildUnsignedTransferTx", { enumerable: true, get: function () { return buildUnsignedTransferTx_1.buildUnsignedTransferTx; } });
16
+ var broadcastTransaction_1 = require("./blockchain/broadcastTransaction");
17
+ Object.defineProperty(exports, "broadcastTransaction", { enumerable: true, get: function () { return broadcastTransaction_1.broadcastTransaction; } });
18
+ var estimateGasLimitFromProvider_1 = require("./blockchain/estimateGasLimitFromProvider");
19
+ Object.defineProperty(exports, "estimateGasLimitFromProvider", { enumerable: true, get: function () { return estimateGasLimitFromProvider_1.estimateGasLimitFromProvider; } });
20
+ var getProvider_1 = require("./blockchain/getProvider");
21
+ Object.defineProperty(exports, "getProvider", { enumerable: true, get: function () { return getProvider_1.getProvider; } });
22
+ var txStatus_1 = require("./blockchain/txStatus");
23
+ Object.defineProperty(exports, "txStatus", { enumerable: true, get: function () { return txStatus_1.txStatus; } });
24
+ /** utils exports */
25
+ var getShortenTxHash_1 = require("./utils/getShortenTxHash");
26
+ Object.defineProperty(exports, "getShortenTransactionHash", { enumerable: true, get: function () { return getShortenTxHash_1.getShortenTransactionHash; } });
27
+ var transformBigInt_1 = require("./utils/transformBigInt");
28
+ Object.defineProperty(exports, "transformBigInt", { enumerable: true, get: function () { return transformBigInt_1.transformBigInt; } });
29
+ const tokens_1 = __importDefault(require("./utils/tokens"));
30
+ exports.NATIVE_TOKENS = tokens_1.default;
@@ -0,0 +1,57 @@
1
+ /** npm imports */
2
+ import { JsonRpcApiProvider, JsonRpcProvider, TransactionReceipt, TransactionRequest } from 'ethers';
3
+ export interface EstimateGasLimitFromProviderProps {
4
+ provider: JsonRpcApiProvider | JsonRpcProvider;
5
+ unsignedTx: TransactionRequest;
6
+ walletAddress: string;
7
+ defaultGasLimit: bigint;
8
+ }
9
+ export interface GasEstimateResult {
10
+ gasEstimated: bigint;
11
+ gasLimit: bigint;
12
+ bufferPercentage: number;
13
+ fallbackUsed: boolean;
14
+ feeData: {
15
+ maxFeePerGas?: bigint;
16
+ maxPriorityFeePerGas?: bigint;
17
+ gasPrice?: bigint;
18
+ };
19
+ }
20
+ export interface BuildUnsignedTransferTxOptions {
21
+ fromAddress: string;
22
+ toAddress: string;
23
+ value?: string;
24
+ data?: string;
25
+ tokenAddress?: string;
26
+ tokenDecimals?: number;
27
+ rpcUrl: string;
28
+ chainId?: number;
29
+ defaultGasLimit: bigint;
30
+ }
31
+ export interface UnsignedTransferTxResponse {
32
+ unsignedTx: TransactionRequest;
33
+ nonce: number;
34
+ gasEstimated: string;
35
+ gasLimit: string;
36
+ bufferPercentage: number;
37
+ feeData: {
38
+ maxFeePerGas?: string;
39
+ maxPriorityFeePerGas?: string;
40
+ gasPrice?: string;
41
+ };
42
+ }
43
+ export interface BroadcastTransactionOptions {
44
+ signedTx: string;
45
+ rpcUrl: string;
46
+ chainId?: number;
47
+ waitConfirmations?: number;
48
+ }
49
+ export interface TxStatusOptions {
50
+ rpcUrl: string;
51
+ txHash: string;
52
+ chainId?: number;
53
+ }
54
+ export interface TxStatusResponse {
55
+ success: boolean;
56
+ receipt: TransactionReceipt | null;
57
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export declare const getShortenTransactionHash: (txHash: string) => string;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getShortenTransactionHash = void 0;
4
+ const getShortenTransactionHash = (txHash) => {
5
+ const firstCharacters = txHash.substring(0, 6);
6
+ const lastCharacters = txHash.slice(-4);
7
+ return `${firstCharacters}...${lastCharacters}`;
8
+ };
9
+ exports.getShortenTransactionHash = getShortenTransactionHash;
@@ -0,0 +1,2 @@
1
+ export declare const errorMessagesForBroadcast: Record<string, string>;
2
+ export declare const errorMessagesForGasLimitEstimation: Record<string, string>;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorMessagesForGasLimitEstimation = exports.errorMessagesForBroadcast = void 0;
4
+ exports.errorMessagesForBroadcast = {
5
+ INSUFFICIENT_FUNDS: 'Insufficient funds for gas.',
6
+ NONCE_EXPIRED: 'Nonce expired.',
7
+ REPLACEMENT_UNDERPRICED: 'Replacement transaction underpriced.',
8
+ INVALID_SIGNATURE: 'Invalid transaction signature.',
9
+ GAS_PRICE_TOO_LOW: 'Gas price too low.',
10
+ UNDERPRICED: 'Gas price too low.',
11
+ OUT_OF_GAS: 'Transaction ran out of gas.',
12
+ UNPREDICTABLE_GAS_LIMIT: 'Unpredictable gas limit. Transaction might fail.',
13
+ INVALID_ARGUMENT: 'Invalid input arguments provided.',
14
+ UNKNOWN_ERROR: 'Unknown error.',
15
+ };
16
+ exports.errorMessagesForGasLimitEstimation = {
17
+ INSUFFICIENT_FUNDS: 'Error: Insufficient funds to cover transaction fees.',
18
+ CALL_EXCEPTION: 'Error: The transaction would revert (CALL_EXCEPTION).',
19
+ OUT_OF_GAS: 'Error: Transaction would run out of gas.',
20
+ UNPREDICTABLE_GAS_LIMIT: 'Error: Unable to estimate gas. The transaction may fail.',
21
+ INVALID_ARGUMENT: 'Error: Invalid input arguments provided for gas estimation.',
22
+ GAS_LIMIT_REACHED: 'Error: Gas estimation exceeds block gas limit.',
23
+ UNKNOWN_ERROR: 'Unknown error.',
24
+ };
25
+ //TODO: Make methofds to parse errors and return user friendly messages based on the above records
@@ -0,0 +1,9 @@
1
+ export type NativeTokenType = {
2
+ [chainId: number]: {
3
+ symbol: string;
4
+ decimals: number;
5
+ name: string;
6
+ };
7
+ };
8
+ declare const NATIVE_TOKENS: NativeTokenType;
9
+ export default NATIVE_TOKENS;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const NATIVE_TOKENS = {
4
+ 1: { symbol: 'ETH', decimals: 18, name: 'Ethereum' },
5
+ 11155111: { symbol: 'ETH', decimals: 18, name: 'Ethereum' },
6
+ 56: { symbol: 'BNB', decimals: 18, name: 'BNB Chain' },
7
+ 137: { symbol: 'POL', decimals: 18, name: 'Polygon' },
8
+ };
9
+ exports.default = NATIVE_TOKENS;
@@ -0,0 +1,20 @@
1
+ /** npm imports */
2
+ import { ContractTransaction } from 'ethers';
3
+ export declare const transformBigInt: (obj: ContractTransaction) => {
4
+ to: string;
5
+ data: string;
6
+ from?: string;
7
+ type?: number;
8
+ nonce?: number;
9
+ gasLimit?: bigint;
10
+ gasPrice?: bigint;
11
+ maxPriorityFeePerGas?: bigint;
12
+ maxFeePerGas?: bigint;
13
+ value?: bigint;
14
+ chainId?: bigint;
15
+ accessList?: import("ethers").AccessList;
16
+ authorizationList?: Array<import("ethers").Authorization>;
17
+ customData?: any;
18
+ blockTag?: import("ethers").BlockTag;
19
+ enableCcipRead?: boolean;
20
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformBigInt = void 0;
4
+ const transformBigInt = (obj) => {
5
+ const newObj = { ...obj };
6
+ for (let key in obj) {
7
+ if (typeof obj[key] === 'bigint')
8
+ newObj[key] = String(obj[key]);
9
+ }
10
+ return newObj;
11
+ };
12
+ exports.transformBigInt = transformBigInt;
@@ -0,0 +1,5 @@
1
+ export declare const GAS_LIMIT_PER_TX_TYPE: {
2
+ DEFAULT_TRANSFER_NATIVE: bigint;
3
+ DEFAULT_TRANSFER_ERC20: bigint;
4
+ DEFAULT_APPROVAL: bigint;
5
+ };
@@ -0,0 +1,5 @@
1
+ export const GAS_LIMIT_PER_TX_TYPE = {
2
+ DEFAULT_TRANSFER_NATIVE: 21000n,
3
+ DEFAULT_TRANSFER_ERC20: 65000n,
4
+ DEFAULT_APPROVAL: 100000n,
5
+ };
@@ -0,0 +1,18 @@
1
+ /** ABIs exports */
2
+ import ERC20_TOKEN_CONTRACT_ABI from './ABIs/ERC20_TOKEN_CONTRACT_ABI';
3
+ export { ERC20_TOKEN_CONTRACT_ABI };
4
+ /** constants exports */
5
+ export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
+ /** basic blockchain exports */
7
+ export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
8
+ export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
+ export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
+ export { getProvider } from './blockchain/getProvider';
11
+ export { txStatus } from './blockchain/txStatus';
12
+ /** utils exports */
13
+ export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
+ export { transformBigInt } from './utils/transformBigInt';
15
+ import NATIVE_TOKENS from './utils/tokens';
16
+ export { NATIVE_TOKENS };
17
+ /** types exports */
18
+ export { BroadcastTransactionOptions, BuildUnsignedTransferTxOptions, EstimateGasLimitFromProviderProps, GasEstimateResult, TxStatusOptions, TxStatusResponse, UnsignedTransferTxResponse, } from './types/common';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /** ABIs exports */
2
+ import ERC20_TOKEN_CONTRACT_ABI from './ABIs/ERC20_TOKEN_CONTRACT_ABI';
3
+ export { ERC20_TOKEN_CONTRACT_ABI };
4
+ /** constants exports */
5
+ export { GAS_LIMIT_PER_TX_TYPE } from './constants/constants';
6
+ /** basic blockchain exports */
7
+ export { buildUnsignedTransferTx } from './blockchain/buildUnsignedTransferTx';
8
+ export { broadcastTransaction } from './blockchain/broadcastTransaction';
9
+ export { estimateGasLimitFromProvider } from './blockchain/estimateGasLimitFromProvider';
10
+ export { getProvider } from './blockchain/getProvider';
11
+ export { txStatus } from './blockchain/txStatus';
12
+ /** utils exports */
13
+ export { getShortenTransactionHash } from './utils/getShortenTxHash';
14
+ export { transformBigInt } from './utils/transformBigInt';
15
+ import NATIVE_TOKENS from './utils/tokens';
16
+ export { NATIVE_TOKENS };
@@ -0,0 +1,57 @@
1
+ /** npm imports */
2
+ import { JsonRpcApiProvider, JsonRpcProvider, TransactionReceipt, TransactionRequest } from 'ethers';
3
+ export interface EstimateGasLimitFromProviderProps {
4
+ provider: JsonRpcApiProvider | JsonRpcProvider;
5
+ unsignedTx: TransactionRequest;
6
+ walletAddress: string;
7
+ defaultGasLimit: bigint;
8
+ }
9
+ export interface GasEstimateResult {
10
+ gasEstimated: bigint;
11
+ gasLimit: bigint;
12
+ bufferPercentage: number;
13
+ fallbackUsed: boolean;
14
+ feeData: {
15
+ maxFeePerGas?: bigint;
16
+ maxPriorityFeePerGas?: bigint;
17
+ gasPrice?: bigint;
18
+ };
19
+ }
20
+ export interface BuildUnsignedTransferTxOptions {
21
+ fromAddress: string;
22
+ toAddress: string;
23
+ value?: string;
24
+ data?: string;
25
+ tokenAddress?: string;
26
+ tokenDecimals?: number;
27
+ rpcUrl: string;
28
+ chainId?: number;
29
+ defaultGasLimit: bigint;
30
+ }
31
+ export interface UnsignedTransferTxResponse {
32
+ unsignedTx: TransactionRequest;
33
+ nonce: number;
34
+ gasEstimated: string;
35
+ gasLimit: string;
36
+ bufferPercentage: number;
37
+ feeData: {
38
+ maxFeePerGas?: string;
39
+ maxPriorityFeePerGas?: string;
40
+ gasPrice?: string;
41
+ };
42
+ }
43
+ export interface BroadcastTransactionOptions {
44
+ signedTx: string;
45
+ rpcUrl: string;
46
+ chainId?: number;
47
+ waitConfirmations?: number;
48
+ }
49
+ export interface TxStatusOptions {
50
+ rpcUrl: string;
51
+ txHash: string;
52
+ chainId?: number;
53
+ }
54
+ export interface TxStatusResponse {
55
+ success: boolean;
56
+ receipt: TransactionReceipt | null;
57
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export declare const getShortenTransactionHash: (txHash: string) => string;
@@ -0,0 +1,5 @@
1
+ export const getShortenTransactionHash = (txHash) => {
2
+ const firstCharacters = txHash.substring(0, 6);
3
+ const lastCharacters = txHash.slice(-4);
4
+ return `${firstCharacters}...${lastCharacters}`;
5
+ };
@@ -0,0 +1,2 @@
1
+ export declare const errorMessagesForBroadcast: Record<string, string>;
2
+ export declare const errorMessagesForGasLimitEstimation: Record<string, string>;
@@ -0,0 +1,22 @@
1
+ export const errorMessagesForBroadcast = {
2
+ INSUFFICIENT_FUNDS: 'Insufficient funds for gas.',
3
+ NONCE_EXPIRED: 'Nonce expired.',
4
+ REPLACEMENT_UNDERPRICED: 'Replacement transaction underpriced.',
5
+ INVALID_SIGNATURE: 'Invalid transaction signature.',
6
+ GAS_PRICE_TOO_LOW: 'Gas price too low.',
7
+ UNDERPRICED: 'Gas price too low.',
8
+ OUT_OF_GAS: 'Transaction ran out of gas.',
9
+ UNPREDICTABLE_GAS_LIMIT: 'Unpredictable gas limit. Transaction might fail.',
10
+ INVALID_ARGUMENT: 'Invalid input arguments provided.',
11
+ UNKNOWN_ERROR: 'Unknown error.',
12
+ };
13
+ export const errorMessagesForGasLimitEstimation = {
14
+ INSUFFICIENT_FUNDS: 'Error: Insufficient funds to cover transaction fees.',
15
+ CALL_EXCEPTION: 'Error: The transaction would revert (CALL_EXCEPTION).',
16
+ OUT_OF_GAS: 'Error: Transaction would run out of gas.',
17
+ UNPREDICTABLE_GAS_LIMIT: 'Error: Unable to estimate gas. The transaction may fail.',
18
+ INVALID_ARGUMENT: 'Error: Invalid input arguments provided for gas estimation.',
19
+ GAS_LIMIT_REACHED: 'Error: Gas estimation exceeds block gas limit.',
20
+ UNKNOWN_ERROR: 'Unknown error.',
21
+ };
22
+ //TODO: Make methofds to parse errors and return user friendly messages based on the above records
@@ -0,0 +1,9 @@
1
+ export type NativeTokenType = {
2
+ [chainId: number]: {
3
+ symbol: string;
4
+ decimals: number;
5
+ name: string;
6
+ };
7
+ };
8
+ declare const NATIVE_TOKENS: NativeTokenType;
9
+ export default NATIVE_TOKENS;
@@ -0,0 +1,7 @@
1
+ const NATIVE_TOKENS = {
2
+ 1: { symbol: 'ETH', decimals: 18, name: 'Ethereum' },
3
+ 11155111: { symbol: 'ETH', decimals: 18, name: 'Ethereum' },
4
+ 56: { symbol: 'BNB', decimals: 18, name: 'BNB Chain' },
5
+ 137: { symbol: 'POL', decimals: 18, name: 'Polygon' },
6
+ };
7
+ export default NATIVE_TOKENS;
@@ -0,0 +1,20 @@
1
+ /** npm imports */
2
+ import { ContractTransaction } from 'ethers';
3
+ export declare const transformBigInt: (obj: ContractTransaction) => {
4
+ to: string;
5
+ data: string;
6
+ from?: string;
7
+ type?: number;
8
+ nonce?: number;
9
+ gasLimit?: bigint;
10
+ gasPrice?: bigint;
11
+ maxPriorityFeePerGas?: bigint;
12
+ maxFeePerGas?: bigint;
13
+ value?: bigint;
14
+ chainId?: bigint;
15
+ accessList?: import("ethers").AccessList;
16
+ authorizationList?: Array<import("ethers").Authorization>;
17
+ customData?: any;
18
+ blockTag?: import("ethers").BlockTag;
19
+ enableCcipRead?: boolean;
20
+ };
@@ -0,0 +1,8 @@
1
+ export const transformBigInt = (obj) => {
2
+ const newObj = { ...obj };
3
+ for (let key in obj) {
4
+ if (typeof obj[key] === 'bigint')
5
+ newObj[key] = String(obj[key]);
6
+ }
7
+ return newObj;
8
+ };
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@octaflowlabs/onchain-sdk",
3
+ "version": "1.0.0-test10",
4
+ "description": "onchain methods for web3",
5
+ "repository": "https://github.com/crisramb665/onchain-sdk.git",
6
+ "license": "MIT",
7
+ "main": "dist/cjs/index.js",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "scripts": {
14
+ "build": "rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && tsc-alias",
15
+ "prettier": "prettier --write \"src/**/*.ts\"",
16
+ "prepublishOnly": "yarn run build"
17
+ },
18
+ "devDependencies": {
19
+ "eslint": "^9.39.2",
20
+ "eslint-config-prettier": "^10.1.8",
21
+ "eslint-plugin-prettier": "^5.5.5",
22
+ "prettier": "^3.8.1",
23
+ "tsc-alias": "^1.8.16",
24
+ "typescript": "^5.9.3"
25
+ },
26
+ "dependencies": {
27
+ "ethers": "^6.16.0"
28
+ }
29
+ }