diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f9a98118..33ff7b20b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,8 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how - [Breaking change: extractions (network providers and contract wrappers)](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/186) - [Breaking change: rename "methods" to "methodsExplicit". Rename "methodsAuto" to "methods" (default choice)](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/187) - [Remove SmartContractController (downgraded to a mere test utility)](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/188) + - [Breaking changes: cleanup and minor improvements prior release (step 1)](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/190) + - [Breaking changes: cleanup and minor improvements prior release (step 2)](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/191) **Breaking changes** - Removed utility functions: `transaction.awaitExecuted()`, `transaction.awaitPending()`. `TransactionWatcher` should be used directly, instead. @@ -49,6 +51,7 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how - Removed `transaction.awaitSigned()` (it isn't useful in relation with any of our signing providers). - Removed not used interfaces (e.g. `ISignable` is not needed in erdjs, but in walletcore). - Removed `interaction.getContract()`. Add `interaction.getContractAddress()`. + - Remove `interaction.withGasLimitComponents()`. Not so helpful anymore (since `NetworkConfig` isn't a singleton anymore). ## [10.0.0-beta.3] - [Extract dapp / signing providers to separate repositories](https://github.com/ElrondNetwork/elrond-sdk-erdjs/pull/170) diff --git a/package-lock.json b/package-lock.json index 1c250e2a2..c70267c7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "protobufjs": "6.10.2" }, "devDependencies": { - "@elrondnetwork/erdjs-network-providers": "0.1.2", + "@elrondnetwork/erdjs-network-providers": "0.1.3", "@elrondnetwork/erdjs-walletcore": "1.0.0", "@types/assert": "1.4.6", "@types/chai": "4.2.11", @@ -423,9 +423,9 @@ } }, "node_modules/@elrondnetwork/erdjs-network-providers": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@elrondnetwork/erdjs-network-providers/-/erdjs-network-providers-0.1.2.tgz", - "integrity": "sha512-6xlyoWHP2kLqsJr9hV5LgqDIrRo8YcF9xCUad/fP0cEyaJej6naeEC/TysGghWyfgpqQ4uUtkpSYFOlCJyL3zQ==", + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@elrondnetwork/erdjs-network-providers/-/erdjs-network-providers-0.1.3.tgz", + "integrity": "sha512-lGXkhcyYBoXEy4IwsmaeNOgusYlHTSlPtpLBAraZd+mgheb5bi/Kgb4qshrqQK5cujToQYup0ic68TOsGF+CuQ==", "dev": true, "dependencies": { "axios": "0.24.0", @@ -5956,9 +5956,9 @@ } }, "@elrondnetwork/erdjs-network-providers": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@elrondnetwork/erdjs-network-providers/-/erdjs-network-providers-0.1.2.tgz", - "integrity": "sha512-6xlyoWHP2kLqsJr9hV5LgqDIrRo8YcF9xCUad/fP0cEyaJej6naeEC/TysGghWyfgpqQ4uUtkpSYFOlCJyL3zQ==", + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@elrondnetwork/erdjs-network-providers/-/erdjs-network-providers-0.1.3.tgz", + "integrity": "sha512-lGXkhcyYBoXEy4IwsmaeNOgusYlHTSlPtpLBAraZd+mgheb5bi/Kgb4qshrqQK5cujToQYup0ic68TOsGF+CuQ==", "dev": true, "requires": { "axios": "0.24.0", diff --git a/package.json b/package.json index 96f45d1d2..a237c42d6 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "protobufjs": "6.10.2" }, "devDependencies": { - "@elrondnetwork/erdjs-network-providers": "0.1.2", + "@elrondnetwork/erdjs-network-providers": "0.1.3", "@elrondnetwork/erdjs-walletcore": "1.0.0", "@types/assert": "1.4.6", "@types/chai": "4.2.11", diff --git a/src/account.ts b/src/account.ts index b7bc4502d..dd8054ce8 100644 --- a/src/account.ts +++ b/src/account.ts @@ -2,7 +2,7 @@ import { Address } from "./address"; import { Nonce } from "./nonce"; import { Balance } from "./balance"; import { Egld } from "./balanceBuilder"; -import { IAccountBalance, INonce } from "./interface"; +import { IAccountBalance, IAddress, INonce } from "./interface"; /** * An abstraction representing an account (user or Smart Contract) on the Network. @@ -11,7 +11,7 @@ export class Account { /** * The address of the account. */ - readonly address: Address = new Address(); + readonly address: IAddress = new Address(); /** * The nonce of the account (the account sequence number). @@ -26,7 +26,7 @@ export class Account { /** * Creates an account object from an address */ - constructor(address: Address) { + constructor(address: IAddress) { this.address = address; } diff --git a/src/interface.ts b/src/interface.ts index c82a60894..07cbe8fa0 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -4,15 +4,13 @@ export interface ITransactionFetcher { /** * Fetches the state of a {@link Transaction}. */ - getTransaction(txHash: IHash, hintSender?: IAddress, withResults?: boolean): Promise; + getTransaction(txHash: string): Promise; } export interface ISignature { hex(): string; } -export interface IHash { hex(): string; } export interface IAddress { bech32(): string; } export interface ITransactionValue { toString(): string; } export interface IAccountBalance { toString(): string; } -export interface ITransactionPayload { encoded(): string; } export interface INonce { valueOf(): number; } export interface IChainID { valueOf(): string; } export interface IGasLimit { valueOf(): number; } diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index 7b7838272..73a4fd704 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,26 +1,26 @@ -import { IAccountBalance, IAddress, IChainID, IGasLimit, IHash, INonce, ITransactionPayload, ITransactionValue } from "./interface"; +import { IAccountBalance, IAddress } from "./interface"; export interface IAccountOnNetwork { - nonce: INonce; + nonce: number; balance: IAccountBalance; } export interface INetworkConfig { - MinGasLimit: IGasLimit; + MinGasLimit: number; GasPerDataByte: number; GasPriceModifier: number; - ChainID: IChainID; + ChainID: string; } export interface ITransactionOnNetwork { isCompleted: boolean; - hash: IHash; + hash: string; type: string; - value: ITransactionValue; + value: string; receiver: IAddress; sender: IAddress; - data: ITransactionPayload; + data: Buffer; status: ITransactionStatus; receipt: ITransactionReceipt; contractResults: IContractResults; @@ -43,8 +43,8 @@ export interface IContractResults { } export interface IContractResultItem { - hash: IHash; - nonce: INonce; + hash: string; + nonce: number; receiver: IAddress; sender: IAddress; data: string; diff --git a/src/smartcontracts/interaction.spec.ts b/src/smartcontracts/interaction.spec.ts index e107e4402..468fb2d97 100644 --- a/src/smartcontracts/interaction.spec.ts +++ b/src/smartcontracts/interaction.spec.ts @@ -40,17 +40,13 @@ describe("test smart contract interactor", function() { let transaction = interaction .withNonce(new Nonce(7)) .withValue(Balance.egld(1)) - .withGasLimitComponents({ minGasLimit: 50000, gasPerDataByte: 1500, estimatedExecutionComponent: 20000000 }) + .withGasLimit(new GasLimit(20000000)) .buildTransaction(); - let expectedGasLimit = new GasLimit(50000) - .add(new GasLimit("dummy".length * 1500)) - .add(new GasLimit(20000000)); - assert.deepEqual(transaction.getReceiver(), dummyAddress); assert.deepEqual(transaction.getValue(), Balance.egld(1)); assert.deepEqual(transaction.getNonce(), new Nonce(7)); - assert.deepEqual(transaction.getGasLimit(), expectedGasLimit); + assert.equal(transaction.getGasLimit().valueOf(), 20000000); }); it("should set transfers (payments) on contract calls (transfer and execute)", async function () { @@ -126,7 +122,7 @@ describe("test smart contract interactor", function() { provider.mockQueryContractOnFunction( "getUltimateAnswer", - new ContractQueryResponse({ returnData: [Buffer.from([42]).toString("base64")], returnCode: ReturnCode.Ok }) + new ContractQueryResponse({ returnData: [Buffer.from([42]).toString("base64")], returnCode: "ok" }) ); // Query @@ -183,7 +179,7 @@ describe("test smart contract interactor", function() { // For "get()", return fake 7 provider.mockQueryContractOnFunction( "get", - new ContractQueryResponse({ returnData: [Buffer.from([7]).toString("base64")], returnCode: ReturnCode.Ok }) + new ContractQueryResponse({ returnData: [Buffer.from([7]).toString("base64")], returnCode: "ok" }) ); // Query "get()" diff --git a/src/smartcontracts/interaction.ts b/src/smartcontracts/interaction.ts index 2b190809f..7de11ebff 100644 --- a/src/smartcontracts/interaction.ts +++ b/src/smartcontracts/interaction.ts @@ -1,5 +1,5 @@ import { Balance } from "../balance"; -import { ChainID, GasLimit, GasPrice } from "../networkParams"; +import { ChainID, GasLimit } from "../networkParams"; import { Transaction } from "../transaction"; import { Query } from "./query"; import { ContractFunction } from "./function"; @@ -9,7 +9,7 @@ import { Nonce } from "../nonce"; import { ESDTNFT_TRANSFER_FUNCTION_NAME, ESDT_TRANSFER_FUNCTION_NAME, MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME } from "../constants"; import { Account } from "../account"; import { CallArguments } from "./interface"; -import { IAddress, IChainID, IGasLimit, IGasPrice } from "../interface"; +import { IAddress, IChainID, IGasLimit, IGasPrice, INonce } from "../interface"; import { InteractionChecker } from "./interactionChecker"; /** @@ -32,7 +32,7 @@ export class Interaction { private readonly function: ContractFunction; private readonly args: TypedValue[]; - private nonce: Nonce = new Nonce(0); + private nonce: INonce = new Nonce(0); private value: Balance = Balance.Zero(); private gasLimit: IGasLimit = new GasLimit(0); private gasPrice: IGasPrice | undefined = undefined; @@ -142,44 +142,31 @@ export class Interaction { return this; } - withSingleESDTNFTTransfer(transfer: Balance, sender: Address) { + withSingleESDTNFTTransfer(transfer: Balance, sender: IAddress) { this.isWithSingleESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction([transfer], this); this.tokenTransfersSender = sender; return this; } - withMultiESDTNFTTransfer(transfers: Balance[], sender: Address) { + withMultiESDTNFTTransfer(transfers: Balance[], sender: IAddress) { this.isWithMultiESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction(transfers, this); this.tokenTransfersSender = sender; return this; } - withGasLimit(gasLimit: GasLimit): Interaction { + withGasLimit(gasLimit: IGasLimit): Interaction { this.gasLimit = gasLimit; return this; } - withGasLimitComponents(args: { minGasLimit: number, gasPerDataByte: number, estimatedExecutionComponent: number }): Interaction { - let minGasLimit = args.minGasLimit; - let gasPerDataByte = args.gasPerDataByte; - - let transaction = this.buildTransaction(); - let dataLength = transaction.getData().length(); - let movementComponent = new GasLimit(minGasLimit + gasPerDataByte * dataLength); - let executionComponent = new GasLimit(args.estimatedExecutionComponent); - let gasLimit = movementComponent.add(executionComponent); - - return this.withGasLimit(gasLimit); - } - - withGasPrice(gasPrice: GasPrice): Interaction { + withGasPrice(gasPrice: IGasPrice): Interaction { this.gasPrice = gasPrice; return this; } - withNonce(nonce: Nonce): Interaction { + withNonce(nonce: INonce): Interaction { this.nonce = nonce; return this; } @@ -196,7 +183,7 @@ export class Interaction { /** * Sets the "caller" field on contract queries. */ - withQuerent(querent: Address): Interaction { + withQuerent(querent: IAddress): Interaction { this.querent = querent; return this; } diff --git a/src/smartcontracts/interface.ts b/src/smartcontracts/interface.ts index 0ef51b531..800e79add 100644 --- a/src/smartcontracts/interface.ts +++ b/src/smartcontracts/interface.ts @@ -1,12 +1,11 @@ import { Balance } from "../balance"; import { IAddress, IChainID, IGasLimit, IGasPrice } from "../interface"; -import { IContractQueryResponse, ITransactionOnNetwork } from "../interfaceOfNetwork"; import { Transaction } from "../transaction"; import { Code } from "./code"; import { CodeMetadata } from "./codeMetadata"; import { ContractFunction } from "./function"; import { ReturnCode } from "./returnCode"; -import { EndpointDefinition, TypedValue } from "./typesystem"; +import { TypedValue } from "./typesystem"; /** * ISmartContract defines a general interface for operating with {@link SmartContract} objects. diff --git a/src/smartcontracts/nativeSerializer.ts b/src/smartcontracts/nativeSerializer.ts index 8eb449ec1..dc5f4831d 100644 --- a/src/smartcontracts/nativeSerializer.ts +++ b/src/smartcontracts/nativeSerializer.ts @@ -6,11 +6,12 @@ import { BalanceBuilder } from "../balanceBuilder"; import { Address } from "../address"; import { Code } from "./code"; import { ErrInvalidArgument, ErrTypeInferenceSystemRequiresRegularJavascriptObjects, ErrTypingSystem } from "../errors"; +import { IAddress } from "../interface"; export namespace NativeTypes { export type NativeBuffer = Buffer | string | BalanceBuilder; export type NativeBytes = Code | Buffer | string | BalanceBuilder; - export type NativeAddress = Address | string | Buffer | { getAddress(): Address }; + export type NativeAddress = string | Buffer | IAddress | { getAddress(): IAddress }; } export namespace NativeSerializer { @@ -241,16 +242,18 @@ export namespace NativeSerializer { errorContext.convertError(native, "Buffer"); } - export function convertNativeToAddress(native: NativeTypes.NativeAddress, errorContext: ArgumentErrorContext): Address { + export function convertNativeToAddress(native: NativeTypes.NativeAddress, errorContext: ArgumentErrorContext): IAddress { + if ((native).bech32) { + return native; + } if ((native).getAddress) { return (native).getAddress(); } switch (native.constructor) { - case Address: case Buffer: case String: - return new Address(
native); + return new Address(native); default: errorContext.convertError(native, "Address"); } diff --git a/src/smartcontracts/query.spec.ts b/src/smartcontracts/query.spec.ts index baedc6126..7c9539920 100644 --- a/src/smartcontracts/query.spec.ts +++ b/src/smartcontracts/query.spec.ts @@ -2,28 +2,12 @@ import { assert } from "chai"; import { Address } from "../address"; import { ContractFunction } from "./function"; import { Query } from "./query"; -import { Balance } from "../balance"; -import * as errors from "../errors"; import { BigUIntValue, U32Value } from "./typesystem"; import BigNumber from "bignumber.js"; import { BytesValue } from "./typesystem/bytes"; describe("test smart contract queries", () => { - it("should prepare query", async () => { - let query = new Query({ - func: new ContractFunction("foo"), - address: new Address("erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q"), - value: Balance.egld(42) - }); - - let request = query.toHttpRequest(); - assert.equal(request["scAddress"], "erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q"); - assert.equal(request["funcName"], "foo"); - assert.equal(request["value"], "42000000000000000000"); - assert.lengthOf(request["args"], 0); - }); - - it("should prepare query with arguments", async () => { + it("should getEncodedArguments()", async () => { let query = new Query({ func: new ContractFunction("foo"), address: new Address("erd1qqqqqqqqqqqqqpgq3ytm9m8dpeud35v3us20vsafp77smqghd8ss4jtm0q"), @@ -35,11 +19,11 @@ describe("test smart contract queries", () => { ] }); - let request = query.toHttpRequest(); - assert.lengthOf(request["args"], 4); - assert.equal(request["args"][0], "64"); - assert.equal(request["args"][1], "21"); - assert.equal(request["args"][2], "abba"); - assert.equal(request["args"][3], "314dc6448d9338c15b0a00000000"); + let args = query.getEncodedArguments(); + assert.lengthOf(args, 4); + assert.equal(args[0], "64"); + assert.equal(args[1], "21"); + assert.equal(args[2], "abba"); + assert.equal(args[3], "314dc6448d9338c15b0a00000000"); }); }); diff --git a/src/smartcontracts/query.ts b/src/smartcontracts/query.ts index c34fc4a50..5ca2754f2 100644 --- a/src/smartcontracts/query.ts +++ b/src/smartcontracts/query.ts @@ -1,7 +1,6 @@ import { ContractFunction } from "./function"; import { Balance } from "../balance"; import { Address } from "../address"; -import { guardValueIsSet } from "../utils"; import { TypedValue } from "./typesystem"; import { ArgSerializer } from "./argSerializer"; import { IAddress, ITransactionValue } from "../interface"; @@ -13,35 +12,21 @@ export class Query { args: TypedValue[]; value: ITransactionValue; - constructor(init?: Partial) { - this.caller = new Address(); - this.address = new Address(); - this.func = ContractFunction.none(); - this.args = []; - this.value = Balance.Zero(); - - Object.assign(this, init); - - guardValueIsSet("address", this.address); - guardValueIsSet("func", this.func); - - this.args = this.args || []; - this.caller = this.caller || new Address(); - this.value = this.value || Balance.Zero(); + constructor(obj: { + caller?: IAddress, + address: IAddress, + func: ContractFunction, + args?: TypedValue[], + value?: ITransactionValue + }) { + this.caller = obj.caller || new Address(); + this.address = obj.address; + this.func = obj.func; + this.args = obj.args || []; + this.value = obj.value || Balance.Zero(); } - toHttpRequest() { - let request: any = { - "scAddress": this.address.bech32(), - "funcName": this.func.toString(), - "args": new ArgSerializer().valuesToStrings(this.args), - "value": this.value.toString() - }; - - if (this.caller.bech32()) { - request["caller"] = this.caller.bech32(); - } - - return request; + getEncodedArguments(): string[] { + return new ArgSerializer().valuesToStrings(this.args); } } diff --git a/src/smartcontracts/resultsParser.spec.ts b/src/smartcontracts/resultsParser.spec.ts index e5a3a01f5..a862a1231 100644 --- a/src/smartcontracts/resultsParser.spec.ts +++ b/src/smartcontracts/resultsParser.spec.ts @@ -5,8 +5,6 @@ import { BigUIntType, BigUIntValue, EndpointDefinition, EndpointModifiers, Endpo import { BytesType, BytesValue } from "./typesystem/bytes"; import { ReturnCode } from "./returnCode"; import { ResultsParser } from "./resultsParser"; -import { Nonce } from "../nonce"; -import { TransactionHash } from "../transaction"; import { Logger, LogLevel } from "../logger"; import { ITransactionOnNetwork } from "../interfaceOfNetwork"; import { ContractQueryResponse, ContractResultItem, ContractResults, TransactionEvent, TransactionEventTopic, TransactionLogs, TransactionOnNetwork } from "@elrondnetwork/erdjs-network-providers"; @@ -47,7 +45,7 @@ describe("test smart contract results parser", () => { Buffer.from([42]).toString("base64"), Buffer.from("abba", "hex").toString("base64"), ], - returnCode: ReturnCode.Ok, + returnCode: "ok", returnMessage: "foobar" }); @@ -69,7 +67,7 @@ describe("test smart contract results parser", () => { let transactionOnNetwork = new TransactionOnNetwork({ contractResults: new ContractResults([ - new ContractResultItem({ nonce: new Nonce(7), data: "@6f6b@2a@abba" }) + new ContractResultItem({ nonce: 7, data: "@6f6b@2a@abba" }) ]) }); @@ -85,7 +83,7 @@ describe("test smart contract results parser", () => { let transaction = new TransactionOnNetwork({ contractResults: new ContractResults([ new ContractResultItem({ - nonce: new Nonce(42), + nonce: 42, data: "@6f6b@03", returnMessage: "foobar" }) @@ -100,15 +98,16 @@ describe("test smart contract results parser", () => { it("should parse contract outcome, on signal error", async () => { let transaction = new TransactionOnNetwork({ - logs: new TransactionLogs(new Address(), [ - new TransactionEvent({ - identifier: "signalError", - topics: [ - new TransactionEventTopic(Buffer.from("something happened").toString("base64")) - ], - data: `@${Buffer.from("user error").toString("hex")}@07` - }) - ]) + logs: new TransactionLogs({ + address: new Address(), + events: [ + new TransactionEvent({ + identifier: "signalError", + topics: [new TransactionEventTopic(Buffer.from("something happened").toString("base64"))], + data: `@${Buffer.from("user error").toString("hex")}@07` + }) + ] + }) }); let bundle = parser.parseUntypedOutcome(transaction); @@ -119,15 +118,16 @@ describe("test smart contract results parser", () => { it("should parse contract outcome, on too much gas warning", async () => { let transaction = new TransactionOnNetwork({ - logs: new TransactionLogs(new Address(), [ - new TransactionEvent({ - identifier: "writeLog", - topics: [ - new TransactionEventTopic("QHRvbyBtdWNoIGdhcyBwcm92aWRlZCBmb3IgcHJvY2Vzc2luZzogZ2FzIHByb3ZpZGVkID0gNTk2Mzg0NTAwLCBnYXMgdXNlZCA9IDczMzAxMA==") - ], - data: Buffer.from("QDZmNmI=", "base64").toString() - }) - ]) + logs: new TransactionLogs({ + address: new Address(), + events: [ + new TransactionEvent({ + identifier: "writeLog", + topics: [new TransactionEventTopic("QHRvbyBtdWNoIGdhcyBwcm92aWRlZCBmb3IgcHJvY2Vzc2luZzogZ2FzIHByb3ZpZGVkID0gNTk2Mzg0NTAwLCBnYXMgdXNlZCA9IDczMzAxMA==")], + data: Buffer.from("QDZmNmI=", "base64").toString() + }) + ] + }) }); let bundle = parser.parseUntypedOutcome(transaction); @@ -166,7 +166,7 @@ describe("test smart contract results parser", () => { let samples: [ITransactionOnNetwork, string][] = []; for (const file of transactionFiles) { - let txHash = new TransactionHash(path.basename(file, ".json")); + let txHash = path.basename(file, ".json"); let filePath = path.resolve(folder, file); let jsonContent: string = fs.readFileSync(filePath, { encoding: "utf8" }); let json = JSON.parse(jsonContent); diff --git a/src/smartcontracts/resultsParser.ts b/src/smartcontracts/resultsParser.ts index 83f366103..f72c876c3 100644 --- a/src/smartcontracts/resultsParser.ts +++ b/src/smartcontracts/resultsParser.ts @@ -125,7 +125,7 @@ export class ResultsParser { return new TransactionDecoder().getTransactionMetadata({ sender: transaction.sender.bech32(), receiver: transaction.receiver.bech32(), - data: transaction.data.encoded(), + data: transaction.data.toString("base64"), value: transaction.value.toString(), type: transaction.type }); diff --git a/src/smartcontracts/smartContract.local.net.spec.ts b/src/smartcontracts/smartContract.local.net.spec.ts index f8e9a8a59..3f628997e 100644 --- a/src/smartcontracts/smartContract.local.net.spec.ts +++ b/src/smartcontracts/smartContract.local.net.spec.ts @@ -79,12 +79,12 @@ describe("test on local testnet", function () { await provider.sendTransaction(transactionIncrement); await watcher.awaitCompleted(transactionDeploy); - let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash()); + let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash().hex()); let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); assert.isTrue(bundle.returnCode.isSuccess()); await watcher.awaitCompleted(transactionIncrement); - transactionOnNetwork = await provider.getTransaction(transactionIncrement.getHash()); + transactionOnNetwork = await provider.getTransaction(transactionIncrement.getHash().hex()); bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); assert.isTrue(bundle.returnCode.isSuccess()); @@ -289,11 +289,11 @@ describe("test on local testnet", function () { await watcher.awaitAnyEvent(transactionStart, ["completedTxEvent"]); // Let's check the SCRs - let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash()); + let transactionOnNetwork = await provider.getTransaction(transactionDeploy.getHash().hex()); let bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); assert.isTrue(bundle.returnCode.isSuccess()); - transactionOnNetwork = await provider.getTransaction(transactionStart.getHash()); + transactionOnNetwork = await provider.getTransaction(transactionStart.getHash().hex()); bundle = resultsParser.parseUntypedOutcome(transactionOnNetwork); assert.isTrue(bundle.returnCode.isSuccess()); diff --git a/src/smartcontracts/smartContract.spec.ts b/src/smartcontracts/smartContract.spec.ts index bece92d44..55f5b62b0 100644 --- a/src/smartcontracts/smartContract.spec.ts +++ b/src/smartcontracts/smartContract.spec.ts @@ -43,7 +43,7 @@ describe("test contract", () => { }); provider.mockUpdateAccount(alice.address, account => { - account.nonce = new Nonce(42); + account.nonce = 42; }); await alice.sync(provider); @@ -78,7 +78,7 @@ describe("test contract", () => { let contract = new SmartContract({ address: new Address("erd1qqqqqqqqqqqqqpgqak8zt22wl2ph4tswtyc39namqx6ysa2sd8ss4xmlj3") }); provider.mockUpdateAccount(alice.address, account => { - account.nonce = new Nonce(42); + account.nonce = 42 }); let callTransactionOne = contract.call({ diff --git a/src/smartcontracts/smartContractResults.local.net.spec.ts b/src/smartcontracts/smartContractResults.local.net.spec.ts index 176fcb180..30bddd740 100644 --- a/src/smartcontracts/smartContractResults.local.net.spec.ts +++ b/src/smartcontracts/smartContractResults.local.net.spec.ts @@ -57,8 +57,8 @@ describe("fetch transactions from local testnet", function () { await watcher.awaitCompleted(transactionDeploy); await watcher.awaitCompleted(transactionIncrement); - let transactionOnNetworkDeploy = await provider.getTransaction(transactionDeploy.getHash()); - let transactionOnNetworkIncrement = await provider.getTransaction(transactionIncrement.getHash()); + let transactionOnNetworkDeploy = await provider.getTransaction(transactionDeploy.getHash().hex()); + let transactionOnNetworkIncrement = await provider.getTransaction(transactionIncrement.getHash().hex()); let bundle = resultsParser.parseUntypedOutcome(transactionOnNetworkDeploy); assert.isTrue(bundle.returnCode.isSuccess()); diff --git a/src/testutils/mockProvider.ts b/src/testutils/mockProvider.ts index 7dac160d4..cd74fb7c1 100644 --- a/src/testutils/mockProvider.ts +++ b/src/testutils/mockProvider.ts @@ -1,7 +1,6 @@ -import { IAddress, IHash } from "../interface"; +import { IAddress } from "../interface"; import { Transaction, TransactionHash } from "../transaction"; import { Address } from "../address"; -import { Nonce } from "../nonce"; import { AsyncTimer } from "../asyncTimer"; import { Balance } from "../balance"; import * as errors from "../errors"; @@ -27,15 +26,15 @@ export class MockProvider { this.accounts.set( MockProvider.AddressOfAlice.bech32(), - new AccountOnNetwork({ nonce: new Nonce(0), balance: Balance.egld(1000) }) + new AccountOnNetwork({ nonce: 0, balance: Balance.egld(1000).toString() }) ); this.accounts.set( MockProvider.AddressOfBob.bech32(), - new AccountOnNetwork({ nonce: new Nonce(5), balance: Balance.egld(500) }) + new AccountOnNetwork({ nonce: 5, balance: Balance.egld(500).toString() }) ); this.accounts.set( MockProvider.AddressOfCarol.bech32(), - new AccountOnNetwork({ nonce: new Nonce(42), balance: Balance.egld(300) }) + new AccountOnNetwork({ nonce: 42, balance: Balance.egld(300).toString() }) ); } @@ -63,9 +62,9 @@ export class MockProvider { } mockGetTransactionWithAnyHashAsNotarizedWithOneResult(returnCodeAndData: string) { - let contractResult = new ContractResultItem({ nonce: new Nonce(1), data: returnCodeAndData }); + let contractResult = new ContractResultItem({ nonce: 1, data: returnCodeAndData }); - let predicate = (_hash: IHash) => true; + let predicate = (_hash: string) => true; let response = new TransactionOnNetwork({ status: new TransactionStatus("executed"), contractResults: new ContractResults([contractResult]), @@ -112,30 +111,26 @@ export class MockProvider { throw new ErrMock("Account not found") } - async sendTransaction(transaction: Transaction): Promise { + async sendTransaction(transaction: Transaction): Promise { this.mockPutTransaction( transaction.getHash(), new TransactionOnNetwork({ sender: transaction.getSender(), receiver: transaction.getReceiver(), - data: transaction.getData(), + data: transaction.getData().valueOf(), status: new TransactionStatus("pending"), }) ); this.mockTransactionTimeline(transaction, this.nextTransactionTimelinePoints); - return transaction.getHash(); + return transaction.getHash().hex(); } async simulateTransaction(_transaction: Transaction): Promise { return {}; } - async getTransaction( - txHash: IHash, - _hintSender?: IAddress, - _withResults?: boolean - ): Promise { + async getTransaction(txHash: string): Promise { // At first, try to use a mock responder for (const responder of this.getTransactionResponders) { if (responder.matches(txHash)) { @@ -152,7 +147,7 @@ export class MockProvider { throw new ErrMock("Transaction not found"); } - async getTransactionStatus(txHash: TransactionHash): Promise { + async getTransactionStatus(txHash: string): Promise { let transaction = await this.getTransaction(txHash); return transaction.status; } @@ -193,10 +188,10 @@ class QueryContractResponder { } class GetTransactionResponder { - readonly matches: (hash: IHash) => boolean; + readonly matches: (hash: string) => boolean; readonly response: ITransactionOnNetwork; - constructor(matches: (hash: IHash) => boolean, response: ITransactionOnNetwork) { + constructor(matches: (hash: string) => boolean, response: ITransactionOnNetwork) { this.matches = matches; this.response = response; } diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 01ca92299..ee3a836c1 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,19 +1,19 @@ -import { createProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; -import { IAddress, IHash } from "../interface"; +import { ProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; +import { IAddress } from "../interface"; import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionOnNetwork, ITransactionStatus } from "../interfaceOfNetwork"; import { Query } from "../smartcontracts/query"; import { Transaction } from "../transaction"; export function createLocalnetProvider(): INetworkProvider { - return createProxyNetworkProvider("http://localhost:7950", { timeout: 5000 }); + return new ProxyNetworkProvider("http://localhost:7950", { timeout: 5000 }); } export interface INetworkProvider { getNetworkConfig(): Promise; getAccount(address: IAddress): Promise; - getTransaction(txHash: IHash): Promise; - getTransactionStatus(txHash: IHash): Promise; - sendTransaction(tx: Transaction): Promise; + getTransaction(txHash: string): Promise; + getTransactionStatus(txHash: string): Promise; + sendTransaction(tx: Transaction): Promise; simulateTransaction(tx: Transaction): Promise; queryContract(query: Query): Promise; } diff --git a/src/transaction.spec.ts b/src/transaction.spec.ts index 36c23e97f..a05e5f383 100644 --- a/src/transaction.spec.ts +++ b/src/transaction.spec.ts @@ -142,7 +142,7 @@ describe("test transaction construction", async () => { }); let networkConfig = { - MinGasLimit: new GasLimit(10), + MinGasLimit: 10, GasPerDataByte: 1500, GasPriceModifier: 0.01, ChainID: "T" @@ -164,7 +164,7 @@ describe("test transaction construction", async () => { }); let networkConfig = { - MinGasLimit: new GasLimit(10), + MinGasLimit: 10, GasPerDataByte: 1500, GasPriceModifier: 0.01, ChainID: "T" diff --git a/src/transaction.ts b/src/transaction.ts index 896008580..8bd857f4f 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,5 +1,5 @@ import { BigNumber } from "bignumber.js"; -import { IAddress, IChainID, IGasLimit, IGasPrice, ISignature } from "./interface"; +import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ISignature } from "./interface"; import { Address } from "./address"; import { Balance } from "./balance"; import { @@ -28,7 +28,7 @@ export class Transaction { /** * The nonce of the transaction (the account sequence number of the sender). */ - private nonce: Nonce; + private nonce: INonce; /** * The value to transfer. @@ -126,7 +126,7 @@ export class Transaction { this.hash = TransactionHash.empty(); } - getNonce(): Nonce { + getNonce(): INonce { return this.nonce; } @@ -146,7 +146,7 @@ export class Transaction { * await alice.signer.sign(tx); * ``` */ - setNonce(nonce: Nonce) { + setNonce(nonce: INonce) { this.nonce = nonce; } diff --git a/src/transactionWatcher.spec.ts b/src/transactionWatcher.spec.ts index cec65d251..d2825e5f4 100644 --- a/src/transactionWatcher.spec.ts +++ b/src/transactionWatcher.spec.ts @@ -23,6 +23,6 @@ describe("test transactionWatcher", () => { watcher.awaitCompleted(dummyTransaction) ]); - assert.isTrue((await provider.getTransactionStatus(hash)).isExecuted()); + assert.isTrue((await provider.getTransactionStatus(hash.hex())).isExecuted()); }); }); diff --git a/src/transactionWatcher.ts b/src/transactionWatcher.ts index 099229f81..ddf7d8c1e 100644 --- a/src/transactionWatcher.ts +++ b/src/transactionWatcher.ts @@ -1,8 +1,7 @@ -import { ITransactionFetcher, IHash } from "./interface"; +import { ITransactionFetcher } from "./interface"; import { AsyncTimer } from "./asyncTimer"; import { Logger } from "./logger"; import { Err, ErrExpectedTransactionEventsNotFound, ErrExpectedTransactionStatusNotReached } from "./errors"; -import { Address } from "./address"; import { ITransactionEvent, ITransactionOnNetwork, ITransactionStatus } from "./interfaceOfNetwork"; export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; @@ -11,7 +10,7 @@ export type PredicateIsAwaitedStatus = (status: ITransactionStatus) => boolean; * Internal interface: a transaction, as seen from the perspective of a {@link TransactionWatcher}. */ interface ITransaction { - getHash(): IHash; + getHash(): { hex(): string; } } /** @@ -48,7 +47,7 @@ export class TransactionWatcher { */ public async awaitPending(transaction: ITransaction): Promise { let isPending = (transaction: ITransactionOnNetwork) => transaction.status.isPending(); - let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash()); + let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash().hex()); let errorProvider = () => new ErrExpectedTransactionStatusNotReached(); return this.awaitConditionally( @@ -63,7 +62,7 @@ export class TransactionWatcher { */ public async awaitCompleted(transaction: ITransaction): Promise { let isCompleted = (transactionOnNetwork: ITransactionOnNetwork) => transactionOnNetwork.isCompleted; - let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash(), undefined, true); + let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash().hex()); let errorProvider = () => new ErrExpectedTransactionStatusNotReached(); return this.awaitConditionally( @@ -80,7 +79,7 @@ export class TransactionWatcher { return allAreFound; }; - let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash(), undefined, true); + let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash().hex()); let errorProvider = () => new ErrExpectedTransactionEventsNotFound(); return this.awaitConditionally( @@ -97,7 +96,7 @@ export class TransactionWatcher { return anyIsFound; }; - let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash(), undefined, true); + let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash().hex()); let errorProvider = () => new ErrExpectedTransactionEventsNotFound(); return this.awaitConditionally( @@ -108,7 +107,7 @@ export class TransactionWatcher { } public async awaitOnCondition(transaction: ITransaction, condition: (data: ITransactionOnNetwork) => boolean): Promise { - let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash(), undefined, true); + let doFetch = async () => await this.fetcher.getTransaction(transaction.getHash().hex()); let errorProvider = () => new ErrExpectedTransactionStatusNotReached(); return this.awaitConditionally( @@ -183,8 +182,8 @@ class TransactionFetcherWithTracing implements ITransactionFetcher { this.fetcher = fetcher; } - async getTransaction(txHash: IHash, hintSender?: Address, withResults?: boolean): Promise { - Logger.debug(`transactionWatcher, getTransaction(${txHash.toString()})`); - return await this.fetcher.getTransaction(txHash, hintSender, withResults); + async getTransaction(txHash: string): Promise { + Logger.debug(`transactionWatcher, getTransaction(${txHash})`); + return await this.fetcher.getTransaction(txHash); } }