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

Contract wrapper #9

Merged
merged 12 commits into from
Aug 9, 2021
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how

## [Unreleased]

- [Contract wrapper](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/9)
- Added `ContractWrapper`, `SystemWrapper` - for more details check the pull request.
- Added support for constructors in ABIs
- Added ABIs:
- builtin functions
- ESDT system smart contract
- Added `BalanceBuilder` interface
- Added `NativeSerializer`

Breaking changes:
- Changed how a provider is obtained:
- Removed `getDevnetProvider`, `getTestnetProvider`, `getMainnetProvider`
- Use added `chooseProvider`
- Renamed `ESDTToken` to `Token`
- Changed how test wallets (alice, bob, carol etc.) are obtained, added all 12 test wallets:
- Removed `TestWallets`
- Use added function `loadTestWallets` (or `loadInteractive`)

## [6.5.1]
- [Adapted message signing for ledger #42](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/42)

Expand Down
6 changes: 3 additions & 3 deletions abi/esdtSystemContract.abi.json
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@
],
"outputs": [
{
"name": "esdtTokenName",
"name": "tokenName",
"type": "bytes"
},
{
Expand Down Expand Up @@ -328,7 +328,7 @@
"name": "getSpecialRoles",
"inputs": [
{
"name": "esdtTokenName",
"name": "tokenName",
"type": "bytes"
}
],
Expand All @@ -343,7 +343,7 @@
"name": "setSpecialRole",
"inputs": [
{
"name": "esdtTokenName",
"name": "tokenName",
"type": "bytes"
},
{
Expand Down
134 changes: 67 additions & 67 deletions src/apiProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,94 +6,94 @@ import { NetworkStake } from "./networkStake";
import { Stats } from "./stats";
import { TransactionHash } from "./transaction";
import { TransactionOnNetwork } from "./transactionOnNetwork";
import { ESDTToken } from "./esdtToken";
import { Token } from "./token";
import { NFTToken } from "./nftToken";
const JSONbig = require("json-bigint");

/**
* 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;
private url: string;
private config: AxiosRequestConfig;

/**
* Creates a new ApiProvider.
* @param url the URL of the Elrond Api
* @param config axios request config options
*/
constructor(url: string, config?: AxiosRequestConfig) {
this.url = url;
this.config = config || {
timeout: 1000,
};
}
/**
* Creates a new ApiProvider.
* @param url the URL of the Elrond Api
* @param config axios request config options
*/
constructor(url: string, config?: AxiosRequestConfig) {
this.url = url;
this.config = config || {
timeout: 1000,
};
}

/**
* Fetches the Network Stake.
*/
async getNetworkStake(): Promise<NetworkStake> {
return this.doGetGeneric("stake", (response) => NetworkStake.fromHttpResponse(response));
}
/**
* Fetches the Network Stake.
*/
async getNetworkStake(): Promise<NetworkStake> {
return this.doGetGeneric("stake", (response) => NetworkStake.fromHttpResponse(response));
}

/**
* Fetches the Network Stats.
*/
async getNetworkStats(): Promise<Stats> {
return this.doGetGeneric("stats", (response) => Stats.fromHttpResponse(response));
}
/**
* Fetches the Network Stats.
*/
async getNetworkStats(): Promise<Stats> {
return this.doGetGeneric("stats", (response) => Stats.fromHttpResponse(response));
}

/**
* Fetches the state of a {@link Transaction}.
*/
async getTransaction(txHash: TransactionHash): Promise<TransactionOnNetwork> {
return this.doGetGeneric(`transactions/${txHash.toString()}`, (response) =>
TransactionOnNetwork.fromHttpResponse(response)
);
}
/**
* Fetches the state of a {@link Transaction}.
*/
async getTransaction(txHash: TransactionHash): Promise<TransactionOnNetwork> {
return this.doGetGeneric(`transactions/${txHash.toString()}`, (response) =>
TransactionOnNetwork.fromHttpResponse(response)
);
}

async getESDTToken(tokenIdentifier: string): Promise<ESDTToken> {
return this.doGetGeneric(`tokens/${tokenIdentifier}`, (response) => ESDTToken.fromHttpResponse(response));
}
async getToken(tokenIdentifier: string): Promise<Token> {
return this.doGetGeneric(`tokens/${tokenIdentifier}`, (response) => Token.fromHttpResponse(response));
}

async getNFTToken(tokenIdentifier: string): Promise<NFTToken> {
return this.doGetGeneric(`nfts/${tokenIdentifier}`, (response) => NFTToken.fromHttpResponse(response));
}
async getNFTToken(tokenIdentifier: string): Promise<NFTToken> {
return this.doGetGeneric(`nfts/${tokenIdentifier}`, (response) => NFTToken.fromHttpResponse(response));
}

/**
* Get method that receives the resource url and on callback the method used to map the response.
*/
async doGetGeneric(resourceUrl: string, callback: (response: any) => any): Promise<any> {
let response = await this.doGet(resourceUrl);
return callback(response);
}
/**
* Get method that receives the resource url and on callback the method used to map the response.
*/
async doGetGeneric(resourceUrl: string, callback: (response: any) => any): Promise<any> {
let response = await this.doGet(resourceUrl);
return callback(response);
}

private async doGet(resourceUrl: string): Promise<any> {
try {
let url = `${this.url}/${resourceUrl}`;
let response = await axios.get(url, this.config);
private async doGet(resourceUrl: string): Promise<any> {
try {
let url = `${this.url}/${resourceUrl}`;
let response = await axios.get(url, this.config);

return response.data;
} catch (error) {
this.handleApiError(error, resourceUrl);
return response.data;
} catch (error) {
this.handleApiError(error, resourceUrl);
}
}
}

private handleApiError(error: any, resourceUrl: string) {
if (!error.response) {
Logger.warn(error);
throw new errors.ErrApiProviderGet(resourceUrl, error.toString(), error);
}
private handleApiError(error: any, resourceUrl: string) {
if (!error.response) {
Logger.warn(error);
throw new errors.ErrApiProviderGet(resourceUrl, error.toString(), error);
}

let errorData = error.response.data;
let originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData);
throw new errors.ErrApiProviderGet(resourceUrl, originalErrorMessage, error);
}
let errorData = error.response.data;
let originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData);
throw new errors.ErrApiProviderGet(resourceUrl, originalErrorMessage, error);
}
}

// See: https://github.com/axios/axios/issues/983
axios.defaults.transformResponse = [
function(data) {
return JSONbig.parse(data);
},
function (data) {
return JSONbig.parse(data);
},
];
16 changes: 8 additions & 8 deletions src/balance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BigNumber } from "bignumber.js";
import { ESDTToken } from "./esdtToken";
import { Token } from "./token";
import { ErrInvalidArgument } from "./errors";
import { Egld } from "./balanceBuilder";

Expand All @@ -15,14 +15,14 @@ BigNumber.set({ DECIMAL_PLACES: DEFAULT_BIGNUMBER_DECIMAL_PLACES, ROUNDING_MODE:
* Balance, as an immutable object.
*/
export class Balance {
readonly token: ESDTToken;
readonly token: Token;
private readonly nonce: BigNumber = new BigNumber(0);
private readonly value: BigNumber = new BigNumber(0);

/**
* Creates a Balance object.
*/
public constructor(token: ESDTToken, nonce: BigNumber.Value, value: BigNumber.Value) {
public constructor(token: Token, nonce: BigNumber.Value, value: BigNumber.Value) {
this.token = token;
this.nonce = new BigNumber(nonce);
this.value = new BigNumber(value);
Expand Down Expand Up @@ -65,7 +65,7 @@ export class Balance {
* Returns the string representation of the value (as EGLD currency).
*/
toCurrencyString(): string {
return `${this.toDenominated()} ${this.token.token}`;
return `${this.toDenominated()} ${this.token.getTokenIdentifier()}`;
}

toDenominated(): string {
Expand Down Expand Up @@ -98,21 +98,21 @@ export class Balance {
}

plus(other: Balance) {
this.checkSameType(other);
this.checkSameToken(other);
return new Balance(this.token, this.nonce, this.value.plus(other.value));
}

minus(other: Balance) {
this.checkSameType(other);
this.checkSameToken(other);
return new Balance(this.token, this.nonce, this.value.minus(other.value));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to check against deducting a high value from a low one, to avoid negative balances.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Negative balances are allowed.

}

isEqualTo(other: Balance) {
this.checkSameType(other);
this.checkSameToken(other);
return this.value.isEqualTo(other.value);
}

checkSameType(other: Balance) {
checkSameToken(other: Balance) {
if (this.token != other.token) {
throw new ErrInvalidArgument("Different token types");
}
Expand Down
18 changes: 9 additions & 9 deletions src/balanceBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import BigNumber from "bignumber.js";
import { Balance, ErrInvalidArgument, ErrInvariantFailed } from ".";
import { ESDTToken, TokenType } from "./esdtToken";
import { Balance, ErrInvariantFailed } from ".";
import { Token, TokenType } from "./token";

/**
* Creates balances for ESDTs (Fungible, Semi-Fungible (SFT) or Non-Fungible Tokens).
*/
export interface BalanceBuilder {

/**
* Creates a balance. Identical to {@link BalanceBuilder.denominated}
* Creates a balance. Identical to {@link BalanceBuilder.value}
*/
(value: BigNumber.Value): Balance;

Expand Down Expand Up @@ -46,7 +46,7 @@ export interface BalanceBuilder {
/*
* Get the token.
*/
getToken(): ESDTToken;
getToken(): Token;

/*
* Get the token identifier.
Expand All @@ -60,9 +60,9 @@ export interface BalanceBuilder {
}

class BalanceBuilderImpl {
readonly token: ESDTToken;
readonly token: Token;
nonce_: BigNumber | null;
constructor(token: ESDTToken) {
constructor(token: Token) {
this.token = token;
this.nonce_ = null;
if (token.isFungible()) {
Expand Down Expand Up @@ -104,7 +104,7 @@ class BalanceBuilderImpl {
return new BigNumber(this.nonce_);
}

getToken(): ESDTToken {
getToken(): Token {
return this.token;
}

Expand All @@ -113,7 +113,7 @@ class BalanceBuilderImpl {
}
}

export function createBalanceBuilder(token: ESDTToken): BalanceBuilder {
export function createBalanceBuilder(token: Token): BalanceBuilder {
let impl = new BalanceBuilderImpl(token);
let denominated = <BalanceBuilder>impl.value.bind(impl);
let others = {
Expand All @@ -133,7 +133,7 @@ export function createBalanceBuilder(token: ESDTToken): BalanceBuilder {
/**
* Builder for an EGLD value.
*/
export const Egld = createBalanceBuilder(new ESDTToken({ token: "EGLD", name: "eGold", decimals: 18, type: TokenType.FungibleESDT }));
export const Egld = createBalanceBuilder(new Token({ identifier: "EGLD", name: "eGold", decimals: 18, type: TokenType.Fungible }));

function applyDenomination(value: BigNumber.Value, decimals: number): BigNumber {
return new BigNumber(value).shiftedBy(decimals).decimalPlaces(0);
camilbancioiu marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Loading