Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
},
parserOptions: {
ecmaVersion: 2016,
project: './tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
Expand Down
6 changes: 3 additions & 3 deletions packages/web3-common/src/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { FormatterError } from 'web3-errors';
import { Iban } from 'web3-eth-iban';
import { Web3Iban } from 'web3-eth-iban';
import {
BlockTags,
Filter,
Expand Down Expand Up @@ -121,8 +121,8 @@ export const inputDefaultBlockNumberFormatter = (
};

export const inputAddressFormatter = (address: string): string | never => {
if (Iban.isValid(address) && Iban.isDirect(address)) {
const iban = new Iban(address);
if (Web3Iban.isValid(address) && Web3Iban.isDirect(address)) {
const iban = new Web3Iban(address);

return iban.toAddress().toLowerCase();
}
Expand Down
3 changes: 2 additions & 1 deletion packages/web3-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export * from './web3_base_wallet';
export * from './web3_event_emitter';
export * from './eth_execution_api';
export * from './deferred_promise';
export * from './promi_event';
export * from './web3_promi_event';
export * from './formatters';
export * as formatters from './formatters';
export * from './formatter';
export * as jsonRpc from './json_rpc';
21 changes: 21 additions & 0 deletions packages/web3-common/src/web3_base_provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,27 @@ export abstract class Web3BaseProvider<API extends Web3APISpec = EthExecutionAPI
public abstract getStatus(): Web3BaseProviderStatus;
public abstract supportsSubscriptions(): boolean;

/**
* @deprecated Please use `.request` instead.
*
* @param payload - Request Payload
* @param cb - Callback
*/
public send<Method extends Web3APIMethod<API>, ResponseType = Web3APIReturnType<API, Method>>(
payload: Web3APIPayload<API, Method>,
// Used "null" value to match the legacy version
// eslint-disable-next-line @typescript-eslint/ban-types
cb: (err?: Error | null, response?: JsonRpcResponse<ResponseType>) => void,
) {
this.request(payload)
.then(response => {
cb(undefined, response);
})
.catch((err: Error) => {
cb(err);
});
}

// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#request
public abstract request<
Method extends Web3APIMethod<API>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export type PromiseExecutor<T> = (
reject: (reason: unknown) => void,
) => void;

export class PromiEvent<ResolveType, EventMap extends Web3EventMap>
export class Web3PromiEvent<ResolveType, EventMap extends Web3EventMap>
extends Web3EventEmitter<EventMap>
implements Promise<ResolveType>
{
Expand Down
24 changes: 12 additions & 12 deletions packages/web3-common/test/unit/formatters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import * as utils from 'web3-utils';
import { Iban } from 'web3-eth-iban';
import { Web3Iban } from 'web3-eth-iban';
import {
inputAddressFormatter,
inputBlockNumberFormatter,
Expand Down Expand Up @@ -54,8 +54,8 @@ describe('formatters', () => {
jest.spyOn(utils, 'isHexStrict').mockReturnValue(true);
jest.spyOn(utils, 'isAddress').mockReturnValue(true);
jest.spyOn(utils, 'sha3Raw').mockReturnValue(sha3Result);
jest.spyOn(Iban, 'isValid').mockImplementation(() => false);
jest.spyOn(Iban, 'isDirect').mockImplementation(() => false);
jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => false);
jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => false);
});

describe('outputProofFormatter', () => {
Expand All @@ -82,9 +82,9 @@ describe('formatters', () => {

describe('outputBigIntegerFormatter', () => {
it('should convert input to number', () => {
const result = outputBigIntegerFormatter(12n);
const result = outputBigIntegerFormatter(BigInt(12));

expect(utils.toNumber).toHaveBeenCalledWith(12n);
expect(utils.toNumber).toHaveBeenCalledWith(BigInt(12));
expect(result).toEqual(toNumberResult);
});
});
Expand Down Expand Up @@ -139,13 +139,13 @@ describe('formatters', () => {
describe('inputAddressFormatter', () => {
it('should return lowercase address if given value is iban', () => {
const address = '0x00c5496aee77c1ba1f0854206a26dda82a81d6d8';
Iban.prototype.toAddress = jest.fn(() => address);
Web3Iban.prototype.toAddress = jest.fn(() => address);

jest.spyOn(Iban, 'isValid').mockImplementation(() => true);
jest.spyOn(Iban, 'isDirect').mockImplementation(() => true);
jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => true);
jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => true);

expect(inputAddressFormatter('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS')).toBe(address);
expect(Iban.prototype.toAddress).toHaveBeenCalled();
expect(Web3Iban.prototype.toAddress).toHaveBeenCalled();
});

it('should return lower case value if valid address', () => {
Expand Down Expand Up @@ -243,13 +243,13 @@ describe('formatters', () => {
it.each(['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce'])(
'should convert "%s" number value to hex',
attr => {
jest.spyOn(utils, 'toNumber').mockReturnValue(5678n);
jest.spyOn(utils, 'toNumber').mockReturnValue(BigInt(5678));

expect(
txInputOptionsFormatter({ ...txInput, data: '0xff0011', [attr]: 5678n }),
txInputOptionsFormatter({ ...txInput, data: '0xff0011', [attr]: BigInt(5678) }),
).toEqual(expect.objectContaining({ [attr]: numberToHexResult }));

expect(utils.numberToHex).toHaveBeenCalledWith(5678n);
expect(utils.numberToHex).toHaveBeenCalledWith(BigInt(5678));
},
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ 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 { PromiEvent } from '../../src/promi_event';
import { Web3PromiEvent } from '../../src/web3_promi_event';

describe('PromiEvent', () => {
describe('Web3PromiEvent', () => {
it('should initialize and resolve promise', async () => {
const p = new PromiEvent(resolve => {
const p = new Web3PromiEvent(resolve => {
resolve('Resolved Value');
});

await expect(p).resolves.toBe('Resolved Value');
});

it('should initialize and reject promise', async () => {
const p = new PromiEvent((_, reject) => {
const p = new Web3PromiEvent((_, reject) => {
reject(new Error('My Error'));
});

Expand All @@ -36,7 +36,7 @@ describe('PromiEvent', () => {

it('should initialize and emit event', async () => {
return new Promise(done => {
const p = new PromiEvent<string, { data: string }>(resolve => {
const p = new Web3PromiEvent<string, { data: string }>(resolve => {
resolve('resolved value');
});

Expand All @@ -56,7 +56,7 @@ describe('PromiEvent', () => {
it('should initialize and emit later', async () => {
return new Promise(done => {
const func = () => {
const p = new PromiEvent<string, { data: string }>(resolve => {
const p = new Web3PromiEvent<string, { data: string }>(resolve => {
resolve('resolved value');
});

Expand Down
3 changes: 1 addition & 2 deletions packages/web3-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ export type SupportedProviders<API extends Web3APISpec> =
| Web3BaseProvider<API>
| LegacyRequestProvider
| LegacySendProvider
| LegacySendAsyncProvider
| string;
| LegacySendAsyncProvider;

export type Web3BaseProviderConstructor = new <API extends Web3APISpec>(
url: string,
Expand Down
11 changes: 7 additions & 4 deletions packages/web3-core/src/web3_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export type Web3ContextInitOptions<
} = any,
> = {
config?: Partial<Web3ConfigOptions>;
provider: SupportedProviders<API>;
provider: SupportedProviders<API> | string;
requestManager?: Web3RequestManager<API>;
subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs> | undefined;
registeredSubscriptions?: RegisteredSubs;
Expand Down Expand Up @@ -98,7 +98,10 @@ export class Web3Context<
private _wallet?: Web3BaseWallet<Web3BaseWalletAccount>;

public constructor(
providerOrContext: SupportedProviders<API> | Web3ContextInitOptions<API, RegisteredSubs>,
providerOrContext?:
| SupportedProviders<API>
| Web3ContextInitOptions<API, RegisteredSubs>
| string,
) {
super();
if (
Expand Down Expand Up @@ -230,15 +233,15 @@ export class Web3Context<
return this.requestManager.provider;
}

public set provider(provider: SupportedProviders<API>) {
public set provider(provider: SupportedProviders<API> | string) {
this.requestManager.setProvider(provider);
}

public get currentProvider(): SupportedProviders<API> {
return this.requestManager.provider;
}

public set currentProvider(provider: SupportedProviders<API>) {
public set currentProvider(provider: SupportedProviders<API> | string) {
this.requestManager.setProvider(provider);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/web3-core/src/web3_request_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class Web3RequestManager<
}> {
private _provider!: SupportedProviders<API>;

public constructor(provider?: SupportedProviders<API>, net?: Socket) {
public constructor(provider?: SupportedProviders<API> | string, net?: Socket) {
super();

if (provider) {
Expand All @@ -89,7 +89,7 @@ export class Web3RequestManager<
return availableProviders;
}

public setProvider(provider: SupportedProviders<API>, net?: Socket) {
public setProvider(provider: SupportedProviders<API> | string, net?: Socket) {
let newProvider!: Web3BaseProvider<API>;

// autodetect provider
Expand Down
2 changes: 1 addition & 1 deletion packages/web3-errors/src/web3_error_base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export abstract class Web3Error extends Error {
this.name = this.constructor.name;

if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, new.target.constructor);
Error.captureStackTrace(new.target.constructor);
} else {
this.stack = new Error().stack;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/web3-eth-contract/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ import {
inputAddressFormatter,
inputLogFormatter,
LogsInput,
PromiEvent,
Web3PromiEvent,
Web3EventEmitter,
ReceiptInfo,
} from 'web3-common';
import { Web3Context, Web3ContextObject } from 'web3-core';
import { Web3Context, Web3ContextInitOptions } from 'web3-core';
import {
call,
estimateGas,
Expand Down Expand Up @@ -162,7 +162,7 @@ export class Contract<Abi extends ContractAbi>
address?: Address,
options?: ContractInitOptions,
context?: Partial<
Web3ContextObject<
Web3ContextInitOptions<
EthExecutionAPI,
{
logs: typeof LogsSubscription;
Expand Down Expand Up @@ -368,7 +368,7 @@ export class Contract<Abi extends ContractAbi>
arguments: args,
send: (
options?: PayableTxOptions,
): PromiEvent<Contract<Abi>, SendTransactionEvents> => {
): Web3PromiEvent<Contract<Abi>, SendTransactionEvents> => {
const modifiedOptions = { ...options };

// Remove to address
Expand Down
8 changes: 4 additions & 4 deletions packages/web3-eth-contract/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
DEFAULT_RETURN_FORMAT,
EthExecutionAPI,
FormatType,
PromiEvent,
Web3PromiEvent,
} from 'web3-common';
import { SupportedProviders } from 'web3-core';
import { ContractAbi } from 'web3-eth-abi';
Expand Down Expand Up @@ -61,7 +61,7 @@ export interface ContractInitOptions {
readonly from?: Address;
readonly data?: Bytes;
readonly gasLimit?: Uint;
readonly provider: SupportedProviders<EthExecutionAPI>;
readonly provider: SupportedProviders<EthExecutionAPI> | string;
}

export type TransactionReceipt = ReceiptInfo;
Expand Down Expand Up @@ -91,7 +91,7 @@ export interface NonPayableMethodObject<Inputs = unknown[], Outputs = unknown[]>
call(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise<Outputs>;
send(
tx?: NonPayableTxOptions,
): PromiEvent<FormatType<ReceiptInfo, typeof DEFAULT_RETURN_FORMAT>, SendTransactionEvents>;
): Web3PromiEvent<FormatType<ReceiptInfo, typeof DEFAULT_RETURN_FORMAT>, SendTransactionEvents>;
estimateGas<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
options?: NonPayableCallOptions,
returnFormat?: ReturnFormat,
Expand All @@ -104,7 +104,7 @@ export interface PayableMethodObject<Inputs = unknown[], Outputs = unknown[]> {
call(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise<Outputs>;
send(
tx?: PayableTxOptions,
): PromiEvent<FormatType<ReceiptInfo, typeof DEFAULT_RETURN_FORMAT>, SendTransactionEvents>;
): Web3PromiEvent<FormatType<ReceiptInfo, typeof DEFAULT_RETURN_FORMAT>, SendTransactionEvents>;
estimateGas<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
options?: PayableCallOptions,
returnFormat?: ReturnFormat,
Expand Down
3 changes: 2 additions & 1 deletion packages/web3-eth-ens/src/ens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export class ENS extends Web3Context<EthExecutionAPI & Web3NetAPI> {
registryAddr?: string,
provider?:
| SupportedProviders<EthExecutionAPI & Web3NetAPI>
| Web3ContextObject<EthExecutionAPI & Web3NetAPI>,
| Web3ContextObject<EthExecutionAPI & Web3NetAPI>
| string,
) {
super(provider ?? '');
this.registryAddress = registryAddr ?? registryAddresses.main; // will default to main registry address
Expand Down
4 changes: 2 additions & 2 deletions packages/web3-eth-ens/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ export class Registry {
txConfig: NonPayableCallOptions, // TODO: web3-eth txconfig should be replaced with sendTransaction type
) {
try {
const promievent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig);
const promiEvent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig);

return promievent;
return promiEvent;
} catch (error) {
throw new Error(); // TODO: TransactionRevertError Needs to be added after web3-eth call method is implemented
}
Expand Down
Loading