Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Breaking change: unifying provider interfaces, preparing network providers for extraction - step 1 #180

Merged
merged 14 commits into from
Apr 6, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 12 additions & 11 deletions src/apiProvider.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import axios, { AxiosRequestConfig } from "axios";
import { IApiProvider } from "./interface";
import { IApiProvider, IHash } from "./interface";
import * as errors from "./errors";
import { Logger } from "./logger";
import { NetworkStake } from "./networkStake";
import { Stats } from "./stats";
import { TransactionHash, TransactionStatus } from "./transaction";
import { TransactionOnNetwork } from "./transactionOnNetwork";
import { Token } from "./token";
import { NFTToken } from "./nftToken";
import { defaultConfig } from "./constants";
import { ApiNetworkProvider } from "./networkProvider/apiNetworkProvider";
import { ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";

/**
* This is a temporary change, this will be the only provider used, ProxyProvider will be deprecated
*/
export class ApiProvider implements IApiProvider {
private url: string;
private config: AxiosRequestConfig;
/**
* @deprecated used only for preparatory refactoring (unifying network providers)
*/
private readonly backingProvider: ApiNetworkProvider;

/**
* Creates a new ApiProvider.
Expand All @@ -25,6 +29,7 @@ export class ApiProvider implements IApiProvider {
constructor(url: string, config?: AxiosRequestConfig) {
this.url = url;
this.config = {...defaultConfig, ...config};
this.backingProvider = new ApiNetworkProvider(url, config);
}

/**
Expand All @@ -44,19 +49,15 @@ export class ApiProvider implements IApiProvider {
/**
* Fetches the state of a {@link Transaction}.
*/
async getTransaction(txHash: TransactionHash): Promise<TransactionOnNetwork> {
return this.doGetGeneric(`transactions/${txHash.toString()}`, (response) =>
TransactionOnNetwork.fromHttpResponse(txHash, response)
);
async getTransaction(txHash: IHash): Promise<ITransactionOnNetwork> {
return await this.backingProvider.getTransaction(txHash);
}

/**
* Queries the status of a {@link Transaction}.
*/
async getTransactionStatus(txHash: TransactionHash): Promise<TransactionStatus> {
return this.doGetGeneric(`transactions/${txHash.toString()}?fields=status`, (response) =>
new TransactionStatus(response.status)
);
async getTransactionStatus(txHash: IHash): Promise<ITransactionStatus> {
return await this.backingProvider.getTransactionStatus(txHash);
}

async getToken(tokenIdentifier: string): Promise<Token> {
Expand Down
6 changes: 3 additions & 3 deletions src/boundaryAdapters.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Address } from "./address";
import { ErrInvariantFailed } from "./errors";
import { IAddressOfExternalSigner, ISignatureOfExternalSigner } from "./interface";
import { IBech32Address, ISignature } from "./interface";
import { Signature } from "./signature";

/**
* Adapts a signature created by other components (e.g. erdjs-walletcore, erdjs-hw-provider) to one understood by erdjs.
*/
export function adaptToSignature(obj: ISignatureOfExternalSigner): Signature {
export function adaptToSignature(obj: ISignature): Signature {
if (!obj.hex || typeof obj.hex() !== "string") {
throw new ErrInvariantFailed("adaptToSignature: bad or missing hex()")
}
Expand All @@ -17,7 +17,7 @@ export function adaptToSignature(obj: ISignatureOfExternalSigner): Signature {
/**
* Adapts an address created by other components (e.g. erdjs-walletcore, erdjs-hw-provider) to one understood by erdjs.
*/
export function adaptToAddress(obj: IAddressOfExternalSigner): Address {
export function adaptToAddress(obj: IBech32Address): Address {
if (!obj.bech32 || typeof obj.bech32() !== "string") {
throw new ErrInvariantFailed("adaptToSignature: bad or missing bech32()")
}
Expand Down
12 changes: 1 addition & 11 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export class ErrInvariantFailed extends Err {
/**
* Signals an unexpected condition.
*/
export class ErrUnexpectedCondition extends Err {
export class ErrUnexpectedCondition extends Err {
public constructor(message: string) {
super(`Unexpected condition: [${message}]`);
}
Expand Down Expand Up @@ -272,16 +272,6 @@ export class ErrInvalidFunctionName extends Err {
}
}

/**
* Signals an error that happened during a request against the Network.
*/
export class ErrNetworkProvider extends Err {
public constructor(url: string, error: string, inner?: Error) {
let message = `Request error on url [${url}]: [${error}]`;
super(message, inner);
}
}

/**
* Signals an error that happened during a HTTP GET request.
*/
Expand Down
4 changes: 4 additions & 0 deletions src/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ export class Hash {
}

toString(): string {
return this.hex();
}

hex(): string {
return this.hash.toString("hex");
}

Expand Down
51 changes: 19 additions & 32 deletions src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
import { Transaction, TransactionHash, TransactionStatus } from "./transaction";
import { Transaction } from "./transaction";
import { NetworkConfig } from "./networkConfig";
import { Signature } from "./signature";
import { Address } from "./address";
import { AccountOnNetwork, TokenOfAccountOnNetwork } from "./account";
import { Query } from "./smartcontracts";
import { QueryResponse } from "./smartcontracts";
import { NetworkStake } from "./networkStake";
import { Stats } from "./stats";
import { NetworkStatus } from "./networkStatus";
import { TransactionOnNetwork } from "./transactionOnNetwork";
import { Token } from "./token";
import BigNumber from "bignumber.js";
import { ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";

/**
* @deprecated This interface will be removed in a future release, upon merging {@link IProvider} and {@link IApiProvider}.
*/
export interface ITransactionFetcher {
/**
* Fetches the state of a {@link Transaction}.
*/
getTransaction(txHash: TransactionHash, hintSender?: Address, withResults?: boolean): Promise<TransactionOnNetwork>;
getTransaction(txHash: IHash, hintSender?: IBech32Address, withResults?: boolean): Promise<ITransactionOnNetwork>;

/**
* Queries the status of a {@link Transaction}.
*/
getTransactionStatus(txHash: TransactionHash): Promise<TransactionStatus>;
getTransactionStatus(txHash: IHash): Promise<ITransactionStatus>;
}

/**
Expand All @@ -44,22 +40,22 @@ export interface IProvider extends ITransactionFetcher {
/**
* Fetches the state of an {@link Account}.
*/
getAccount(address: Address): Promise<AccountOnNetwork>;
getAccount(address: IBech32Address): Promise<AccountOnNetwork>;

/**
* Fetches the list of ESDT data for all the tokens of an address.
*/
getAddressEsdtList(address: Address): Promise<TokenOfAccountOnNetwork[]>;
getAddressEsdtList(address: IBech32Address): Promise<TokenOfAccountOnNetwork[]>;

/**
* Fetches the ESDT data for a token of an address.
*/
getAddressEsdt(address: Address, tokenIdentifier: string): Promise<any>;
getAddressEsdt(address: IBech32Address, tokenIdentifier: string): Promise<any>;

/**
* Fetches the NFT data for a token with a given nonce of an address.
*/
getAddressNft(address: Address, tokenIdentifier: string, nonce: BigNumber): Promise<any>;
getAddressNft(address: IBech32Address, tokenIdentifier: string, nonce: BigNumber): Promise<any>;

/**
* Queries a Smart Contract - runs a pure function defined by the contract and returns its results.
Expand All @@ -69,12 +65,12 @@ export interface IProvider extends ITransactionFetcher {
/**
* Broadcasts an already-signed {@link Transaction}.
*/
sendTransaction(tx: Transaction): Promise<TransactionHash>;
sendTransaction(tx: Transaction): Promise<IHash>;

/**
* Simulates the processing of an already-signed {@link Transaction}.
*/
simulateTransaction(tx: Transaction): Promise<TransactionHash>;
simulateTransaction(tx: Transaction): Promise<IHash>;

/**
* Get method that receives the resource url and on callback the method used to map the response.
Expand Down Expand Up @@ -115,15 +111,15 @@ export interface ISignable {
/**
* Returns the signable object in its raw form - a sequence of bytes to be signed.
*/
serializeForSigning(signedBy: IAddressOfExternalSigner): Buffer;
serializeForSigning(signedBy: IBech32Address): Buffer;

/**
* Applies the computed signature on the object itself.
*
* @param signature The computed signature
* @param signedBy The address of the signer
*/
applySignature(signature: ISignatureOfExternalSigner, signedBy: IAddressOfExternalSigner): void;
applySignature(signature: ISignature, signedBy: IBech32Address): void;
}

/**
Expand All @@ -137,7 +133,7 @@ export interface IVerifiable {
/**
* Returns the signable object in its raw form - a sequence of bytes to be verified.
*/
serializeForSigning(signedBy?: Address): Buffer;
serializeForSigning(signedBy?: IBech32Address): Buffer;
}

/**
Expand All @@ -147,18 +143,9 @@ export interface Disposable {
dispose(): void;
}

/**
* An interface that defines the signature, as computed by an external (to erdjs) signer.
* Implementations are outside of erdjs.
*/
export interface ISignatureOfExternalSigner {
hex(): string;
}

/**
* An interface that defines the address of an external (to erdjs) signer.
* Implementations are outside of erdjs.
*/
export interface IAddressOfExternalSigner {
bech32(): string;
}
export interface ISignature { hex(): string; }
export interface IHash { hex(): string; }
export interface IBech32Address { bech32(): string; }
export interface ITransactionValue { toString(): string; }
export interface ITransactionPayload { encoded(): string; }
export interface INonce { valueOf(): number; }
65 changes: 65 additions & 0 deletions src/interfaceOfNetwork.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { IBech32Address, IHash, INonce, ITransactionPayload, ITransactionValue } from "./interface";

export interface ITransactionOnNetwork {
hash: IHash;
type: string;
value: ITransactionValue;
receiver: IBech32Address;
sender: IBech32Address;
data: ITransactionPayload;
status: ITransactionStatus;
receipt: ITransactionReceipt;
contractResults: IContractResults;
logs: ITransactionLogs;

isCompleted(): boolean;
getAllEvents(): ITransactionEvent[];
}

export interface ITransactionStatus {
isPending(): boolean;
isFailed(): boolean;
isInvalid(): boolean;
isExecuted(): boolean;
}

export interface ITransactionReceipt {
data: string;
}

export interface IContractResults {
items: IContractResultItem[];
}

export interface IContractResultItem {
hash: IHash;
nonce: INonce;
receiver: IBech32Address;
sender: IBech32Address;
data: string;
returnMessage: string;
logs: ITransactionLogs;
}

export interface ITransactionLogs {
events: ITransactionEvent[];

findSingleOrNoneEvent(identifier: string, predicate?: (event: ITransactionEvent) => boolean): ITransactionEvent | undefined;
findFirstOrNoneEvent(identifier: string, predicate?: (event: ITransactionEvent) => boolean): ITransactionEvent | undefined;
findEvents(identifier: string, predicate?: (event: ITransactionEvent) => boolean): ITransactionEvent[];
}

export interface ITransactionEvent {
readonly address: IBech32Address;
readonly identifier: string;
readonly topics: ITransactionEventTopic[];
readonly data: string;

findFirstOrNoneTopic(predicate: (topic: ITransactionEventTopic) => boolean): ITransactionEventTopic | undefined;
getLastTopic(): ITransactionEventTopic;
}

export interface ITransactionEventTopic {
toString(): string;
hex(): string;
}
Loading