Skip to content

Commit

Permalink
refactor: remove config from manager
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasbrugneaux committed Sep 16, 2024
1 parent 1f8d416 commit 125bf12
Show file tree
Hide file tree
Showing 16 changed files with 44 additions and 52 deletions.
1 change: 0 additions & 1 deletion packages/web3-core/src/web3_batch_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
import { JsonRpcBatchResponse, JsonRpcOptionalRequest, JsonRpcRequest } from 'web3-types';
import { jsonRpc, Web3DeferredPromise } from 'web3-utils';
import { OperationAbortError, OperationTimeoutError, ResponseError } from 'web3-errors';
// eslint-disable-next-line import/no-cycle
import { Web3RequestManager } from './web3_request_manager.js';

export const DEFAULT_BATCH_REQUEST_TIMEOUT = 1000;
Expand Down
8 changes: 4 additions & 4 deletions packages/web3-core/src/web3_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
} from 'web3-types';
import { ConfigHardforkMismatchError, ConfigChainMismatchError } from 'web3-errors';
import { isNullish, toHex } from 'web3-utils';
import { ValidationSchemaInput } from 'web3-validator';
import { Schema } from 'web3-validator';
import { TransactionTypeParser } from './types.js';
// eslint-disable-next-line import/no-cycle
import { TransactionBuilder } from './web3_context.js';
Expand Down Expand Up @@ -60,7 +60,7 @@ export interface Web3ConfigOptions {
};
transactionBuilder?: TransactionBuilder;
transactionTypeParser?: TransactionTypeParser;
customTransactionSchema?: ValidationSchemaInput;
customTransactionSchema?: Record<string, Schema>;
defaultReturnFormat: DataFormat;
}

Expand Down Expand Up @@ -523,11 +523,11 @@ export abstract class Web3Config
this.config.transactionTypeParser = val;
}

public get customTransactionSchema(): ValidationSchemaInput | undefined {
public get customTransactionSchema(): Record<string, Schema> | undefined {
return this.config.customTransactionSchema;
}

public set customTransactionSchema(schema: ValidationSchemaInput | undefined) {
public set customTransactionSchema(schema: Record<string, Schema> | undefined) {
this._triggerConfigChange('customTransactionSchema', schema);
this.config.customTransactionSchema = schema;
}
Expand Down
6 changes: 0 additions & 6 deletions packages/web3-core/src/web3_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import { ExtensionObject, RequestManagerMiddleware } from './types.js';
import { Web3BatchRequest } from './web3_batch_request.js';
// eslint-disable-next-line import/no-cycle
import { Web3Config, Web3ConfigEvent, Web3ConfigOptions } from './web3_config.js';
// eslint-disable-next-line import/no-cycle
import { Web3RequestManager } from './web3_request_manager.js';
import { Web3SubscriptionConstructor } from './web3_subscriptions.js';
import { Web3SubscriptionManager } from './web3_subscription_manager.js';
Expand Down Expand Up @@ -149,7 +148,6 @@ export class Web3Context<
provider,
config?.enableExperimentalFeatures?.useSubscriptionWhenCheckingBlockTimeout,
requestManagerMiddleware,
config,
);

if (subscriptionManager) {
Expand Down Expand Up @@ -226,8 +224,6 @@ export class Web3Context<
this.on(Web3ConfigEvent.CONFIG_CHANGE, event => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
newContextChild.setConfig({ [event.name]: event.newValue });
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this._requestManager.setConfig({ [event.name]: event.newValue });
});

// @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context<API, RegisteredSubs>'
Expand All @@ -251,8 +247,6 @@ export class Web3Context<
parentContext.on(Web3ConfigEvent.CONFIG_CHANGE, event => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.setConfig({ [event.name]: event.newValue });
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this._requestManager.setConfig({ [event.name]: event.newValue });
});
}

Expand Down
9 changes: 0 additions & 9 deletions packages/web3-core/src/web3_request_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ import {
} from './utils.js';
import { Web3EventEmitter } from './web3_event_emitter.js';
import { RequestManagerMiddleware } from './types.js';
import { type Web3ConfigOptions } from './web3_config.js';

