From bdbefd1526af1a6ccfa99c1d8e58a3be2fa24f07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 13:34:43 +0300 Subject: [PATCH 01/12] Simplifications (wrt. integration with network providers). --- src/interface.ts | 1 - src/smartcontracts/interaction.spec.ts | 4 ++-- src/smartcontracts/resultsParser.spec.ts | 6 +++--- src/smartcontracts/resultsParser.ts | 2 +- src/testutils/mockProvider.ts | 10 +++++----- src/transaction.spec.ts | 4 ++-- 6 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/interface.ts b/src/interface.ts index 2ae791056..a26a962ad 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -12,7 +12,6 @@ export interface IHash { hex(): string; } export interface IBech32Address { 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/smartcontracts/interaction.spec.ts b/src/smartcontracts/interaction.spec.ts index e107e4402..b330e9f46 100644 --- a/src/smartcontracts/interaction.spec.ts +++ b/src/smartcontracts/interaction.spec.ts @@ -126,7 +126,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 +183,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/resultsParser.spec.ts b/src/smartcontracts/resultsParser.spec.ts index e5a3a01f5..f350fc5c4 100644 --- a/src/smartcontracts/resultsParser.spec.ts +++ b/src/smartcontracts/resultsParser.spec.ts @@ -47,7 +47,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 +69,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 +85,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" }) diff --git a/src/smartcontracts/resultsParser.ts b/src/smartcontracts/resultsParser.ts index 121c57942..794f630cd 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/testutils/mockProvider.ts b/src/testutils/mockProvider.ts index e9b8da8a0..f29306da6 100644 --- a/src/testutils/mockProvider.ts +++ b/src/testutils/mockProvider.ts @@ -27,15 +27,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,7 +63,7 @@ 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 response = new TransactionOnNetwork({ @@ -118,7 +118,7 @@ export class MockProvider { new TransactionOnNetwork({ sender: transaction.getSender(), receiver: transaction.getReceiver(), - data: transaction.getData(), + data: transaction.getData().valueOf(), status: new TransactionStatus("pending"), }) ); 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" From 5d122336bca1c1e7c5a33a82b71a48083cabef2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 15:12:17 +0300 Subject: [PATCH 02/12] Move query.toHttpRequest() logic to network-providers. --- src/interfaceOfNetwork.ts | 8 +++--- src/smartcontracts/query.spec.ts | 30 +++++---------------- src/smartcontracts/query.ts | 43 ++++++++++--------------------- src/testutils/networkProviders.ts | 4 +-- 4 files changed, 27 insertions(+), 58 deletions(-) diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index a4f4d4430..7538fde69 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,4 +1,4 @@ -import { IAccountBalance, IBech32Address, IChainID, IGasLimit, IHash, INonce, ITransactionPayload, ITransactionValue } from "./interface"; +import { IAccountBalance, IBech32Address, IChainID, IGasLimit, IHash, INonce, ITransactionValue } from "./interface"; export interface IAccountOnNetwork { nonce: INonce; @@ -6,10 +6,10 @@ export interface IAccountOnNetwork { } export interface INetworkConfig { - MinGasLimit: IGasLimit; + MinGasLimit: number; GasPerDataByte: number; GasPriceModifier: number; - ChainID: IChainID; + ChainID: string; } export interface ITransactionOnNetwork { @@ -20,7 +20,7 @@ export interface ITransactionOnNetwork { value: ITransactionValue; receiver: IBech32Address; sender: IBech32Address; - data: ITransactionPayload; + data: Buffer; status: ITransactionStatus; receipt: ITransactionReceipt; contractResults: IContractResults; 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 add9a6ab9..81bc28801 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 { IBech32Address, 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?: IBech32Address, + address: IBech32Address, + 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/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index a45668787..7798b0fdd 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,11 +1,11 @@ -import { createProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; +import { ProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; import { IBech32Address, IHash } 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 { From 3eae57f102548010eac71ddda905ac508ff639d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 19:33:06 +0300 Subject: [PATCH 03/12] Simplifications (IHash vs. string). --- src/interface.ts | 3 +-- src/interfaceOfNetwork.ts | 12 +++++------ src/smartcontracts/resultsParser.spec.ts | 2 +- .../smartContract.local.net.spec.ts | 8 +++---- src/smartcontracts/smartContract.spec.ts | 4 ++-- .../smartContractResults.local.net.spec.ts | 4 ++-- src/testutils/mockProvider.ts | 21 +++++++------------ src/testutils/networkProviders.ts | 8 +++---- src/transactionWatcher.spec.ts | 2 +- src/transactionWatcher.ts | 21 +++++++++---------- 10 files changed, 39 insertions(+), 46 deletions(-) diff --git a/src/interface.ts b/src/interface.ts index a26a962ad..fbfaf9cd1 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -4,11 +4,10 @@ export interface ITransactionFetcher { /** * Fetches the state of a {@link Transaction}. */ - getTransaction(txHash: IHash, hintSender?: IBech32Address, withResults?: boolean): Promise; + getTransaction(txHash: string): Promise; } export interface ISignature { hex(): string; } -export interface IHash { hex(): string; } export interface IBech32Address { bech32(): string; } export interface ITransactionValue { toString(): string; } export interface IAccountBalance { toString(): string; } diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index 7538fde69..d06702840 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,7 +1,7 @@ -import { IAccountBalance, IBech32Address, IChainID, IGasLimit, IHash, INonce, ITransactionValue } from "./interface"; +import { IAccountBalance, IBech32Address, ITransactionValue } from "./interface"; export interface IAccountOnNetwork { - nonce: INonce; + nonce: number; balance: IAccountBalance; } @@ -15,9 +15,9 @@ export interface INetworkConfig { export interface ITransactionOnNetwork { isCompleted: boolean; - hash: IHash; + hash: string; type: string; - value: ITransactionValue; + value: string; receiver: IBech32Address; sender: IBech32Address; data: Buffer; @@ -43,8 +43,8 @@ export interface IContractResults { } export interface IContractResultItem { - hash: IHash; - nonce: INonce; + hash: string; + nonce: number; receiver: IBech32Address; sender: IBech32Address; data: string; diff --git a/src/smartcontracts/resultsParser.spec.ts b/src/smartcontracts/resultsParser.spec.ts index f350fc5c4..32b26166e 100644 --- a/src/smartcontracts/resultsParser.spec.ts +++ b/src/smartcontracts/resultsParser.spec.ts @@ -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/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 f29306da6..d85851ae3 100644 --- a/src/testutils/mockProvider.ts +++ b/src/testutils/mockProvider.ts @@ -1,7 +1,6 @@ -import { IBech32Address, IHash } from "../interface"; +import { IBech32Address } 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"; @@ -65,7 +64,7 @@ export class MockProvider { mockGetTransactionWithAnyHashAsNotarizedWithOneResult(returnCodeAndData: string) { 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,7 +111,7 @@ 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({ @@ -124,18 +123,14 @@ export class MockProvider { ); this.mockTransactionTimeline(transaction, this.nextTransactionTimelinePoints); - return transaction.getHash(); + return transaction.getHash().hex(); } async simulateTransaction(_transaction: Transaction): Promise { return {}; } - async getTransaction( - txHash: IHash, - _hintSender?: IBech32Address, - _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 7798b0fdd..9f60a86d6 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,5 +1,5 @@ import { ProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; -import { IBech32Address, IHash } from "../interface"; +import { IBech32Address } from "../interface"; import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionOnNetwork, ITransactionStatus } from "../interfaceOfNetwork"; import { Query } from "../smartcontracts/query"; import { Transaction } from "../transaction"; @@ -11,9 +11,9 @@ export function createLocalnetProvider(): INetworkProvider { export interface INetworkProvider { getNetworkConfig(): Promise; getAccount(address: IBech32Address): 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/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); } } From 28ac2a92f17a53560915230f7fb3a050243a74aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 22:24:30 +0300 Subject: [PATCH 04/12] Remove interaction.withGasLimitComponents(). Not so helpful anymore (since NetworkConfig isn't a singleton anymore). --- src/smartcontracts/interaction.spec.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/smartcontracts/interaction.spec.ts b/src/smartcontracts/interaction.spec.ts index b330e9f46..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 () { From 5450326bf68f36b705c1ff9289f1538740566eab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 22:25:35 +0300 Subject: [PATCH 05/12] Remove interaction.withGasLimitComponents(). --- src/smartcontracts/interaction.ts | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/smartcontracts/interaction.ts b/src/smartcontracts/interaction.ts index 8e6c949ab..806596d5c 100644 --- a/src/smartcontracts/interaction.ts +++ b/src/smartcontracts/interaction.ts @@ -161,19 +161,6 @@ export class Interaction { 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 { this.gasPrice = gasPrice; return this; From c5f13692299bc19cd8e7629f381f59ca7c2feb71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 22:25:49 +0300 Subject: [PATCH 06/12] Use interface for Address. --- src/account.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/account.ts b/src/account.ts index b7bc4502d..9cef93cfb 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, IBech32Address, 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: IBech32Address = 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: IBech32Address) { this.address = address; } From 4aba162728da4a6e265808e8d2606d963ebe22b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrei=20B=C4=83ncioiu?= Date: Sun, 10 Apr 2022 22:51:23 +0300 Subject: [PATCH 07/12] Use interfaces where possible (on interaction / tx). --- src/smartcontracts/interaction.ts | 10 +++++----- src/transaction.ts | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/smartcontracts/interaction.ts b/src/smartcontracts/interaction.ts index 806596d5c..8d6b40dbc 100644 --- a/src/smartcontracts/interaction.ts +++ b/src/smartcontracts/interaction.ts @@ -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 { IBech32Address, IChainID, IGasLimit, IGasPrice } from "../interface"; +import { IBech32Address, 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; @@ -156,17 +156,17 @@ export class Interaction { return this; } - withGasLimit(gasLimit: GasLimit): Interaction { + withGasLimit(gasLimit: IGasLimit): Interaction { this.gasLimit = gasLimit; return this; } - 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; } diff --git a/src/transaction.ts b/src/transaction.ts index 9cea940bf..94d5008ae 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,5 +1,5 @@ import { BigNumber } from "bignumber.js"; -import { IBech32Address, IChainID, IGasLimit, IGasPrice, ISignature } from "./interface"; +import { IBech32Address, 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; } From 2895720cccdae804bcca75c1b3487e6ec118ad8a Mon Sep 17 00:00:00 2001 From: Andrei Bancioiu Date: Mon, 11 Apr 2022 10:25:19 +0300 Subject: [PATCH 08/12] Reference newer network-providers (dev-dependency). --- package-lock.json | 14 ++++----- package.json | 2 +- src/smartcontracts/resultsParser.spec.ts | 40 ++++++++++++------------ 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/package-lock.json b/package-lock.json index b39fe0ab4..ac82618b6 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/smartcontracts/resultsParser.spec.ts b/src/smartcontracts/resultsParser.spec.ts index 32b26166e..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"; @@ -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); From 8664274a7716288e363878ce4b5f6b15279b677c Mon Sep 17 00:00:00 2001 From: Andrei Bancioiu Date: Mon, 11 Apr 2022 11:40:23 +0300 Subject: [PATCH 09/12] Use interface for address in interaction. --- src/smartcontracts/interaction.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/smartcontracts/interaction.ts b/src/smartcontracts/interaction.ts index 8d6b40dbc..a52475aad 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"; @@ -142,14 +142,14 @@ export class Interaction { return this; } - withSingleESDTNFTTransfer(transfer: Balance, sender: Address) { + withSingleESDTNFTTransfer(transfer: Balance, sender: IBech32Address) { this.isWithSingleESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction([transfer], this); this.tokenTransfersSender = sender; return this; } - withMultiESDTNFTTransfer(transfers: Balance[], sender: Address) { + withMultiESDTNFTTransfer(transfers: Balance[], sender: IBech32Address) { this.isWithMultiESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction(transfers, this); this.tokenTransfersSender = sender; @@ -183,7 +183,7 @@ export class Interaction { /** * Sets the "caller" field on contract queries. */ - withQuerent(querent: Address): Interaction { + withQuerent(querent: IBech32Address): Interaction { this.querent = querent; return this; } From e48431cbddca4c73231f13c9e16e8bf5b6a47bed Mon Sep 17 00:00:00 2001 From: Andrei Bancioiu Date: Mon, 11 Apr 2022 14:40:27 +0300 Subject: [PATCH 10/12] Use interface instead of Address class. --- src/smartcontracts/nativeSerializer.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/smartcontracts/nativeSerializer.ts b/src/smartcontracts/nativeSerializer.ts index 8eb449ec1..feadaaeef 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 { IBech32Address } 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 | IBech32Address | { getAddress(): IBech32Address }; } 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): IBech32Address { + 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"); } From f8af8c7a403f5925a4f40f43801e8b49916b9f3b Mon Sep 17 00:00:00 2001 From: Andrei Bancioiu Date: Mon, 11 Apr 2022 15:26:23 +0300 Subject: [PATCH 11/12] Fix after review: renamed interface. --- src/account.ts | 6 +++--- src/interface.ts | 2 +- src/interfaceOfNetwork.ts | 12 ++++++------ src/smartcontracts/interaction.ts | 16 ++++++++-------- src/smartcontracts/interface.ts | 11 +++++------ src/smartcontracts/nativeSerializer.ts | 8 ++++---- src/smartcontracts/query.ts | 10 +++++----- src/smartcontracts/resultsParser.ts | 4 ++-- src/smartcontracts/smartContract.ts | 12 ++++++------ src/smartcontracts/typesystem/address.ts | 4 ++-- src/testutils/mockProvider.ts | 4 ++-- src/testutils/networkProviders.ts | 4 ++-- src/testutils/wallets.ts | 4 ++-- src/transaction.ts | 20 ++++++++++---------- 14 files changed, 58 insertions(+), 59 deletions(-) diff --git a/src/account.ts b/src/account.ts index 9cef93cfb..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, IBech32Address, 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: IBech32Address = 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: IBech32Address) { + constructor(address: IAddress) { this.address = address; } diff --git a/src/interface.ts b/src/interface.ts index fbfaf9cd1..07cbe8fa0 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -8,7 +8,7 @@ export interface ITransactionFetcher { } export interface ISignature { hex(): string; } -export interface IBech32Address { bech32(): string; } +export interface IAddress { bech32(): string; } export interface ITransactionValue { toString(): string; } export interface IAccountBalance { toString(): string; } export interface INonce { valueOf(): number; } diff --git a/src/interfaceOfNetwork.ts b/src/interfaceOfNetwork.ts index d06702840..a55f31613 100644 --- a/src/interfaceOfNetwork.ts +++ b/src/interfaceOfNetwork.ts @@ -1,4 +1,4 @@ -import { IAccountBalance, IBech32Address, ITransactionValue } from "./interface"; +import { IAccountBalance, IAddress, ITransactionValue } from "./interface"; export interface IAccountOnNetwork { nonce: number; @@ -18,8 +18,8 @@ export interface ITransactionOnNetwork { hash: string; type: string; value: string; - receiver: IBech32Address; - sender: IBech32Address; + receiver: IAddress; + sender: IAddress; data: Buffer; status: ITransactionStatus; receipt: ITransactionReceipt; @@ -45,8 +45,8 @@ export interface IContractResults { export interface IContractResultItem { hash: string; nonce: number; - receiver: IBech32Address; - sender: IBech32Address; + receiver: IAddress; + sender: IAddress; data: string; returnMessage: string; logs: ITransactionLogs; @@ -71,7 +71,7 @@ export interface ITransactionLogs { } export interface ITransactionEvent { - readonly address: IBech32Address; + readonly address: IAddress; readonly identifier: string; readonly topics: ITransactionEventTopic[]; readonly data: string; diff --git a/src/smartcontracts/interaction.ts b/src/smartcontracts/interaction.ts index a52475aad..7de11ebff 100644 --- a/src/smartcontracts/interaction.ts +++ b/src/smartcontracts/interaction.ts @@ -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 { IBech32Address, IChainID, IGasLimit, IGasPrice, INonce } from "../interface"; +import { IAddress, IChainID, IGasLimit, IGasPrice, INonce } from "../interface"; import { InteractionChecker } from "./interactionChecker"; /** @@ -17,7 +17,7 @@ import { InteractionChecker } from "./interactionChecker"; */ interface ISmartContractWithinInteraction { call({ func, args, value, gasLimit, receiver }: CallArguments): Transaction; - getAddress(): IBech32Address; + getAddress(): IAddress; getEndpoint(name: ContractFunction): EndpointDefinition; } @@ -37,13 +37,13 @@ export class Interaction { private gasLimit: IGasLimit = new GasLimit(0); private gasPrice: IGasPrice | undefined = undefined; private chainID: IChainID = ChainID.unspecified(); - private querent: IBech32Address = new Address(); + private querent: IAddress = new Address(); private isWithSingleESDTTransfer: boolean = false; private isWithSingleESDTNFTTransfer: boolean = false; private isWithMultiESDTNFTTransfer: boolean = false; private tokenTransfers: TokenTransfersWithinInteraction; - private tokenTransfersSender: IBech32Address = new Address(); + private tokenTransfersSender: IAddress = new Address(); constructor( contract: ISmartContractWithinInteraction, @@ -56,7 +56,7 @@ export class Interaction { this.tokenTransfers = new TokenTransfersWithinInteraction([], this); } - getContractAddress(): IBech32Address { + getContractAddress(): IAddress { return this.contract.getAddress(); } @@ -142,14 +142,14 @@ export class Interaction { return this; } - withSingleESDTNFTTransfer(transfer: Balance, sender: IBech32Address) { + withSingleESDTNFTTransfer(transfer: Balance, sender: IAddress) { this.isWithSingleESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction([transfer], this); this.tokenTransfersSender = sender; return this; } - withMultiESDTNFTTransfer(transfers: Balance[], sender: IBech32Address) { + withMultiESDTNFTTransfer(transfers: Balance[], sender: IAddress) { this.isWithMultiESDTNFTTransfer = true; this.tokenTransfers = new TokenTransfersWithinInteraction(transfers, this); this.tokenTransfersSender = sender; @@ -183,7 +183,7 @@ export class Interaction { /** * Sets the "caller" field on contract queries. */ - withQuerent(querent: IBech32Address): Interaction { + withQuerent(querent: IAddress): Interaction { this.querent = querent; return this; } diff --git a/src/smartcontracts/interface.ts b/src/smartcontracts/interface.ts index 2eeea3add..800e79add 100644 --- a/src/smartcontracts/interface.ts +++ b/src/smartcontracts/interface.ts @@ -1,12 +1,11 @@ import { Balance } from "../balance"; -import { IBech32Address, IChainID, IGasLimit, IGasPrice } from "../interface"; -import { IContractQueryResponse, ITransactionOnNetwork } from "../interfaceOfNetwork"; +import { IAddress, IChainID, IGasLimit, IGasPrice } from "../interface"; 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. @@ -15,7 +14,7 @@ export interface ISmartContract { /** * Gets the address of the Smart Contract. */ - getAddress(): IBech32Address; + getAddress(): IAddress; /** * Creates a {@link Transaction} for deploying the Smart Contract to the Network. @@ -58,7 +57,7 @@ export interface CallArguments { args?: TypedValue[]; value?: Balance; gasLimit: IGasLimit; - receiver?: IBech32Address; + receiver?: IAddress; gasPrice?: IGasPrice; chainID: IChainID; } @@ -67,7 +66,7 @@ export interface QueryArguments { func: ContractFunction; args?: TypedValue[]; value?: Balance; - caller?: IBech32Address + caller?: IAddress } export interface TypedOutcomeBundle { diff --git a/src/smartcontracts/nativeSerializer.ts b/src/smartcontracts/nativeSerializer.ts index feadaaeef..dc5f4831d 100644 --- a/src/smartcontracts/nativeSerializer.ts +++ b/src/smartcontracts/nativeSerializer.ts @@ -6,12 +6,12 @@ import { BalanceBuilder } from "../balanceBuilder"; import { Address } from "../address"; import { Code } from "./code"; import { ErrInvalidArgument, ErrTypeInferenceSystemRequiresRegularJavascriptObjects, ErrTypingSystem } from "../errors"; -import { IBech32Address } from "../interface"; +import { IAddress } from "../interface"; export namespace NativeTypes { export type NativeBuffer = Buffer | string | BalanceBuilder; export type NativeBytes = Code | Buffer | string | BalanceBuilder; - export type NativeAddress = string | Buffer | IBech32Address | { getAddress(): IBech32Address }; + export type NativeAddress = string | Buffer | IAddress | { getAddress(): IAddress }; } export namespace NativeSerializer { @@ -242,9 +242,9 @@ export namespace NativeSerializer { errorContext.convertError(native, "Buffer"); } - export function convertNativeToAddress(native: NativeTypes.NativeAddress, errorContext: ArgumentErrorContext): IBech32Address { + export function convertNativeToAddress(native: NativeTypes.NativeAddress, errorContext: ArgumentErrorContext): IAddress { if ((native).bech32) { - return native; + return native; } if ((native).getAddress) { return (native).getAddress(); diff --git a/src/smartcontracts/query.ts b/src/smartcontracts/query.ts index 81bc28801..5ca2754f2 100644 --- a/src/smartcontracts/query.ts +++ b/src/smartcontracts/query.ts @@ -3,18 +3,18 @@ import { Balance } from "../balance"; import { Address } from "../address"; import { TypedValue } from "./typesystem"; import { ArgSerializer } from "./argSerializer"; -import { IBech32Address, ITransactionValue } from "../interface"; +import { IAddress, ITransactionValue } from "../interface"; export class Query { - caller: IBech32Address; - address: IBech32Address; + caller: IAddress; + address: IAddress; func: ContractFunction; args: TypedValue[]; value: ITransactionValue; constructor(obj: { - caller?: IBech32Address, - address: IBech32Address, + caller?: IAddress, + address: IAddress, func: ContractFunction, args?: TypedValue[], value?: ITransactionValue diff --git a/src/smartcontracts/resultsParser.ts b/src/smartcontracts/resultsParser.ts index 794f630cd..f72c876c3 100644 --- a/src/smartcontracts/resultsParser.ts +++ b/src/smartcontracts/resultsParser.ts @@ -7,7 +7,7 @@ import { ArgSerializer } from "./argSerializer"; import { TypedOutcomeBundle, UntypedOutcomeBundle } from "./interface"; import { ReturnCode } from "./returnCode"; import { EndpointDefinition } from "./typesystem"; -import { IBech32Address } from "../interface"; +import { IAddress } from "../interface"; enum WellKnownEvents { OnTransactionCompleted = "completedTxEvent", @@ -216,7 +216,7 @@ export class ResultsParser { }; } - private createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs: ITransactionLogs, address: IBech32Address): UntypedOutcomeBundle | null { + private createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs: ITransactionLogs, address: IAddress): UntypedOutcomeBundle | null { let hexAddress = new Address(address.bech32()).hex(); let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent( diff --git a/src/smartcontracts/smartContract.ts b/src/smartcontracts/smartContract.ts index 29b8b8ea5..b29940bd6 100644 --- a/src/smartcontracts/smartContract.ts +++ b/src/smartcontracts/smartContract.ts @@ -14,7 +14,7 @@ import { bigIntToBuffer } from "./codec/utils"; import BigNumber from "bignumber.js"; import { Interaction } from "./interaction"; import { NativeSerializer } from "./nativeSerializer"; -import { IBech32Address, INonce } from "../interface"; +import { IAddress, INonce } from "../interface"; import { ErrContractHasNoAddress } from "../errors"; const createKeccakHash = require("keccak"); @@ -22,7 +22,7 @@ const createKeccakHash = require("keccak"); * An abstraction for deploying and interacting with Smart Contracts. */ export class SmartContract implements ISmartContract { - private address: IBech32Address = new Address(); + private address: IAddress = new Address(); private abi?: SmartContractAbi; /** @@ -43,7 +43,7 @@ export class SmartContract implements ISmartContract { /** * Create a SmartContract object by providing its address on the Network. */ - constructor({ address, abi }: { address?: IBech32Address, abi?: SmartContractAbi }) { + constructor({ address, abi }: { address?: IAddress, abi?: SmartContractAbi }) { this.address = address || new Address(); this.abi = abi; @@ -81,14 +81,14 @@ export class SmartContract implements ISmartContract { /** * Sets the address, as on Network. */ - setAddress(address: IBech32Address) { + setAddress(address: IAddress) { this.address = address; } /** * Gets the address, as on Network. */ - getAddress(): IBech32Address { + getAddress(): IAddress { return this.address; } @@ -210,7 +210,7 @@ export class SmartContract implements ISmartContract { * @param owner The owner of the Smart Contract * @param nonce The owner nonce used for the deployment transaction */ - static computeAddress(owner: IBech32Address, nonce: INonce): IBech32Address { + static computeAddress(owner: IAddress, nonce: INonce): IAddress { let initialPadding = Buffer.alloc(8, 0); let ownerPubkey = new Address(owner.bech32()).pubkey(); let shardSelector = ownerPubkey.slice(30); diff --git a/src/smartcontracts/typesystem/address.ts b/src/smartcontracts/typesystem/address.ts index ca54cd583..25a869840 100644 --- a/src/smartcontracts/typesystem/address.ts +++ b/src/smartcontracts/typesystem/address.ts @@ -1,5 +1,5 @@ import { Address } from "../../address"; -import { IBech32Address } from "../../interface"; +import { IAddress } from "../../interface"; import { PrimitiveType, PrimitiveValue } from "./types"; export class AddressType extends PrimitiveType { @@ -21,7 +21,7 @@ export class AddressValue extends PrimitiveValue { static ClassName = "AddressValue"; private readonly value: Address; - constructor(value: IBech32Address) { + constructor(value: IAddress) { super(new AddressType()); this.value = new Address(value.bech32()); } diff --git a/src/testutils/mockProvider.ts b/src/testutils/mockProvider.ts index d85851ae3..cd74fb7c1 100644 --- a/src/testutils/mockProvider.ts +++ b/src/testutils/mockProvider.ts @@ -1,4 +1,4 @@ -import { IBech32Address } from "../interface"; +import { IAddress } from "../interface"; import { Transaction, TransactionHash } from "../transaction"; import { Address } from "../address"; import { AsyncTimer } from "../asyncTimer"; @@ -102,7 +102,7 @@ export class MockProvider { } } - async getAccount(address: IBech32Address): Promise { + async getAccount(address: IAddress): Promise { let account = this.accounts.get(address.bech32()); if (account) { return account; diff --git a/src/testutils/networkProviders.ts b/src/testutils/networkProviders.ts index 9f60a86d6..ee3a836c1 100644 --- a/src/testutils/networkProviders.ts +++ b/src/testutils/networkProviders.ts @@ -1,5 +1,5 @@ import { ProxyNetworkProvider } from "@elrondnetwork/erdjs-network-providers"; -import { IBech32Address } from "../interface"; +import { IAddress } from "../interface"; import { IAccountOnNetwork, IContractQueryResponse, INetworkConfig, ITransactionOnNetwork, ITransactionStatus } from "../interfaceOfNetwork"; import { Query } from "../smartcontracts/query"; import { Transaction } from "../transaction"; @@ -10,7 +10,7 @@ export function createLocalnetProvider(): INetworkProvider { export interface INetworkProvider { getNetworkConfig(): Promise; - getAccount(address: IBech32Address): Promise; + getAccount(address: IAddress): Promise; getTransaction(txHash: string): Promise; getTransactionStatus(txHash: string): Promise; sendTransaction(tx: Transaction): Promise; diff --git a/src/testutils/wallets.ts b/src/testutils/wallets.ts index e758eb85e..e7fef128e 100644 --- a/src/testutils/wallets.ts +++ b/src/testutils/wallets.ts @@ -3,13 +3,13 @@ import * as fs from "fs"; import * as path from "path"; import { Account } from "../account"; import { Address } from "../address"; -import { IBech32Address } from "../interface"; +import { IAddress } from "../interface"; import { isOnBrowserTests } from "./utils"; import { UserSecretKey, UserSigner } from "@elrondnetwork/erdjs-walletcore" import { IAccountOnNetwork } from "../interfaceOfNetwork"; interface IAccountFetcher { - getAccount(address: IBech32Address): Promise; + getAccount(address: IAddress): Promise; } export async function loadAndSyncTestWallets(provider: IAccountFetcher): Promise> { diff --git a/src/transaction.ts b/src/transaction.ts index 94d5008ae..8bd857f4f 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -1,5 +1,5 @@ import { BigNumber } from "bignumber.js"; -import { IBech32Address, IChainID, IGasLimit, IGasPrice, INonce, ISignature } from "./interface"; +import { IAddress, IChainID, IGasLimit, IGasPrice, INonce, ISignature } from "./interface"; import { Address } from "./address"; import { Balance } from "./balance"; import { @@ -38,12 +38,12 @@ export class Transaction { /** * The address of the sender. */ - private sender: IBech32Address; + private sender: IAddress; /** * The address of the receiver. */ - private readonly receiver: IBech32Address; + private readonly receiver: IAddress; /** * The gas price to be used. @@ -102,8 +102,8 @@ export class Transaction { }: { nonce?: Nonce; value?: Balance; - receiver: IBech32Address; - sender?: IBech32Address; + receiver: IAddress; + sender?: IAddress; gasPrice?: IGasPrice; gasLimit: IGasLimit; data?: TransactionPayload; @@ -158,11 +158,11 @@ export class Transaction { this.value = value; } - getSender(): IBech32Address { + getSender(): IAddress { return this.sender; } - getReceiver(): IBech32Address { + getReceiver(): IAddress { return this.receiver; } @@ -217,7 +217,7 @@ export class Transaction { * * @param signedBy The address of the future signer */ - serializeForSigning(signedBy: IBech32Address): Buffer { + serializeForSigning(signedBy: IAddress): Buffer { // TODO: for appropriate tx.version, interpret tx.options accordingly and sign using the content / data hash let plain = this.toPlainObject(signedBy); // Make sure we never sign the transaction with another signature set up (useful when using the same method for verification) @@ -235,7 +235,7 @@ export class Transaction { * * @param sender The address of the sender (will be provided when called within the signing procedure) */ - toPlainObject(sender?: IBech32Address): any { + toPlainObject(sender?: IAddress): any { return { nonce: this.nonce.valueOf(), value: this.value.toString(), @@ -283,7 +283,7 @@ export class Transaction { * @param signature The signature, as computed by a signer. * @param signedBy The address of the signer. */ - applySignature(signature: ISignature, signedBy: IBech32Address) { + applySignature(signature: ISignature, signedBy: IAddress) { this.signature = signature; this.sender = signedBy; this.hash = TransactionHash.compute(this); From 916566db881b54051d491a0a0f8fa0411cc3e461 Mon Sep 17 00:00:00 2001 From: Andrei Bancioiu Date: Mon, 11 Apr 2022 16:05:01 +0300 Subject: [PATCH 12/12] Update changelog. --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) 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)