Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit 568b4b2

Browse files
nazarhussainspacesailor24jdevcs
authored
Update web3-eth-contract to use web3-eth methods (#4806)
* Add @ethereumjs/tx dependency * Update Web3BaseProvider to SupportedProviders for Web3Eth constructor * WIP eth-tx * Add support for undefined values for convertToValidType * Remove unused Web3BaseProvider * WIP eth-tx utils * Export privateKeyToAddress * Add web3-eth-accounts dependency * WIP web3-eth-tx util methods * Replace inline errors with error constructors * Change types for transaction r and s properties. Correct hardforks in detectTransactionType * Init formatTransaction tests and fixture * Init detectTransactionType and fixture * Add more descriptive error messages * Logic fixes for validateTransactionForSigning * Init validateTransactionForSigning tests and fixtures * Add esModuleInterop: true to tsconfig * Small bug fixes and added TODOs * Add parent describe to detect_transaction_type test * Add parent describe to format_transaction test * Add web3-providers-http as dev dependency for tests * Init populate_transaction tests * Move types from eth_tx.ts to types.ts * Remove TODOs * Add missing , * Remove TODO * Remove TODO * Fix transaction type import issues * Update convertToValidType test data for undefined * Update override method tests * Update packages/web3-eth/src/eth_tx.ts Co-authored-by: jdevcs <86780488+jdevcs@users.noreply.github.com> * Move getBlock to after type check for populateTransaction * Replace N/A with name of error for error.msg * Assign formattedTransaction type Transaction<ReturnType> * convertToValidType now throws error for value === undefined * NumberType extends Numbers * Transaction type related changes * Refactor DesiredType logic * Convert to deep copy for formatTransaction method * skip override method test - needs to be refactored. General formatting * Skip override method test - needs to be refactored. Set input.type > 0x7f * Refactor formatTransaction * Add error codes to web3-eth errors * Refactor validateGate if statements into readable consts * Update comment * Add link to error message from 1.x * Fix bug with is gas consts in validateGas * Init InvalidConvertibleValueError * Replace error with InvalidConvertibleValueError * Update tests for formatting undefined * Update expected errors for validateGas tests * No longer default tx.type if undefined * Refactor detectTransactionType * Fix type error for return in detectTransactionType * Init rpc_method_wrappers.ts * Remove Web3Eth import * Refactor use of web3Context.defaults * Restore Formatted transaction types * Init web3_rpc_method_wrappers tests * Refactor web3_eth_methods_with_parameters test * Replace if X === undefined checks with ? * Un-export consts that aren't used * Add defaultTransactionType and defaultMaxPriorityFeePerGas * Update defaults for chain and hardfork to mainnet and london * Update to use web3Context.default chain and hardfork. Init tests for defaults * Update test to account for added defaults * Refactor validateGas to use helper methods * remove TODO * Init error TransactionGasMismatchError * Fix tests and refactor transaction validator helper methods * Move validation methods to validation.ts * Add input to Transaction type * Add @ethereumjs/common dependency * yarn format * Remove null for defaultTransactionType * Add default for defaultTransactionType * Update default for defaultTransactionType * Bug fixes, refactors, and init prepareTransactionForSigning and tests * Remove unused test code * revert transaction data and value to default to 0x * Fix failing populate_transaction tests * Add defaultNetworkId to web3_config * Add TODO for failing prepare_transaction_for_signing test * Remove TODO * Init TransactionDataAndInputError * Add else if to populateTransaction - data * Refactor populateTransaction - chainId * Comment out unused ifs * Remove populateTransaction - gas * Remove populateTransaction - hexTxType * Replace use of ValidReturnTypes[ValidTypes.HexString] with HexString * Remove toHex import * Remove | null for Web3ConfigOptions defaultChain and defaultHardfork * Refactor getEthereumjsTransactionOptions * Remove no longer needed populateTransaction - gas test * Update packages/web3-eth/src/validation.ts * Remove unnecessary rpc method wrappers * Web3Eth now extends Web3Context instead of instantiating it * Init getPendingTransactions * Init requestAccounts * Add EIP-1102 as a comment for requestAccounts * Init getChainId * Init getProof * Init Web3EthExecutionAPI * Fix imports for AccountObject in fixtures * Add formatting to getPendingTransactions. Move formatTransaction to seperate file * Add TODO to investigate transaction.data * Add formatting to getChainId response * Init getNodeInfo * Revert esModuleInterop change * Combine networkId and chainId if statements * yarn format * Add Partial to type of transaction for eth_sendTransaction * Init transactionReceiptPollingInterval and transactionConfirmationPollingInterval * Add TODO and Partial to transaction type for sendTransaction * WIP sendTransaction and PromiEvent integration * Add eslint-disable-next-line * Add eslint-disable-next-line * Move TransactionEvents * eslint fixes * Update sendSignedTransaction to use PromiEvent * Init signTransaction * Refactor TransactionCall * Comment out validation for call * Init TransactionCall type for web3-eth types * Remove as BaseTransaction from isTransactionCall * Implement call for rpc_method_wrappers * Uncomment sendTransaction, signTransaction, and call * ✨ Update estimate gas method to use web3-eth * 🎨 Update contract mehtod send to use web3-eth utility functions * 🎨 Update contract method call to use web3-eth utilities * 🎨 Fix code introduced in merge conflicts Co-authored-by: Wyatt Barnes <me@wyatt.email> Co-authored-by: jdevcs <86780488+jdevcs@users.noreply.github.com>
1 parent 39f8fd5 commit 568b4b2

File tree

8 files changed

+192
-193
lines changed

8 files changed

+192
-193
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,7 @@ Released with 1.0.0-beta.37 code base.
357357
4. `recover` function's last param is boolean `hashed`, it is used to indicate if data provided is already hashed or not. By default this function will assume data is not hashed.
358358
5. The `Wallet` no more supports address/number indexing. Have to use `wallet.get` instead.
359359
6. `Wallet.create` function doesn't accepts `entropy` param
360+
7. `contract.method.send()` will resolve to transaction receipt instead of `transactionHash`. User can use `receipt.transactionHash` instead.
360361

361362
#### web3-net
362363

@@ -368,3 +369,4 @@ Released with 1.0.0-beta.37 code base.
368369
2. `setContent` is not supported in web3-eth-ens 4.x as its deprecated in ENS public resolver (https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol)
369370
3. `getContent` is not supported in web3-eth-ens 4.x as its deprecated in ENS public resolver.
370371
4. `getMultihash` is not supported in web3-eth-ens 4.x as its deprecated in ENS public resolver.
372+

packages/web3-common/src/web3_event_emitter.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,16 @@ export class Web3EventEmitter<T extends Web3EventMap> implements Web3Emitter<T>
3131
public emit<K extends Web3EventKey<T>>(eventName: K, params: T[K]) {
3232
this._emitter.emit(eventName, params);
3333
}
34+
35+
public listenerCount<K extends Web3EventKey<T>>(eventName: K) {
36+
return this._emitter.listenerCount(eventName);
37+
}
38+
39+
public listeners<K extends Web3EventKey<T>>(eventName: K) {
40+
return this._emitter.listeners(eventName);
41+
}
42+
43+
public eventNames() {
44+
return this._emitter.eventNames();
45+
}
3446
}