export enum Web3RequestManagerEvent {
PROVIDER_CHANGED = 'PROVIDER_CHANGED',
Expand All @@ -75,19 +74,15 @@ export class Web3RequestManager<
}> {
private _provider?: SupportedProviders<API>;
private readonly useRpcCallSpecification?: boolean;
public config: Partial<Web3ConfigOptions>;
public middleware?: RequestManagerMiddleware<API>;

public constructor(
provider?: SupportedProviders<API> | string,
useRpcCallSpecification?: boolean,
requestManagerMiddleware?: RequestManagerMiddleware<API>,
config?: Partial<Web3ConfigOptions>,
) {
super();

this.config = config ?? {};

if (!isNullish(provider)) {
this.setProvider(provider);
}
Expand Down Expand Up @@ -153,10 +148,6 @@ export class Web3RequestManager<
return true;
}

public setConfig(options: Partial<Web3ConfigOptions>) {
Object.assign(this.config, options);
}

public setMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>) {
this.middleware = requestManagerMiddleware;
}
Expand Down
1 change: 0 additions & 1 deletion packages/web3-core/src/web3_subscription_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
import { ProviderError, SubscriptionError } from 'web3-errors';
import { isNullish } from 'web3-utils';
import { isSupportSubscriptions } from './utils.js';
// eslint-disable-next-line import/no-cycle
import { Web3RequestManager, Web3RequestManagerEvent } from './web3_request_manager.js';
// eslint-disable-next-line import/no-cycle
import { Web3SubscriptionConstructor } from './web3_subscriptions.js';
Expand Down
1 change: 0 additions & 1 deletion packages/web3-core/src/web3_subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import { jsonRpc } from 'web3-utils';
// eslint-disable-next-line import/no-cycle
import { Web3SubscriptionManager } from './web3_subscription_manager.js';
import { Web3EventEmitter, Web3EventMap } from './web3_event_emitter.js';
// eslint-disable-next-line import/no-cycle
import { Web3RequestManager } from './web3_request_manager.js';

