Skip to content
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how
- [Breaking change: unifying provider interfaces, preparing network providers for extraction - step 2](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/181)
- [Breaking change: unifying provider interfaces, preparing network providers for extraction - step 3](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/182)
- [Breaking change: SmartContract does not depend on IProvider anymore](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/183).
- [Breaking change: unifying provider interfaces, preparing network providers for extraction - step 4](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/184)

**Breaking changes**
- Removed utility functions: `transaction.awaitExecuted()`, `transaction.awaitPending()`. `TransactionWatcher` should be used directly, instead.
Expand Down
5 changes: 2 additions & 3 deletions src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Transaction } from "./transaction";
import { Signature } from "./signature";
import { Query } from "./smartcontracts";
import { QueryResponse } from "./smartcontracts";
import { Token } from "./token";
import BigNumber from "bignumber.js";
import { IAccountOnNetwork, IFungibleTokenOfAccountOnNetwork, INetworkConfig, INetworkStake, INetworkStats, INetworkStatus, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";
import { IAccountOnNetwork, IContractQueryResponse, IFungibleTokenOfAccountOnNetwork, INetworkConfig, INetworkStake, INetworkStats, INetworkStatus, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";

export interface ITransactionFetcher {
/**
Expand Down Expand Up @@ -55,7 +54,7 @@ export interface IProvider extends ITransactionFetcher {
/**
* Queries a Smart Contract - runs a pure function defined by the contract and returns its results.
*/
queryContract(query: Query): Promise<QueryResponse>;
queryContract(query: Query): Promise<IContractQueryResponse>;

/**
* Broadcasts an already-signed {@link Transaction}.
Expand Down
12 changes: 12 additions & 0 deletions src/interfaceOfNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ export interface IContractResultItem {
logs: ITransactionLogs;
}

export interface IContractQueryResponse {
returnCode: IContractReturnCode;
returnMessage: string;
gasUsed: IGasLimit;
getReturnDataParts(): Buffer[];
isSuccess(): boolean;
}

export interface IContractReturnCode {
toString(): string;
}

export interface ITransactionLogs {
events: ITransactionEvent[];

Expand Down
7 changes: 3 additions & 4 deletions src/networkProvider/apiNetworkProvider.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import axios, { AxiosRequestConfig } from "axios";
import { AccountOnNetwork } from "./accounts";
import { IAddress, IContractQueryResponse, IDefinitionOfFungibleTokenOnNetwork, IDefinitionOfTokenCollectionOnNetwork, IFungibleTokenOfAccountOnNetwork, IHash, INetworkProvider, INonce, INonFungibleTokenOfAccountOnNetwork, ITransaction, Pagination } from "./interface";
import { IAddress, IContractQuery, IDefinitionOfFungibleTokenOnNetwork, IDefinitionOfTokenCollectionOnNetwork, IFungibleTokenOfAccountOnNetwork, IHash, INetworkProvider, INonce, INonFungibleTokenOfAccountOnNetwork, ITransaction, Pagination } from "./interface";
import { NetworkConfig } from "./networkConfig";
import { NetworkStake } from "./networkStake";
import { Query } from "../smartcontracts";
import { Stats } from "./stats";
import { ContractQueryResponse } from "./contractResults";
import { ProxyNetworkProvider } from "./proxyNetworkProvider";
import { DefinitionOfFungibleTokenOnNetwork, DefinitionOfTokenCollectionOnNetwork } from "./tokenDefinitions";
import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens";
Expand All @@ -15,6 +13,7 @@ import { Hash } from "./primitives";
import { ErrNetworkProvider } from "./errors";
import { defaultAxiosConfig } from "./config";
import { NetworkStatus } from "./networkStatus";
import { ContractQueryResponse } from "./contractQueryResponse";

// TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider".
export class ApiNetworkProvider implements INetworkProvider {
Expand Down Expand Up @@ -112,7 +111,7 @@ export class ApiNetworkProvider implements INetworkProvider {
return await this.backingProxyNetworkProvider.simulateTransaction(tx);
}

async queryContract(query: Query): Promise<IContractQueryResponse> {
async queryContract(query: IContractQuery): Promise<ContractQueryResponse> {
let data = query.toHttpRequest();
let response = await this.doPostGeneric("query", data);
let queryResponse = ContractQueryResponse.fromHttpResponse(response);
Expand Down
3 changes: 3 additions & 0 deletions src/networkProvider/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import BigNumber from "bignumber.js";

export const MaxUint64AsBigNumber = new BigNumber("18446744073709551615");
Original file line number Diff line number Diff line change
@@ -1,61 +1,43 @@
import { GasLimit } from "../networkParams";
import { MaxUint64 } from "./query";
import { ReturnCode } from "./returnCode";
import BigNumber from "bignumber.js";
import { ErrContract } from "../errors";
import { ArgSerializer } from "./argSerializer";
import { MaxUint64AsBigNumber } from "./constants";
import { IContractReturnCode, IGasLimit } from "./interface";
import { ContractReturnCode } from "./primitives";

export class QueryResponse {
export class ContractQueryResponse {
returnData: string[];
returnCode: ReturnCode;
returnCode: IContractReturnCode;
returnMessage: string;
gasUsed: GasLimit;
gasUsed: IGasLimit;

constructor(init?: Partial<QueryResponse>) {
constructor(init?: Partial<ContractQueryResponse>) {
this.returnData = init?.returnData || [];
this.returnCode = init?.returnCode || ReturnCode.Unknown;
this.returnCode = init?.returnCode || new ContractReturnCode("");
this.returnMessage = init?.returnMessage || "";
this.gasUsed = init?.gasUsed || new GasLimit(0);
this.gasUsed = init?.gasUsed || 0;
}

/**
* Constructs a QueryResponse object from a HTTP response (as returned by the provider).
*/
static fromHttpResponse(payload: any): QueryResponse {
static fromHttpResponse(payload: any): ContractQueryResponse {
let returnData = <string[]>payload["returnData"] || payload["ReturnData"];
let returnCode = payload["returnCode"] || payload["ReturnCode"];
let returnMessage = payload["returnMessage"] || payload["ReturnMessage"];
let gasRemaining = new BigNumber(payload["gasRemaining"] || payload["GasRemaining"] || 0);
let gasUsed = new GasLimit(MaxUint64.minus(gasRemaining).toNumber());
let gasUsed = new Number(MaxUint64AsBigNumber.minus(gasRemaining).toNumber());

return new QueryResponse({
return new ContractQueryResponse({
returnData: returnData,
returnCode: new ReturnCode(returnCode),
returnCode: new ContractReturnCode(returnCode),
returnMessage: returnMessage,
gasUsed: gasUsed,
});
}

getReturnCode(): ReturnCode {
return this.returnCode;
}

getReturnMessage(): string {
return this.returnMessage;
}

getReturnDataParts(): Buffer[] {
return this.returnData.map((item) => Buffer.from(item || "", "base64"));
}

assertSuccess() {
if (this.isSuccess()) {
return;
}

throw new ErrContract(`${this.getReturnCode()}: ${this.getReturnMessage()}`);
}

isSuccess(): boolean {
return this.returnCode.isSuccess();
}
Expand Down
29 changes: 2 additions & 27 deletions src/networkProvider/contractResults.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { BigNumber } from "bignumber.js";
import { IAddress, IContractQueryResponse, IContractReturnCode, IGasLimit, IGasPrice, IHash, INonce } from "./interface";
import { IAddress, IGasLimit, IGasPrice, IHash, INonce } from "./interface";
import { TransactionLogs } from "./transactionLogs";
import { MaxUint64 } from "../smartcontracts/query";
import { Address, ContractReturnCode, Hash, Nonce, TransactionValue } from "./primitives";
import { Address, Hash, Nonce, TransactionValue } from "./primitives";

export class ContractResults {
readonly items: ContractResultItem[];
Expand Down Expand Up @@ -84,26 +82,3 @@ export class ContractResultItem {
return item;
}
}

export class ContractQueryResponse implements IContractQueryResponse {
returnData: string[] = [];
returnCode: IContractReturnCode = new ContractReturnCode("");
returnMessage: string = "";
gasUsed: IGasLimit = 0;

static fromHttpResponse(payload: any): ContractQueryResponse {
let response = new ContractQueryResponse();
let gasRemaining = new BigNumber(payload["gasRemaining"] || payload["GasRemaining"] || 0);

response.returnData = payload["returnData"] || [];
response.returnCode = new ContractReturnCode(payload["returnCode"] || "");
response.returnMessage = payload["returnMessage"] || "";
response.gasUsed = MaxUint64.minus(gasRemaining).toNumber();

return response;
}

getReturnDataParts(): Buffer[] {
return this.returnData.map((item) => Buffer.from(item || ""));
}
}
14 changes: 5 additions & 9 deletions src/networkProvider/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { BigNumber } from "bignumber.js";
import { AccountOnNetwork } from "./accounts";
import { NetworkConfig } from "./networkConfig";
import { NetworkStake } from "./networkStake";
import { Query } from "../smartcontracts";
import { Stats } from "./stats";
import { TransactionOnNetwork } from "./transactions";
import { TransactionStatus } from "./transactionStatus";
import { NetworkStatus } from "./networkStatus";
import { ContractQueryResponse } from "./contractQueryResponse";

/**
* An interface that defines the endpoints of an HTTP API Provider.
Expand Down Expand Up @@ -81,7 +81,7 @@ export interface INetworkProvider {
/**
* Queries a Smart Contract - runs a pure function defined by the contract and returns its results.
*/
queryContract(query: Query): Promise<IContractQueryResponse>;
queryContract(query: IContractQuery): Promise<ContractQueryResponse>;

/**
* Fetches the definition of a fungible token.
Expand Down Expand Up @@ -159,17 +159,13 @@ export interface IDefinitionOfTokenCollectionOnNetwork {
// TODO: add "assets", "roles"
}

export interface IContractQueryResponse {
returnData: string[];
returnCode: IContractReturnCode;
returnMessage: string;
gasUsed: IGasLimit;

getReturnDataParts(): Buffer[];
export interface IContractQuery {
toHttpRequest(): any;
}

export interface IContractReturnCode {
toString(): string;
isSuccess(): boolean;
}

export interface IContractSimulation {
Expand Down
6 changes: 6 additions & 0 deletions src/networkProvider/primitives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ export class TransactionPayload implements ITransactionPayload {
}

export class ContractReturnCode {
private static OK: string = "ok";

private readonly value: string;

constructor(value: string) {
Expand All @@ -78,6 +80,10 @@ export class ContractReturnCode {
toString() {
return this.value;
}

isSuccess(): boolean {
return this.value == ContractReturnCode.OK;
}
}

export class AccountBalance {
Expand Down
7 changes: 3 additions & 4 deletions src/networkProvider/proxyNetworkProvider.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import axios, { AxiosRequestConfig } from "axios";
import { AccountOnNetwork } from "./accounts";
import { IAddress, IContractQueryResponse, IDefinitionOfFungibleTokenOnNetwork, IDefinitionOfTokenCollectionOnNetwork, IFungibleTokenOfAccountOnNetwork, IHash, INetworkProvider, INonce, INonFungibleTokenOfAccountOnNetwork, ITransaction, Pagination } from "./interface";
import { IAddress, IContractQuery, IDefinitionOfFungibleTokenOnNetwork, IDefinitionOfTokenCollectionOnNetwork, IFungibleTokenOfAccountOnNetwork, IHash, INetworkProvider, INonce, INonFungibleTokenOfAccountOnNetwork, ITransaction, Pagination } from "./interface";
import { NetworkConfig } from "./networkConfig";
import { NetworkStake } from "./networkStake";
import { Query } from "../smartcontracts";
import { Stats } from "./stats";
import { ContractQueryResponse } from "./contractResults";
import { FungibleTokenOfAccountOnNetwork, NonFungibleTokenOfAccountOnNetwork } from "./tokens";
import { TransactionOnNetwork } from "./transactions";
import { TransactionStatus } from "./transactionStatus";
import { Hash } from "./primitives";
import { ErrNetworkProvider } from "./errors";
import { defaultAxiosConfig } from "./config";
import { NetworkStatus } from "./networkStatus";
import { ContractQueryResponse } from "./contractQueryResponse";

// TODO: Find & remove duplicate code between "ProxyNetworkProvider" and "ApiNetworkProvider".
export class ProxyNetworkProvider implements INetworkProvider {
Expand Down Expand Up @@ -116,7 +115,7 @@ export class ProxyNetworkProvider implements INetworkProvider {
return response;
}

async queryContract(query: Query): Promise<IContractQueryResponse> {
async queryContract(query: IContractQuery): Promise<ContractQueryResponse> {
let data = query.toHttpRequest();
let response = await this.doPostGeneric("vm-values/query", data);
let queryResponse = ContractQueryResponse.fromHttpResponse(response.data);
Expand Down
26 changes: 7 additions & 19 deletions src/proxyProvider.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import axios, { AxiosRequestConfig } from "axios";
import BigNumber from "bignumber.js";

import { IProvider } from "./interface";
import { IHash, IProvider } from "./interface";
import { Transaction, TransactionHash } from "./transaction";
import { Address } from "./address";
import * as errors from "./errors";
import { Query } from "./smartcontracts/query";
import { QueryResponse } from "./smartcontracts/queryResponse";
import { Logger } from "./logger";
import { defaultConfig } from "./constants";
import { ProxyNetworkProvider } from "./networkProvider/proxyNetworkProvider";
import { IAccountOnNetwork, IFungibleTokenOfAccountOnNetwork, INetworkConfig, INetworkStatus, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";
import { IAccountOnNetwork, IContractQueryResponse, IFungibleTokenOfAccountOnNetwork, INetworkConfig, INetworkStatus, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork";

export class ProxyProvider implements IProvider {
private url: string;
Expand Down Expand Up @@ -57,33 +56,22 @@ export class ProxyProvider implements IProvider {
/**
* Queries a Smart Contract - runs a pure function defined by the contract and returns its results.
*/
async queryContract(query: Query): Promise<QueryResponse> {
try {
let data = query.toHttpRequest();
return this.doPostGeneric("vm-values/query", data, (response) =>
QueryResponse.fromHttpResponse(response.data || response.vmOutput)
);
} catch (err: any) {
throw errors.ErrContractQuery.increaseSpecificity(err);
}
async queryContract(query: Query): Promise<IContractQueryResponse> {
return await this.backingProvider.queryContract(query);
}

/**
* Broadcasts an already-signed {@link Transaction}.
*/
async sendTransaction(tx: Transaction): Promise<TransactionHash> {
return this.doPostGeneric(
"transaction/send",
tx.toSendable(),
(response) => new TransactionHash(response.txHash)
);
async sendTransaction(tx: Transaction): Promise<IHash> {
return await this.backingProvider.sendTransaction(tx);
}

/**
* Simulates the processing of an already-signed {@link Transaction}.
*/
async simulateTransaction(tx: Transaction): Promise<any> {
return this.doPostGeneric("transaction/simulate", tx.toSendable(), (response) => response);
return await this.backingProvider.simulateTransaction(tx);
}

/**
Expand Down
1 change: 0 additions & 1 deletion src/smartcontracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export * from "./interactionChecker";
export * from "./interface";
export * from "./nativeSerializer";
export * from "./query";
export * from "./queryResponse";
export * from "./resultsParser";
export * from "./returnCode";
export * from "./smartContract";
Expand Down
6 changes: 3 additions & 3 deletions src/smartcontracts/interaction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { assert } from "chai";
import { Interaction } from "./interaction";
import { ChainID, GasLimit } from "../networkParams";
import { ContractFunction } from "./function";
import { QueryResponse } from "./queryResponse";
import { ContractQueryResponse } from "../networkProvider/contractQueryResponse";
import { Nonce } from "../nonce";
import { ReturnCode } from "./returnCode";
import { Balance } from "../balance";
Expand Down Expand Up @@ -126,7 +126,7 @@ describe("test smart contract interactor", function() {

provider.mockQueryContractOnFunction(
"getUltimateAnswer",
new QueryResponse({ returnData: ["Kg=="], returnCode: ReturnCode.Ok })
new ContractQueryResponse({ returnData: ["Kg=="], returnCode: ReturnCode.Ok })
);

// Query
Expand Down Expand Up @@ -183,7 +183,7 @@ describe("test smart contract interactor", function() {
// For "get()", return fake 7
provider.mockQueryContractOnFunction(
"get",
new QueryResponse({ returnData: ["Bw=="], returnCode: ReturnCode.Ok })
new ContractQueryResponse({ returnData: ["Bw=="], returnCode: ReturnCode.Ok })
);

// Query "get()"
Expand Down
Loading