packages/web3-eth-contract/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
"web3-core": "4.0.0-alpha.0",
3030
"web3-eth-abi": "4.0.0-alpha.0",
3131
"web3-utils": "4.0.0-alpha.1",
32-
"web3-validator": "0.1.0-alpha.0"
32+
"web3-validator": "0.1.0-alpha.0",
33+
"web3-eth": "4.0.0-alpha.1"
3334
},
3435
"devDependencies": {
3536
"@humeris/espresso-shot": "^4.0.0",

packages/web3-eth-contract/src/contract.ts

Lines changed: 67 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@ import {
1414
isAbiFunctionFragment,
1515
jsonInterfaceMethodToString,
1616
} from 'web3-eth-abi';
17+
import { estimateGas, sendTransaction, call } from 'web3-eth/src/rpc_method_wrappers';
1718
import {
1819
Address,
1920
BlockNumberOrTag,
2021
BlockTags,
21-
hexToNumber,
22-
toChecksumAddress,
2322
HexString,
23+
toChecksumAddress,
24+
ValidTypes,
2425
} from 'web3-utils';
2526
import { validator } from 'web3-validator';
2627
import { decodeMethodReturn, encodeEventABI, encodeMethodABI } from './encoding';
@@ -164,47 +165,38 @@ export class Contract<Abi extends ContractAbi>
164165

165166
return {
166167
arguments: args,
167-
// TODO: Use `web3-eth-tx` package to return `PromiEvent` instead.
168168
send: async (options?: PayableCallOptions) => {
169169
const modifiedOptions = { ...options };
170170
delete modifiedOptions.to;
171171

172-
const txHash = await this._contractMethodSend(
172+
const promiEvent = this._contractMethodSend(
173173
abi as AbiFunctionFragment,
174174
args,
175175
modifiedOptions,
176176
contractOptions,
177177
);
178178

179-
return txHash;
180-
181-
// TODO: Use eth-tx functions to
182-
//
183-
// 1. Get the transaction receipt from the above txHash
184-
// 2. Extract the contract address from the receipt
185-
// 3. Get the code from eth_getCode for the contract address
186-
// 4. Return the contract instance with the new address and the code
187-
//
188-
// return new Contract<Abi>(this._jsonInterface, contractAddress as HexString, {
189-
// gas: this.options.gas,
190-
// gasPrice: this.options.gasPrice,
191-
// gasLimit: this.options.gasLimit,
192-
// from: this.options.from,
193-
// data: this.options.data,
194-
// provider: this.currentProvider,
195-
// });
179+
// eslint-disable-next-line no-void
180+
void promiEvent.then(res => {
181+
this._address = res.contractAddress;
182+
});
183+
184+
return promiEvent;
196185
},
197-
estimateGas: async (options?: PayableCallOptions, block?: BlockNumberOrTag) => {
186+
estimateGas: async <ReturnType extends ValidTypes = ValidTypes.HexString>(
187+
options?: PayableCallOptions,
188+
returnType?: ReturnType,
189+
) => {
198190
const modifiedOptions = { ...options };
199191
delete modifiedOptions.to;
200192

201-
return this._contractMethodEstimateGas(
202-
abi as AbiFunctionFragment,
203-
args,
204-
modifiedOptions,
205-
block,
193+
return this._contractMethodEstimateGas({
194+
abi: abi as AbiFunctionFragment,
195+
params: args,
196+
returnType,
197+
options: modifiedOptions,
206198
contractOptions,
207-
);
199+
});
208200
},
209201
encodeABI: () => encodeMethodABI(abi as AbiFunctionFragment, args, data),
210202
};
@@ -296,11 +288,12 @@ export class Contract<Abi extends ContractAbi>
296288
arguments: params,
297289
call: async (options?: PayableCallOptions, block?: BlockNumberOrTag) =>
298290
this._contractMethodCall(abi, params, options, block),
299-
// TODO: Use `web3-eth-tx` package to return `PromiEvent` instead.
300-
send: async (options?: PayableCallOptions) =>
291+
send: (options?: PayableCallOptions) =>
301292
this._contractMethodSend(abi, params, options),
302-
estimateGas: async (options?: PayableCallOptions, block?: BlockNumberOrTag) =>
303-
this._contractMethodEstimateGas(abi, params, options, block),
293+
estimateGas: async <ReturnType extends ValidTypes = ValidTypes.HexString>(
294+
options?: PayableCallOptions,
295+
returnType?: ReturnType,
296+
) => this._contractMethodEstimateGas({ abi, params, returnType, options }),
304297
encodeABI: () => encodeMethodABI(abi, params),
305298
} as unknown as PayableMethodObject<
306299
ContractMethod<T>['Inputs'],
@@ -312,10 +305,12 @@ export class Contract<Abi extends ContractAbi>
312305
arguments: params,
313306
call: async (options?: NonPayableCallOptions, block?: BlockNumberOrTag) =>
314307
this._contractMethodCall(abi, params, options, block),
315-
send: async (options?: NonPayableCallOptions) =>
308+
send: (options?: NonPayableCallOptions) =>
316309
this._contractMethodSend(abi, params, options),
317-
estimateGas: async (options?: NonPayableCallOptions, block?: BlockNumberOrTag) =>
318-
this._contractMethodEstimateGas(abi, params, options, block),
310+
estimateGas: async <ReturnType extends ValidTypes = ValidTypes.HexString>(
311+
options?: NonPayableCallOptions,
312+
returnType?: ReturnType,
313+
) => this._contractMethodEstimateGas({ abi, params, returnType, options }),
319314
encodeABI: () => encodeMethodABI(abi, params),
320315
} as unknown as NonPayableMethodObject<
321316
ContractMethod<T>['Inputs'],
@@ -330,68 +325,56 @@ export class Contract<Abi extends ContractAbi>
330325
options?: Options,
331326
block?: BlockNumberOrTag,
332327
) {
333-
return decodeMethodReturn(
328+
const tx = getEthTxCallParams({
334329
abi,
335-
await this.requestManager.send({
336-
method: 'eth_call',
337-
params: [
338-
getEthTxCallParams({
339-
abi,
340-
params,
341-
options,
342-
contractOptions: this.options,
343-
}),
344-
block ?? BlockTags.LATEST,
345-
],
346-
}),
347-
);
330+
params,
331+
options,
332+
contractOptions: this.options,
333+
});
334+
335+
return decodeMethodReturn(abi, await call(this, tx, block));
348336
}
349337