type CommonSubscriptionEvents = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ exports[`Web3Context getContextObject should return correct context object 1`] =
"clientUrl": "http://test/abc",
"httpProviderOptions": undefined,
},
"config": {},
"useRpcCallSpecification": undefined,
},
"subscriptionManager": Web3SubscriptionManager {
Expand Down Expand Up @@ -110,7 +109,6 @@ exports[`Web3Context getContextObject should return correct context object 1`] =
"clientUrl": "http://test/abc",
"httpProviderOptions": undefined,
},
"config": {},
"useRpcCallSpecification": undefined,
},
"tolerateUnlinkedSubscription": false,
Expand Down
4 changes: 2 additions & 2 deletions packages/web3-eth-personal/src/personal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export class Personal extends Web3Context<EthPersonalAPI> {
* ```
*/
public async sendTransaction(tx: Transaction, passphrase: string) {
return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase);
return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase, this.config);
}
/**
* Signs a transaction. This account needs to be unlocked.
Expand Down Expand Up @@ -204,7 +204,7 @@ export class Personal extends Web3Context<EthPersonalAPI> {
* ```
*/
public async signTransaction(tx: Transaction, passphrase: string) {
return rpcWrappers.signTransaction(this.requestManager, tx, passphrase);
return rpcWrappers.signTransaction(this.requestManager, tx, passphrase, this.config);
}
/**
* Calculates an Ethereum specific signature with:
Expand Down
10 changes: 6 additions & 4 deletions packages/web3-eth-personal/src/rpc_method_wrappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ 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 { Web3RequestManager } from 'web3-core';
import { Web3RequestManager, Web3ConfigOptions } from 'web3-core';
import { toChecksumAddress, utf8ToHex } from 'web3-utils';
import { formatTransaction } from 'web3-eth';
import { formatTransaction, type CustomTransactionSchema } from 'web3-eth';
import { Address, EthPersonalAPI, ETH_DATA_FORMAT, HexString, Transaction } from 'web3-types';
import { validator, isHexStrict } from 'web3-validator';
import { personalRpcMethods } from 'web3-rpc-methods';
Expand Down Expand Up @@ -72,9 +72,10 @@ export const sendTransaction = async (
requestManager: Web3RequestManager<EthPersonalAPI>,
tx: Transaction,
passphrase: string,
config?: Web3ConfigOptions,
) => {
const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT, {
transactionSchema: requestManager.config.customTransactionSchema,
transactionSchema: config?.customTransactionSchema as CustomTransactionSchema,
});

return personalRpcMethods.sendTransaction(requestManager, formattedTx, passphrase);
Expand All @@ -84,9 +85,10 @@ export const signTransaction = async (
requestManager: Web3RequestManager<EthPersonalAPI>,
tx: Transaction,
passphrase: string,
config?: Web3ConfigOptions,
) => {
const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT, {
transactionSchema: requestManager.config.customTransactionSchema,
transactionSchema: config?.customTransactionSchema as CustomTransactionSchema,
});

return personalRpcMethods.signTransaction(requestManager, formattedTx, passphrase);
Expand Down
13 changes: 7 additions & 6 deletions packages/web3-eth/src/rpc_method_wrappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
SignatureObjectSchema,
} from './schemas.js';
import {
type CustomTransactionSchema,
SendSignedTransactionEvents,
SendSignedTransactionOptions,
SendTransactionEvents,
Expand Down Expand Up @@ -429,7 +430,7 @@ export async function getTransaction<ReturnFormat extends DataFormat>(
return isNullish(response)
? response
: formatTransaction(response, returnFormat, {
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
fillInputAndData: true,
});
}
Expand All @@ -449,7 +450,7 @@ export async function getPendingTransactions<ReturnFormat extends DataFormat>(
transaction as unknown as Transaction,
returnFormat ?? web3Context.defaultReturnFormat,
{
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
fillInputAndData: true,
},
),
Expand Down Expand Up @@ -490,7 +491,7 @@ export async function getTransactionFromBlock<ReturnFormat extends DataFormat>(
return isNullish(response)
? response
: formatTransaction(response, returnFormat ?? web3Context.defaultReturnFormat, {
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
fillInputAndData: true,
});
}
Expand Down Expand Up @@ -610,7 +611,7 @@ export function sendTransaction<
},
ETH_DATA_FORMAT,
{
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
},
);

Expand Down Expand Up @@ -854,7 +855,7 @@ export async function signTransaction<ReturnFormat extends DataFormat>(
const response = await ethRpcMethods.signTransaction(
web3Context.requestManager,
formatTransaction(transaction, ETH_DATA_FORMAT, {
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
}),
);
// Some clients only return the encoded signed transaction (e.g. Ganache)
Expand All @@ -870,7 +871,7 @@ export async function signTransaction<ReturnFormat extends DataFormat>(
returnFormat,
),
tx: formatTransaction((response as SignedTransactionInfoAPI).tx, returnFormat, {
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
fillInputAndData: true,
}),
};
Expand Down
7 changes: 7 additions & 0 deletions packages/web3-eth/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import {
TransactionWithFromLocalWalletIndex,
TransactionWithToLocalWalletIndex,
} from 'web3-types';
import { Schema } from 'web3-validator';
import { transactionSchema } from './schemas.js';

export type InternalTransaction = FormatType<Transaction, typeof ETH_DATA_FORMAT>;

Expand Down Expand Up @@ -105,3 +107,8 @@ export interface TransactionMiddleware {
options?: { [key: string]: unknown },
): Promise<TransactionMiddlewareData>;
}

export type CustomTransactionSchema = {
type: string;
properties: typeof transactionSchema['properties'] & Record<string, Schema>;
};
4 changes: 2 additions & 2 deletions packages/web3-eth/src/utils/decode_signed_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import {
} from 'web3-types';
import { bytesToHex, format, hexToBytes, keccak256 } from 'web3-utils';
import { TransactionFactory } from 'web3-eth-accounts';
import { ValidationSchemaInput } from 'web3-validator';
import { detectRawTransactionType } from './detect_transaction_type.js';
import { formatTransaction } from './format_transaction.js';
import { type CustomTransactionSchema } from '../types.js';

/**
* Decodes an [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/#top) encoded transaction.
Expand All @@ -36,7 +36,7 @@ import { formatTransaction } from './format_transaction.js';
export function decodeSignedTransaction<ReturnFormat extends DataFormat>(
encodedSignedTransaction: HexStringBytes,
returnFormat: ReturnFormat,
options: { fillInputAndData?: boolean; transactionSchema?: ValidationSchemaInput } = {
options: { fillInputAndData?: boolean; transactionSchema?: CustomTransactionSchema } = {
fillInputAndData: false,
},
): SignedTransactionInfoAPI {
Expand Down
12 changes: 4 additions & 8 deletions packages/web3-eth/src/utils/format_transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,12 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { Transaction, DataFormat, DEFAULT_RETURN_FORMAT, FormatType } from 'web3-types';
import { isNullish, ValidationSchemaInput, Schema } from 'web3-validator';
import { isNullish, ValidationSchemaInput } from 'web3-validator';
import { mergeDeep, format, bytesToHex, toHex } from 'web3-utils';
import { TransactionDataAndInputError } from 'web3-errors';

import { transactionInfoSchema, transactionSchema } from '../schemas.js';

type TransactionSchema = {
type: string;
properties: typeof transactionSchema['properties'] & Record<string, Schema>;
};
import { transactionInfoSchema } from '../schemas.js';
import { type CustomTransactionSchema } from '../types.js';

export function formatTransaction<
ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT,
Expand All @@ -34,7 +30,7 @@ export function formatTransaction<
transaction: TransactionType,
returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
options: {
transactionSchema?: ValidationSchemaInput | TransactionSchema | undefined;
transactionSchema?: ValidationSchemaInput | CustomTransactionSchema | undefined;
fillInputAndData?: boolean;
} = {
transactionSchema: transactionInfoSchema,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { isNullish } from 'web3-validator';
import { validateTransactionForSigning } from '../validation.js';
import { formatTransaction } from './format_transaction.js';
import { transactionBuilder } from './transaction_builder.js';
import { type CustomTransactionSchema } from '../types.js';

const getEthereumjsTxDataFromTransaction = (
transaction: FormatType<PopulatedUnsignedTransaction, typeof ETH_DATA_FORMAT>,
Expand Down Expand Up @@ -135,14 +136,15 @@ export const prepareTransactionForSigning = async (
fillGasLimit,
})) as unknown as PopulatedUnsignedTransaction;
const formattedTransaction = formatTransaction(populatedTransaction, ETH_DATA_FORMAT, {
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config.customTransactionSchema as CustomTransactionSchema,
}) as unknown as FormatType<PopulatedUnsignedTransaction, typeof ETH_DATA_FORMAT>;

validateTransactionForSigning(
formattedTransaction as unknown as FormatType<Transaction, typeof ETH_DATA_FORMAT>,
undefined,
{
transactionSchema: web3Context.config.customTransactionSchema,
transactionSchema: web3Context.config
.customTransactionSchema as CustomTransactionSchema,
},
);

Expand Down
4 changes: 2 additions & 2 deletions packages/web3-eth/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import {
UnsupportedFeeMarketError,
} from 'web3-errors';
import { formatTransaction } from './utils/format_transaction.js';
import { InternalTransaction } from './types.js';
import { CustomTransactionSchema, InternalTransaction } from './types.js';

export function isBaseTransaction(value: BaseTransactionAPI): boolean {
if (!isNullish(value.to) && !isAddress(value.to)) return false;
Expand Down Expand Up @@ -290,7 +290,7 @@ export const validateTransactionForSigning = (
transaction: InternalTransaction,
overrideMethod?: (transaction: InternalTransaction) => void,
options: {
transactionSchema?: ValidationSchemaInput;
transactionSchema?: CustomTransactionSchema;
} = { transactionSchema: undefined },
) => {
if (!isNullish(overrideMethod)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import { ethRpcMethods } from 'web3-rpc-methods';

import { getTransaction } from '../../../src/rpc_method_wrappers';
import { mockRpcResponse, testData } from './fixtures/get_transaction';
import { formatTransaction, transactionInfoSchema } from '../../../src';
import {
type CustomTransactionSchema,
formatTransaction,
transactionInfoSchema,
} from '../../../src';

jest.mock('web3-rpc-methods');

Expand Down Expand Up @@ -57,7 +61,7 @@ describe('getTransaction', () => {
const expectedFormattedResult = formatTransaction(
mockRpcResponse,
expectedReturnFormat,
{ transactionSchema: transactionInfoSchema },
{ transactionSchema: transactionInfoSchema as CustomTransactionSchema },
);
(ethRpcMethods.getTransactionByHash as jest.Mock).mockResolvedValueOnce(
mockRpcResponse,
Expand Down

0 comments on commit 125bf12

Please sign in to comment.