This repository was archived by the owner on Mar 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Expand file tree
/
Copy pathutils.ts
More file actions
287 lines (257 loc) · 9.28 KB
/
utils.ts
File metadata and controls
287 lines (257 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import { RLP } from '@ethereumjs/rlp';
import {
InvalidAddressError,
InvalidMethodParamsError,
InvalidNumberError,
Web3ContractError,
} from 'web3-errors';
import {
TransactionForAccessList,
AbiFunctionFragment,
TransactionWithSenderAPI,
TransactionCall,
HexString,
Address,
NonPayableCallOptions,
PayableCallOptions,
ContractOptions,
Numbers,
AbiConstructorFragment,
} from 'web3-types';
import {
isNullish,
mergeDeep,
isContractInitOptions,
keccak256,
toChecksumAddress,
hexToNumber,
} from 'web3-utils';
import { isAddress, isHexString } from 'web3-validator';
import { encodeMethodABI } from './encoding.js';
import { Web3ContractContext } from './types.js';
const dataInputEncodeMethodHelper = (
txParams: TransactionCall | TransactionForAccessList,
abi: AbiFunctionFragment | AbiConstructorFragment,
params: unknown[],
dataInputFill?: 'data' | 'input' | 'both',
): { data?: HexString; input?: HexString } => {
const tx: { data?: HexString; input?: HexString } = {};
if (!isNullish(txParams.data) || dataInputFill === 'both') {
tx.data = encodeMethodABI(abi, params, (txParams.data ?? txParams.input) as HexString);
}
if (!isNullish(txParams.input) || dataInputFill === 'both') {
tx.input = encodeMethodABI(abi, params, (txParams.input ?? txParams.data) as HexString);
}
// if input and data is empty, use web3config default
if (isNullish(tx.input) && isNullish(tx.data)) {
tx[dataInputFill as 'data' | 'input'] = encodeMethodABI(abi, params);
}
return { data: tx.data as HexString, input: tx.input as HexString };
};
export const getSendTxParams = ({
abi,
params,
options,
contractOptions,
}: {
abi: AbiFunctionFragment | AbiConstructorFragment;
params: unknown[];
options?: (PayableCallOptions | NonPayableCallOptions) & {
input?: HexString;
data?: HexString;
to?: Address;
dataInputFill?: 'input' | 'data' | 'both';
};
contractOptions: ContractOptions;
}): TransactionCall => {
const deploymentCall =
options?.input ?? options?.data ?? contractOptions.input ?? contractOptions.data;
if (!deploymentCall && !options?.to && !contractOptions.address) {
throw new Web3ContractError('Contract address not specified');
}
if (!options?.from && !contractOptions.from) {
throw new Web3ContractError('Contract "from" address not specified');
}
let txParams = mergeDeep(
{
to: contractOptions.address,
gas: contractOptions.gas,
gasPrice: contractOptions.gasPrice,
from: contractOptions.from,
input: contractOptions.input,
maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas,
maxFeePerGas: contractOptions.maxFeePerGas,
data: contractOptions.data,
},
options as unknown as Record<string, unknown>,
) as unknown as TransactionCall;
const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill);
txParams = { ...txParams, data: dataInput.data, input: dataInput.input };
return txParams;
};
export const getEthTxCallParams = ({
abi,
params,
options,
contractOptions,
}: {
abi: AbiFunctionFragment;
params: unknown[];
options?: (PayableCallOptions | NonPayableCallOptions) & {
to?: Address;
dataInputFill?: 'input' | 'data' | 'both';
};
contractOptions: ContractOptions;
}): TransactionCall => {
if (!options?.to && !contractOptions.address) {
throw new Web3ContractError('Contract address not specified');
}
let txParams = mergeDeep(
{
to: contractOptions.address,
gas: contractOptions.gas,
gasPrice: contractOptions.gasPrice,
from: contractOptions.from,
input: contractOptions.input,
maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas,
maxFeePerGas: contractOptions.maxFeePerGas,
data: contractOptions.data,
},
options as unknown as Record<string, unknown>,
) as unknown as TransactionCall;
const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill);
txParams = { ...txParams, data: dataInput.data, input: dataInput.input };
return txParams;
};
export const getEstimateGasParams = ({
abi,
params,
options,
contractOptions,
}: {
abi: AbiFunctionFragment;
params: unknown[];
options?: (PayableCallOptions | NonPayableCallOptions) & {
dataInputFill?: 'input' | 'data' | 'both';
};
contractOptions: ContractOptions;
}): Partial<TransactionWithSenderAPI> => {
let txParams = mergeDeep(
{
to: contractOptions.address,
gas: contractOptions.gas,
gasPrice: contractOptions.gasPrice,
from: contractOptions.from,
input: contractOptions.input,
data: contractOptions.data,
},
options as unknown as Record<string, unknown>,
) as unknown as TransactionCall;
const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill);
txParams = { ...txParams, data: dataInput.data, input: dataInput.input };
return txParams as TransactionWithSenderAPI;
};
export const isWeb3ContractContext = (options: unknown): options is Web3ContractContext =>
typeof options === 'object' &&
!isNullish(options) &&
Object.keys(options).length !== 0 &&
!isContractInitOptions(options);
export const getCreateAccessListParams = ({
abi,
params,
options,
contractOptions,
}: {
abi: AbiFunctionFragment;
params: unknown[];
options?: (PayableCallOptions | NonPayableCallOptions) & {
to?: Address;
dataInputFill?: 'input' | 'data' | 'both';
};
contractOptions: ContractOptions;
}): TransactionForAccessList => {
if (!options?.to && !contractOptions.address) {
throw new Web3ContractError('Contract address not specified');
}
if (!options?.from && !contractOptions.from) {
throw new Web3ContractError('Contract "from" address not specified');
}
let txParams = mergeDeep(
{
to: contractOptions.address,
gas: contractOptions.gas,
gasPrice: contractOptions.gasPrice,
from: contractOptions.from,
input: contractOptions.input,
maxPriorityFeePerGas: contractOptions.maxPriorityFeePerGas,
maxFeePerGas: contractOptions.maxFeePerGas,
data: contractOptions.data,
},
options as unknown as Record<string, unknown>,
) as unknown as TransactionForAccessList;
const dataInput = dataInputEncodeMethodHelper(txParams, abi, params, options?.dataInputFill);
txParams = { ...txParams, data: dataInput.data, input: dataInput.input };
return txParams;
};
/**
* Generates the Ethereum address of a contract created via a regular transaction.
*
* This function calculates the contract address based on the sender's address and nonce,
* following Ethereum's address generation rules.
*
* @param from The sender’s Ethereum {@link Address}, from which the contract will be deployed.
* @param nonce The transaction count (or {@link Numbers}) of the sender account at the time of contract creation.
* You can get it here: https://docs.web3js.org/api/web3/class/Web3Eth#getTransactionCount.
* @returns An Ethereum {@link Address} of the contract in checksum address format.
* @throws An {@link InvalidAddressError} if the provided address ('from') is invalid.
* @throws An {@link InvalidNumberError} if the provided nonce value is not in a valid format.
* @example
* ```ts
* const from = "0x1234567890abcdef1234567890abcdef12345678";
* const nonce = (await web3.eth.getTransactionCount(from)) + 1; // The nonce value for the transaction
*
* const res = createContractAddress(from, nonce);
*
* console.log(res);
* // > "0x604f1ECbA68f4B4Da57D49C2b945A75bAb331208"
* ```
*/
export const createContractAddress = (from: Address, nonce: Numbers): Address => {
if (!isAddress(from)) throw new InvalidAddressError(`Invalid address given ${from}`);
let nonceValue = nonce;
if (typeof nonce === 'string' && isHexString(nonce)) nonceValue = hexToNumber(nonce);
else if (typeof nonce === 'string' && !isHexString(nonce))
throw new InvalidNumberError('Invalid nonce value format');
const rlpEncoded = RLP.encode([from, nonceValue]);
const result = keccak256(rlpEncoded);
const contractAddress = '0x'.concat(result.substring(26));
return toChecksumAddress(contractAddress);
};
export const create2ContractAddress = (
from: Address,
salt: HexString,
initCode: HexString,
): Address => {
if (!isAddress(from)) throw new InvalidAddressError(`Invalid address given ${from}`);
if (!isHexString(salt)) throw new InvalidMethodParamsError(`Invalid salt value ${salt}`);
if (!isHexString(initCode))
throw new InvalidMethodParamsError(`Invalid initCode value ${initCode}`);
const initCodeHash = keccak256(initCode);
const initCodeHashPadded = initCodeHash.padStart(64, '0'); // Pad to 32 bytes (64 hex characters)
const create2Params = ['0xff', from, salt, initCodeHashPadded].map(x => x.replace(/0x/, ''));
const create2Address = `0x${create2Params.join('')}`;
return toChecksumAddress(`0x${keccak256(create2Address).slice(26)}`); // Slice to get the last 20 bytes (40 hex characters) & checksum
};