350-
private async _contractMethodSend<Options extends PayableCallOptions | NonPayableCallOptions>(
338+
private _contractMethodSend<Options extends PayableCallOptions | NonPayableCallOptions>(
351339
abi: AbiFunctionFragment,
352340
params: unknown[],
353341
options?: Options,
354342
contractOptions?: ContractOptions,
355343
) {
356-
return decodeMethodReturn(
344+
const tx = getSendTxParams({
357345
abi,
358-
await this.requestManager.send({
359-
method: 'eth_sendTransaction',
360-
params: [
361-
getSendTxParams({
362-
abi,
363-
params,
364-
options,
365-
contractOptions: contractOptions ?? this.options,
366-
}),
367-
],
368-
}),
369-
);
346+
params,
347+
options,
348+
contractOptions: contractOptions ?? this.options,
349+
});
350+
351+
return sendTransaction(this, tx);
370352
}
371353

372354
private async _contractMethodEstimateGas<
373355
Options extends PayableCallOptions | NonPayableCallOptions,
374-
>(
375-
abi: AbiFunctionFragment,
376-
params: unknown[],
377-
options?: Options,
378-
block?: BlockNumberOrTag,
379-
contractOptions?: ContractOptions,
380-
) {
381-
return hexToNumber(
382-
await this.requestManager.send({
383-
method: 'eth_estimateGas',
384-
params: [
385-
getEstimateGasParams({
386-
abi,
387-
params,
388-
options,
389-
contractOptions: contractOptions ?? this.options,
390-
}),
391-
block ?? BlockTags.LATEST,
392-
],
393-
}),
394-
);
356+
ReturnType extends ValidTypes = ValidTypes.HexString,
357+
>({
358+
abi,
359+
params,
360+
returnType,
361+
options,
362+
contractOptions,
363+
}: {
364+
abi: AbiFunctionFragment;
365+
params: unknown[];
366+
returnType?: ReturnType;
367+
options?: Options;
368+
contractOptions?: ContractOptions;
369+
}) {
370+
const tx = getEstimateGasParams({
371+
abi,
372+
params,
373+
options,
374+
contractOptions: contractOptions ?? this.options,
375+
});
376+
377+
return estimateGas(this, tx, BlockTags.LATEST, returnType);
395378
}
396379

397380
// eslint-disable-next-line class-methods-use-this
Lines changed: 17 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { EthExecutionAPI, PromiEvent, ReceiptInfo } from 'web3-common';
1+
import { EthExecutionAPI, ReceiptInfo } from 'web3-common';
22
import { SupportedProviders } from 'web3-core';
33
import { ContractAbi } from 'web3-eth-abi';
4-
import { Address, BlockNumberOrTag, Bytes, Filter, HexString, Numbers, Uint } from 'web3-utils';
4+
import { sendTransaction } from 'web3-eth/src/rpc_method_wrappers';
5+
import { Address, BlockNumberOrTag, Bytes, Filter, HexString, Uint, ValidTypes } from 'web3-utils';
56

67
export interface EventLog {
78
event: string;
@@ -43,14 +44,14 @@ export interface ContractInitOptions {
4344
export type TransactionReceipt = ReceiptInfo;
4445

4546
export interface NonPayableCallOptions {
46-
nonce?: Numbers;
47-
chainId?: Numbers;
47+
nonce?: HexString;
48+
chainId?: HexString;
4849
from?: Address;
4950
to?: Address;
5051
data?: HexString;
5152
gas?: string;
52-
maxPriorityFeePerGas?: Numbers;
53-
maxFeePerGas?: Numbers;
53+
maxPriorityFeePerGas?: HexString;
54+
maxFeePerGas?: HexString;
5455
gasPrice?: string;
5556
}
5657

@@ -61,43 +62,21 @@ export interface PayableCallOptions extends NonPayableCallOptions {
6162
export interface NonPayableMethodObject<Inputs = unknown[], Outputs = unknown[]> {
6263
arguments: Inputs;
6364
call(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise<Outputs>;
64-
send(tx?: NonPayableCallOptions): PromiEvent<
65-
TransactionReceipt,
66-
{
67-
sending: object;
68-
sent: object;
69-
transactionHash: string;
70-
receipt: TransactionReceipt;
71-
confirmation: {
72-
confirmations: number;
73-
receipt: TransactionReceipt;
74-
latestBlockHash: HexString;
75-
};
76-
error: Error;
77-
}
78-
>;
79-
estimateGas(tx?: NonPayableCallOptions): Promise<number>;
65+
send(tx?: NonPayableCallOptions): ReturnType<typeof sendTransaction>;
66+
estimateGas<ReturnType extends ValidTypes = ValidTypes.HexString>(
67+
options?: NonPayableCallOptions,
68+
returnType?: ReturnType,
69+
): Promise<ReturnType>;
8070
encodeABI(): string;
8171
}
8272

8373
export interface PayableMethodObject<Inputs = unknown[], Outputs = unknown[]> {
8474
arguments: Inputs;
8575
call(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise<Outputs>;
86-
send(tx?: PayableCallOptions): PromiEvent<
87-
TransactionReceipt,
88-
{
89-
sending: object;
90-
sent: object;
91-
transactionHash: string;
92-
receipt: TransactionReceipt;
93-
confirmation: {
94-
confirmations: number;
95-
receipt: TransactionReceipt;
96-
latestBlockHash: HexString;
97-
};
98-
error: Error;
99-
}
100-
>;
101-
estimateGas(tx?: PayableCallOptions): Promise<number>;
76+
send(tx?: PayableCallOptions): ReturnType<typeof sendTransaction>;
77+
estimateGas<ReturnType extends ValidTypes = ValidTypes.HexString>(
78+
options?: PayableCallOptions,
79+
returnType?: ReturnType,
80+
): Promise<ReturnType>;
10281
encodeABI(): HexString;
10382
}

packages/web3-eth-contract/src/utils.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { TransactionCall, TransactionWithSender } from 'web3-common';
1+
import { TransactionWithSender } from 'web3-common';
22
import { AbiFunctionFragment } from 'web3-eth-abi';
33
import { mergeDeep } from 'web3-utils';
4+
import { TransactionCall } from 'web3-eth/src/types';
45
import { encodeMethodABI } from './encoding';
56
import { Web3ContractError } from './errors';
67
import { NonPayableCallOptions, PayableCallOptions, ContractOptions } from './types';
@@ -15,7 +16,7 @@ export const getSendTxParams = ({
1516
params: unknown[];
1617
options?: PayableCallOptions | NonPayableCallOptions;
1718
contractOptions: ContractOptions;
18-
}): TransactionWithSender & { data: string } => {
19+
}): TransactionCall => {
1920
if (!options?.to && !contractOptions.address) {
2021
throw new Web3ContractError('Contract address not specified');
2122
}
@@ -33,7 +34,7 @@ export const getSendTxParams = ({
3334
data: contractOptions.data,
3435
},
3536
options as unknown as Record<string, unknown>,
36-
) as unknown as TransactionWithSender & { data: string };
37+
) as unknown as TransactionCall;
3738

3839
if (!txParams.data) {
3940
txParams = {
@@ -114,5 +115,5 @@ export const getEstimateGasParams = ({
114115
};
115116
}
116117

117-
return txParams;
118+
return txParams as TransactionWithSender;
118119
};

0 commit comments

Comments
 (0)