diff --git a/__tests__/functional/core-database/repositories/round-repository.test.ts b/__tests__/functional/core-database/repositories/round-repository.test.ts index 158ac7a381..0ceb1d6ac1 100644 --- a/__tests__/functional/core-database/repositories/round-repository.test.ts +++ b/__tests__/functional/core-database/repositories/round-repository.test.ts @@ -17,6 +17,10 @@ class DelegateWalletMock { this.voteBalance = voteBalance; } + public getPublicKey(): string { + return this.publicKey; + } + public getAttribute(key: string) { switch (key) { case "delegate.round": diff --git a/__tests__/functional/transaction-forging/__support__/index.ts b/__tests__/functional/transaction-forging/__support__/index.ts index 11e5cad428..705cec3fd5 100644 --- a/__tests__/functional/transaction-forging/__support__/index.ts +++ b/__tests__/functional/transaction-forging/__support__/index.ts @@ -81,14 +81,14 @@ export const tearDown = async (): Promise => { delete walletAttributes.delegate; } return { - publicKey: wallet.publicKey, - balance: wallet.balance, - nonce: wallet.nonce, + publicKey: wallet.getPublicKey(), + balance: wallet.getBalance(), + nonce: wallet.getNonce(), attributes: walletAttributes, }; }; const sortWallets = (a: Contracts.State.Wallet, b: Contracts.State.Wallet) => - a.publicKey!.localeCompare(b.publicKey!); + a.getPublicKey()!.localeCompare(b.getPublicKey()!); const allByPublicKey = walletRepository .allByPublicKey() diff --git a/__tests__/integration/core-api/__support__/setup.ts b/__tests__/integration/core-api/__support__/setup.ts index ba49384de1..f0f35ebb91 100644 --- a/__tests__/integration/core-api/__support__/setup.ts +++ b/__tests__/integration/core-api/__support__/setup.ts @@ -103,8 +103,8 @@ export const calculateRanks = async () => { .comparedTo(a.getAttribute("delegate.voteBalance")), ); - AppUtils.sortBy(delegateWallets, (wallet) => wallet.publicKey).forEach((delegate, i) => { - const wallet = walletRepository.findByPublicKey(delegate.publicKey!); + AppUtils.sortBy(delegateWallets, (wallet) => wallet.getPublicKey()).forEach((delegate, i) => { + const wallet = walletRepository.findByPublicKey(delegate.getPublicKey()!); wallet.setAttribute("delegate.rank", i + 1); walletRepository.index(wallet); diff --git a/__tests__/integration/core-api/controllers/locks.test.ts b/__tests__/integration/core-api/controllers/locks.test.ts index c97f990d60..de938f3bc7 100644 --- a/__tests__/integration/core-api/controllers/locks.test.ts +++ b/__tests__/integration/core-api/controllers/locks.test.ts @@ -35,7 +35,7 @@ beforeAll(() => { walletLocks[transaction.id] = { amount: Utils.BigNumber.make(n * 10), - recipientId: wallet.address, + recipientId: wallet.getAddress(), secretHash: transaction.id, expiration: j % 2 === 0 diff --git a/__tests__/integration/core-api/handlers/locks.test.ts b/__tests__/integration/core-api/handlers/locks.test.ts index 82200b7c5d..fc824d2a44 100644 --- a/__tests__/integration/core-api/handlers/locks.test.ts +++ b/__tests__/integration/core-api/handlers/locks.test.ts @@ -33,7 +33,7 @@ describe("API 2.0 - Locks", () => { for (let i = 1; i < 7; i++) { const wallet = walletRepository.findByAddress(Identities.Address.fromPassphrase(`${i}`)); - wallet.publicKey = Identities.PublicKey.fromPassphrase(`${i}`); + wallet.setPublicKey(Identities.PublicKey.fromPassphrase(`${i}`)); const transactions = Managers.configManager.get("genesisBlock").transactions.slice(i * 10, i * 10 + i + 1); @@ -44,7 +44,7 @@ describe("API 2.0 - Locks", () => { locks[transaction.id] = { amount: Utils.BigNumber.make(10 * (j + 1)), - recipientId: wallet.address, + recipientId: wallet.getAddress(), secretHash: transaction.id, expiration: { type: j % 2 === 0 ? 1 : 2, diff --git a/__tests__/integration/core-api/services/delegate-search-service.test.ts b/__tests__/integration/core-api/services/delegate-search-service.test.ts index cd80c5b21c..f333fc5ff2 100644 --- a/__tests__/integration/core-api/services/delegate-search-service.test.ts +++ b/__tests__/integration/core-api/services/delegate-search-service.test.ts @@ -80,14 +80,14 @@ describe("DelegateSearchService.getDelegate", () => { const wallet1 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret1")); wallet1.setAttribute("delegate", delegateAttribute1); walletRepository.index(wallet1); - const delegateResource1 = delegateSearchService.getDelegate(wallet1.address); + const delegateResource1 = delegateSearchService.getDelegate(wallet1.getAddress())!; - expect(delegateResource1.address).toBe(wallet1.address); + expect(delegateResource1.address).toBe(wallet1.getAddress()); }); it("should not get non-delegate wallet by address", () => { const wallet1 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret1")); - const delegateResource1 = delegateSearchService.getDelegate(wallet1.address); + const delegateResource1 = delegateSearchService.getDelegate(wallet1.getAddress()); expect(delegateResource1).toBe(undefined); }); diff --git a/__tests__/integration/core-api/services/lock-search-service.test.ts b/__tests__/integration/core-api/services/lock-search-service.test.ts index a9e46ade82..b7047e9337 100644 --- a/__tests__/integration/core-api/services/lock-search-service.test.ts +++ b/__tests__/integration/core-api/services/lock-search-service.test.ts @@ -1,6 +1,6 @@ -import { LockSearchService, Identifiers as ApiIdentifiers } from "@arkecosystem/core-api/src"; +import { Identifiers as ApiIdentifiers, LockSearchService } from "@arkecosystem/core-api/src"; import { Container, Contracts } from "@arkecosystem/core-kernel"; -import { Identities, Utils, Enums } from "@arkecosystem/crypto"; +import { Enums, Identities, Utils } from "@arkecosystem/crypto"; import { setUp } from "./__support__/setup"; @@ -127,7 +127,7 @@ describe("LockSearchService.getWalletLocksPage", () => { const locksPage = lockSearchService.getWalletLocksPage( { offset: 0, limit: 100 }, [{ property: "amount", direction: "asc" }], - wallet1.address, + wallet1.getAddress(), ); expect(locksPage.totalCount).toBe(2); @@ -144,7 +144,7 @@ describe("LockSearchService.getWalletLocksPage", () => { const locksPage = lockSearchService.getWalletLocksPage( { offset: 0, limit: 100 }, [{ property: "amount", direction: "asc" }], - wallet1.address, + wallet1.getAddress(), { amount: "1000" }, ); @@ -165,7 +165,7 @@ describe("LockSearchService.getWalletLocksPage", () => { const locksPage = lockSearchService.getWalletLocksPage( { offset: 0, limit: 100 }, [{ property: "amount", direction: "asc" }], - wallet1.address, + wallet1.getAddress(), ); expect(locksPage.totalCount).toBe(1); diff --git a/__tests__/integration/core-api/services/wallet-search-service.test.ts b/__tests__/integration/core-api/services/wallet-search-service.test.ts index 12a4ac8fdc..c4e9660bd0 100644 --- a/__tests__/integration/core-api/services/wallet-search-service.test.ts +++ b/__tests__/integration/core-api/services/wallet-search-service.test.ts @@ -1,4 +1,4 @@ -import { WalletSearchService, Identifiers as ApiIdentifiers } from "@arkecosystem/core-api/src"; +import { Identifiers as ApiIdentifiers, WalletSearchService } from "@arkecosystem/core-api/src"; import { Container, Contracts } from "@arkecosystem/core-kernel"; import { Identities, Utils } from "@arkecosystem/crypto"; @@ -22,9 +22,9 @@ beforeEach(async () => { describe("WalletSearchService.getWallet", () => { it("should get wallet by address", async () => { const wallet = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret")); - const walletResource = walletSearchService.getWallet(wallet.address); + const walletResource = walletSearchService.getWallet(wallet.getAddress())!; - expect(walletResource.address).toEqual(wallet.address); + expect(walletResource.address).toEqual(wallet.getAddress()); }); it("should not get wallet by address", async () => { @@ -36,9 +36,9 @@ describe("WalletSearchService.getWallet", () => { it("should get wallet by publicKey", async () => { const wallet = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret")); - const walletResource = walletSearchService.getWallet(Identities.PublicKey.fromPassphrase("secret")); + const walletResource = walletSearchService.getWallet(Identities.PublicKey.fromPassphrase("secret"))!; - expect(walletResource.address).toBe(wallet.address); + expect(walletResource.address).toBe(wallet.getAddress()); }); it("should not get wallet by publicKey", async () => { @@ -52,9 +52,9 @@ describe("WalletSearchService.getWallet", () => { const wallet = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret")); wallet.setAttribute("delegate.username", "test_username"); walletRepository.index(wallet); - const walletResource = walletSearchService.getWallet("test_username"); + const walletResource = walletSearchService.getWallet("test_username")!; - expect(walletResource.address).toBe(wallet.address); + expect(walletResource.address).toBe(wallet.getAddress()); }); it("should not get wallet by username", async () => { @@ -75,18 +75,18 @@ describe("WalletSearchService.getWalletsPage", () => { const wallet4 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret4")); const wallet5 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret5")); - wallet1.balance = Utils.BigNumber.make("100"); - wallet2.balance = Utils.BigNumber.make("200"); - wallet3.balance = Utils.BigNumber.make("300"); - wallet4.balance = Utils.BigNumber.make("40"); - wallet5.balance = Utils.BigNumber.make("50"); + wallet1.setBalance(Utils.BigNumber.make("100")); + wallet2.setBalance(Utils.BigNumber.make("200")); + wallet3.setBalance(Utils.BigNumber.make("300")); + wallet4.setBalance(Utils.BigNumber.make("40")); + wallet5.setBalance(Utils.BigNumber.make("50")); const page = walletSearchService.getWalletsPage({ limit: 3, offset: 0 }, []); expect(page.results.length).toBe(3); - expect(page.results[0].address).toBe(wallet3.address); - expect(page.results[1].address).toBe(wallet2.address); - expect(page.results[2].address).toBe(wallet1.address); + expect(page.results[0].address).toBe(wallet3.getAddress()); + expect(page.results[1].address).toBe(wallet2.getAddress()); + expect(page.results[2].address).toBe(wallet1.getAddress()); expect(page.totalCount).toBe(5); }); @@ -97,17 +97,17 @@ describe("WalletSearchService.getWalletsPage", () => { const wallet4 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret4")); const wallet5 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret5")); - wallet1.balance = Utils.BigNumber.make("100"); - wallet2.balance = Utils.BigNumber.make("200"); - wallet3.balance = Utils.BigNumber.make("300"); - wallet4.balance = Utils.BigNumber.make("40"); - wallet5.balance = Utils.BigNumber.make("50"); + wallet1.setBalance(Utils.BigNumber.make("100")); + wallet2.setBalance(Utils.BigNumber.make("200")); + wallet3.setBalance(Utils.BigNumber.make("300")); + wallet4.setBalance(Utils.BigNumber.make("40")); + wallet5.setBalance(Utils.BigNumber.make("50")); const page = walletSearchService.getWalletsPage({ limit: 3, offset: 3 }, []); expect(page.results.length).toBe(2); - expect(page.results[0].address).toBe(wallet5.address); - expect(page.results[1].address).toBe(wallet4.address); + expect(page.results[0].address).toBe(wallet5.getAddress()); + expect(page.results[1].address).toBe(wallet4.getAddress()); expect(page.totalCount).toBe(5); }); @@ -118,18 +118,18 @@ describe("WalletSearchService.getWalletsPage", () => { const wallet4 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret4")); const wallet5 = walletRepository.findByPublicKey(Identities.PublicKey.fromPassphrase("secret5")); - wallet1.balance = Utils.BigNumber.make("100"); - wallet2.balance = Utils.BigNumber.make("200"); - wallet3.balance = Utils.BigNumber.make("300"); - wallet4.balance = Utils.BigNumber.make("40"); - wallet5.balance = Utils.BigNumber.make("50"); + wallet1.setBalance(Utils.BigNumber.make("100")); + wallet2.setBalance(Utils.BigNumber.make("200")); + wallet3.setBalance(Utils.BigNumber.make("300")); + wallet4.setBalance(Utils.BigNumber.make("40")); + wallet5.setBalance(Utils.BigNumber.make("50")); const page = walletSearchService.getWalletsPage({ limit: 5, offset: 0 }, [], { balance: { from: "100" } }); expect(page.results.length).toBe(3); - expect(page.results[0].address).toBe(wallet3.address); - expect(page.results[1].address).toBe(wallet2.address); - expect(page.results[2].address).toBe(wallet1.address); + expect(page.results[0].address).toBe(wallet3.getAddress()); + expect(page.results[1].address).toBe(wallet2.getAddress()); + expect(page.results[2].address).toBe(wallet1.getAddress()); expect(page.totalCount).toBe(3); }); }); @@ -142,18 +142,18 @@ describe("WalletSearchService.getActiveWalletsPage", () => { const wallet4 = walletRepository.findByAddress(Identities.Address.fromPassphrase("secret4")); const wallet5 = walletRepository.findByAddress(Identities.Address.fromPassphrase("secret5")); - wallet1.balance = Utils.BigNumber.make("100"); - wallet2.balance = Utils.BigNumber.make("200"); - wallet3.balance = Utils.BigNumber.make("300"); - wallet4.balance = Utils.BigNumber.make("400"); - wallet5.balance = Utils.BigNumber.make("500"); + wallet1.setBalance(Utils.BigNumber.make("100")); + wallet2.setBalance(Utils.BigNumber.make("200")); + wallet3.setBalance(Utils.BigNumber.make("300")); + wallet4.setBalance(Utils.BigNumber.make("400")); + wallet5.setBalance(Utils.BigNumber.make("500")); const page = walletSearchService.getActiveWalletsPage({ offset: 0, limit: 100 }, [ { property: "balance", direction: "asc" }, ]); expect(page.totalCount).toBe(2); - expect(page.results[0].address).toBe(wallet1.address); - expect(page.results[1].address).toBe(wallet2.address); + expect(page.results[0].address).toBe(wallet1.getAddress()); + expect(page.results[1].address).toBe(wallet2.getAddress()); }); }); diff --git a/__tests__/integration/core-state/__support__/utils.ts b/__tests__/integration/core-state/__support__/utils.ts index fd82a1ba12..edb4d63c63 100644 --- a/__tests__/integration/core-state/__support__/utils.ts +++ b/__tests__/integration/core-state/__support__/utils.ts @@ -11,7 +11,7 @@ export const getExpectedVoteBalances = ( const publicKey = wallet.getAttribute("vote"); const voteBalance = wallet .getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO) - .plus(wallet.balance) + .plus(wallet.getBalance()) .plus(expectedVoteBalances[publicKey] ?? Utils.BigNumber.ZERO); if (voteBalance.isZero()) { @@ -34,8 +34,8 @@ export const getActualVoteBalances = ( if (wallet.hasAttribute("delegate.voteBalance")) { const voteBalance = wallet.getAttribute("delegate.voteBalance"); if (!voteBalance.isZero()) { - AppUtils.assert.defined(wallet.publicKey); - actualVoteBalances[wallet.publicKey] = voteBalance; + AppUtils.assert.defined(wallet.getPublicKey()); + actualVoteBalances[wallet.getPublicKey()!] = voteBalance; } } } diff --git a/__tests__/unit/core-api/__support__/app.ts b/__tests__/unit/core-api/__support__/app.ts index 03df37bfd3..4cc7bfe620 100644 --- a/__tests__/unit/core-api/__support__/app.ts +++ b/__tests__/unit/core-api/__support__/app.ts @@ -45,8 +45,8 @@ export const buildSenderWallet = (app: Application, passphrase: string | null = Identities.Address.fromPassphrase(passphrase ? passphrase : passphrases[0]), ); - wallet.publicKey = Identities.PublicKey.fromPassphrase(passphrase ? passphrase : passphrases[0]); - wallet.balance = Utils.BigNumber.make(7527654310); + wallet.setPublicKey(Identities.PublicKey.fromPassphrase(passphrase ? passphrase : passphrases[0])); + wallet.setBalance(Utils.BigNumber.make(7527654310)); return wallet; }; diff --git a/__tests__/unit/core-api/resources/block-with-transactions.test.ts b/__tests__/unit/core-api/resources/block-with-transactions.test.ts index 618745f943..1f69ed5926 100644 --- a/__tests__/unit/core-api/resources/block-with-transactions.test.ts +++ b/__tests__/unit/core-api/resources/block-with-transactions.test.ts @@ -151,13 +151,15 @@ let mockBlockchainService; beforeEach(() => { mockWallet = { - address: "ANRNMPjQjJGVsVbyeqwShcxKTidYJ2S1Hm", - publicKey: "021770413ad01c60b94e1d3ed44c00e0145fe7897e40f5f6265e220f4e65cf427f", - + getAddress: () => { + return "ANRNMPjQjJGVsVbyeqwShcxKTidYJ2S1Hm"; + }, + getPublicKey: () => { + return "021770413ad01c60b94e1d3ed44c00e0145fe7897e40f5f6265e220f4e65cf427f"; + }, hasAttribute: () => { return true; }, - getAttribute: () => { return "genesis_13"; }, diff --git a/__tests__/unit/core-api/resources/transaction-with-blocks.test.ts b/__tests__/unit/core-api/resources/transaction-with-blocks.test.ts index 4e92fb0240..c50aaf2ed5 100644 --- a/__tests__/unit/core-api/resources/transaction-with-blocks.test.ts +++ b/__tests__/unit/core-api/resources/transaction-with-blocks.test.ts @@ -134,7 +134,7 @@ beforeEach(() => { mockWalletRepository = { findByPublicKey: () => { return { - address: "D8791H5uhZcg1tJmpryVUFanvLth52AmrJ", + getAddress: jest.fn().mockReturnValue("D8791H5uhZcg1tJmpryVUFanvLth52AmrJ"), }; }, }; diff --git a/__tests__/unit/core-api/services/delegate-search-service.test.ts b/__tests__/unit/core-api/services/delegate-search-service.test.ts index ab4de336e0..8faaebb1ff 100644 --- a/__tests__/unit/core-api/services/delegate-search-service.test.ts +++ b/__tests__/unit/core-api/services/delegate-search-service.test.ts @@ -47,7 +47,7 @@ describe("DelegateSearchService", () => { describe("getDelegate", () => { it("should return delegate by wallet address", () => { const delegate = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - delegate.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + delegate.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); delegate.setAttribute("delegate", { username: "delegate_username", @@ -67,7 +67,7 @@ describe("DelegateSearchService", () => { it("should return delegate by wallet address with produced blocks", () => { const delegate = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - delegate.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + delegate.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); delegate.setAttribute("delegate", { username: "delegate_username", @@ -92,7 +92,7 @@ describe("DelegateSearchService", () => { it("should return undefined if walled is not delegate", () => { const delegate = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - delegate.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + delegate.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); walletRepository.findByAddress = jest.fn().mockReturnValue(delegate); @@ -103,7 +103,7 @@ describe("DelegateSearchService", () => { describe("getDelegatesPage", () => { it("should return results with delegate", () => { const delegate = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - delegate.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + delegate.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); delegate.setAttribute("delegate", { username: "delegate_username", @@ -134,7 +134,7 @@ describe("DelegateSearchService", () => { it("should return empty array if all tested criterias are false", () => { const delegate = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - delegate.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + delegate.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); delegate.setAttribute("delegate", { username: "delegate_username", diff --git a/__tests__/unit/core-api/services/lock-search-service.test.ts b/__tests__/unit/core-api/services/lock-search-service.test.ts index 5daf6e3b7d..ad03ed24fd 100644 --- a/__tests__/unit/core-api/services/lock-search-service.test.ts +++ b/__tests__/unit/core-api/services/lock-search-service.test.ts @@ -46,7 +46,7 @@ describe("LockSearchService", () => { describe("getLock", () => { it("should return lock by wallet", () => { const walletWithLock = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - walletWithLock.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + walletWithLock.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); walletWithLock.setAttribute("htlc", { locks: Locks.walletLockAttributes, @@ -78,7 +78,7 @@ describe("LockSearchService", () => { describe("getLocksPage", () => { beforeEach(() => { const walletWithLock = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - walletWithLock.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + walletWithLock.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); walletWithLock.setAttribute("htlc", { locks: Locks.walletLockAttributes, @@ -130,7 +130,7 @@ describe("LockSearchService", () => { describe("getWalletLocksPage", () => { beforeEach(() => { const walletWithLock = new Wallets.Wallet("ANBkoGqWeTSiaEVgVzSKZd3jS7UWzv9PSo", attributeMap); - walletWithLock.publicKey = "03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"; + walletWithLock.setPublicKey("03287bfebba4c7881a0509717e71b34b63f31e40021c321f89ae04f84be6d6ac37"); walletWithLock.setAttribute("htlc", { locks: Locks.walletLockAttributes, diff --git a/__tests__/unit/core-api/services/wallet-search-service.test.ts b/__tests__/unit/core-api/services/wallet-search-service.test.ts index 700b5411cf..4864f87f00 100644 --- a/__tests__/unit/core-api/services/wallet-search-service.test.ts +++ b/__tests__/unit/core-api/services/wallet-search-service.test.ts @@ -34,10 +34,18 @@ beforeEach(() => { }); const wallet = { - address: "APTzMNCTPsDj6VcL8egi2weXJFgHGmCZGp", - publicKey: "028fe98e42e159f2450a52371dfb23ae69a39fc5fee6545690b7f51bfcee933357", - balance: Utils.BigNumber.make("5972178214140"), - nonce: Utils.BigNumber.make("1"), + getAddress: () => { + return "APTzMNCTPsDj6VcL8egi2weXJFgHGmCZGp"; + }, + getPublicKey: () => { + return "028fe98e42e159f2450a52371dfb23ae69a39fc5fee6545690b7f51bfcee933357"; + }, + getBalance: () => { + return Utils.BigNumber.make("5972178214140"); + }, + getNonce: () => { + return Utils.BigNumber.make("1"); + }, getAttributes: () => ({ delegate: { username: "binance_staking", @@ -70,10 +78,10 @@ const wallet = { }; const walletResource = { - address: wallet.address, - publicKey: wallet.publicKey, - balance: wallet.balance, - nonce: wallet.nonce, + address: wallet.getAddress(), + publicKey: wallet.getPublicKey(), + balance: wallet.getBalance(), + nonce: wallet.getNonce(), attributes: wallet.getAttributes(), }; @@ -83,10 +91,10 @@ describe("WalletSearchService", () => { walletRepository.hasByAddress.mockReturnValueOnce(true); walletRepository.findByAddress.mockReturnValueOnce(wallet as any); - const result = walletSearchService.getWallet(wallet.address); + const result = walletSearchService.getWallet(wallet.getAddress()); - expect(walletRepository.hasByAddress).toBeCalledWith(wallet.address); - expect(walletRepository.findByAddress).toBeCalledWith(wallet.address); + expect(walletRepository.hasByAddress).toBeCalledWith(wallet.getAddress()); + expect(walletRepository.findByAddress).toBeCalledWith(wallet.getAddress()); expect(result).toEqual(walletResource); }); @@ -95,10 +103,10 @@ describe("WalletSearchService", () => { walletRepository.hasByPublicKey.mockReturnValueOnce(true); walletRepository.findByPublicKey.mockReturnValueOnce(wallet as any); - const result = walletSearchService.getWallet(wallet.publicKey); + const result = walletSearchService.getWallet(wallet.getPublicKey()); - expect(walletRepository.hasByPublicKey).toBeCalledWith(wallet.publicKey); - expect(walletRepository.findByPublicKey).toBeCalledWith(wallet.publicKey); + expect(walletRepository.hasByPublicKey).toBeCalledWith(wallet.getPublicKey()); + expect(walletRepository.findByPublicKey).toBeCalledWith(wallet.getPublicKey()); expect(result).toEqual(walletResource); }); diff --git a/__tests__/unit/core-blockchain/processor/block-processor.test.ts b/__tests__/unit/core-blockchain/processor/block-processor.test.ts index 077d39479d..0370b17685 100644 --- a/__tests__/unit/core-blockchain/processor/block-processor.test.ts +++ b/__tests__/unit/core-blockchain/processor/block-processor.test.ts @@ -307,7 +307,9 @@ describe("BlockProcessor", () => { .mockReturnValueOnce(generatorWallet) .mockReturnValueOnce(generatorWallet); const notBlockGenerator = { - publicKey: "02ff171adaef486b7db9fc160b28433d20cf43163d56fd28fee72145f0d5219a4b", + getPublicKey: () => { + return "02ff171adaef486b7db9fc160b28433d20cf43163d56fd28fee72145f0d5219a4b"; + }, }; const activeDelegatesWithoutGenerator = []; diff --git a/__tests__/unit/core-blockchain/processor/handlers/unchained-handler.test.ts b/__tests__/unit/core-blockchain/processor/handlers/unchained-handler.test.ts index 1b631956b0..b0acdb66a5 100644 --- a/__tests__/unit/core-blockchain/processor/handlers/unchained-handler.test.ts +++ b/__tests__/unit/core-blockchain/processor/handlers/unchained-handler.test.ts @@ -71,15 +71,17 @@ describe("UnchainedHandler", () => { }, }; blockchain.getLastBlock = jest.fn().mockReturnValueOnce(lastBlock); - roundState.getActiveDelegates = jest - .fn() - .mockResolvedValueOnce( - [ - block.data.generatorPublicKey, - "02aea83a44f1d6b073e5bcffb4176bbe3c51dcd0e96a793a88f3a6135600224adf", - "03a3c6fd74a23fbe1e02f08d9c626ebb255b48de7ba8c283ee27c9303be81a2933", - ].map((publicKey) => ({ publicKey })), - ); + roundState.getActiveDelegates = jest.fn().mockResolvedValueOnce( + [ + block.data.generatorPublicKey, + "02aea83a44f1d6b073e5bcffb4176bbe3c51dcd0e96a793a88f3a6135600224adf", + "03a3c6fd74a23fbe1e02f08d9c626ebb255b48de7ba8c283ee27c9303be81a2933", + ].map((publicKey) => ({ + getPublicKey: () => { + return publicKey; + }, + })), + ); const result = await unchainedHandler.execute(block as Interfaces.IBlock); @@ -100,14 +102,16 @@ describe("UnchainedHandler", () => { }, }; blockchain.getLastBlock = jest.fn().mockReturnValueOnce(lastBlock); - roundState.getActiveDelegates = jest - .fn() - .mockResolvedValueOnce( - [ - "02aea83a44f1d6b073e5bcffb4176bbe3c51dcd0e96a793a88f3a6135600224adf", - "03a3c6fd74a23fbe1e02f08d9c626ebb255b48de7ba8c283ee27c9303be81a2933", - ].map((publicKey) => ({ publicKey })), - ); + roundState.getActiveDelegates = jest.fn().mockResolvedValueOnce( + [ + "02aea83a44f1d6b073e5bcffb4176bbe3c51dcd0e96a793a88f3a6135600224adf", + "03a3c6fd74a23fbe1e02f08d9c626ebb255b48de7ba8c283ee27c9303be81a2933", + ].map((publicKey) => ({ + getPublicKey: () => { + return publicKey; + }, + })), + ); const result = await unchainedHandler.execute(block as Interfaces.IBlock); diff --git a/__tests__/unit/core-database/transaction-filter.test.ts b/__tests__/unit/core-database/transaction-filter.test.ts index 494103368b..04668f37bf 100644 --- a/__tests__/unit/core-database/transaction-filter.test.ts +++ b/__tests__/unit/core-database/transaction-filter.test.ts @@ -1,7 +1,6 @@ -import { Container } from "@arkecosystem/core-kernel"; -import { Enums, Utils } from "@arkecosystem/crypto"; - -import { TransactionFilter } from "../../../packages/core-database/src/transaction-filter"; +import { TransactionFilter } from "@packages/core-database/src/transaction-filter"; +import { Container } from "@packages/core-kernel"; +import { Enums, Utils } from "@packages/crypto"; const walletRepository = { findByAddress: jest.fn(), @@ -27,8 +26,16 @@ describe("TransactionFilter.getExpression", () => { describe("TransactionCriteria.address", () => { it("should compare senderPublicKey, recipientId, multipayment recipientId, delegate registration sender", async () => { walletRepository.findByAddress - .mockReturnValueOnce({ publicKey: "456" }) - .mockReturnValueOnce({ publicKey: "456" }); + .mockReturnValueOnce({ + getPublicKey: () => { + return "456"; + }, + }) + .mockReturnValueOnce({ + getPublicKey: () => { + return "456"; + }, + }); const transactionFilter = container.resolve(TransactionFilter); const expression = await transactionFilter.getExpression({ address: "123" }); @@ -84,7 +91,9 @@ describe("TransactionFilter.getExpression", () => { describe("TransactionCriteria.senderId", () => { it("should compare senderPublicKey using equal expression", async () => { walletRepository.findByAddress.mockReturnValueOnce({ - publicKey: "456", + getPublicKey: () => { + return "456"; + }, }); const transactionFilter = container.resolve(TransactionFilter); @@ -106,7 +115,9 @@ describe("TransactionFilter.getExpression", () => { describe("TransactionCriteria.recipientId", () => { it("should compare using equal expression and include multipayment and include delegate registration transaction", async () => { walletRepository.findByAddress.mockReturnValueOnce({ - publicKey: "456", + getPublicKey: () => { + return "456"; + }, }); const transactionFilter = container.resolve(TransactionFilter); diff --git a/__tests__/unit/core-forger/__utils__/calculate-active-delegates.ts b/__tests__/unit/core-forger/__utils__/calculate-active-delegates.ts index ead617dfcb..1dfd7888ee 100644 --- a/__tests__/unit/core-forger/__utils__/calculate-active-delegates.ts +++ b/__tests__/unit/core-forger/__utils__/calculate-active-delegates.ts @@ -11,7 +11,7 @@ export const calculateActiveDelegates = () => { new Services.Attributes.AttributeMap(new Services.Attributes.AttributeSet()), ); - wallet.publicKey = Identities.PublicKey.fromPassphrase(address); + wallet.setPublicKey(Identities.PublicKey.fromPassphrase(address)); // @ts-ignore wallet.delegate = { username: `Username: ${address}` }; // @ts-ignore diff --git a/__tests__/unit/core-forger/delegate-tracker.test.ts b/__tests__/unit/core-forger/delegate-tracker.test.ts index 0b2410b136..10b2f3a089 100644 --- a/__tests__/unit/core-forger/delegate-tracker.test.ts +++ b/__tests__/unit/core-forger/delegate-tracker.test.ts @@ -60,7 +60,7 @@ describe("DelegateTracker", () => { expect(loggerDebug).toHaveBeenCalledWith( `Next Forgers: ${JSON.stringify( - activeDelegates.slice(2, 7).map((delegate: Wallet) => delegate.publicKey), + activeDelegates.slice(2, 7).map((delegate: Wallet) => delegate.getPublicKey()), )}`, ); diff --git a/__tests__/unit/core-magistrate-transactions/__support__/app.ts b/__tests__/unit/core-magistrate-transactions/__support__/app.ts index 3ef77d37f7..b3e09d8119 100644 --- a/__tests__/unit/core-magistrate-transactions/__support__/app.ts +++ b/__tests__/unit/core-magistrate-transactions/__support__/app.ts @@ -201,8 +201,8 @@ export const buildSenderWallet = (app: Application): Contracts.State.Wallet => { Identities.Address.fromPassphrase(passphrases[0]), ); - wallet.publicKey = Identities.PublicKey.fromPassphrase(passphrases[0]); - wallet.balance = Utils.BigNumber.make(7527654310); + wallet.setPublicKey(Identities.PublicKey.fromPassphrase(passphrases[0])); + wallet.setBalance(Utils.BigNumber.make(7527654310)); return wallet; }; @@ -225,7 +225,7 @@ export const buildSecondSignatureWallet = (factoryBuilder: FactoryBuilder): Wall }) .make(); - wallet.balance = Utils.BigNumber.make(7527654310); + wallet.setBalance(Utils.BigNumber.make(7527654310)); wallet.setAttribute("secondPublicKey", "038082dad560a22ea003022015e3136b21ef1ffd9f2fd50049026cbe8e2258ca17"); return wallet; @@ -242,8 +242,8 @@ export const buildMultiSignatureWallet = (): Wallets.Wallet => { }; const wallet = new Wallets.Wallet(Identities.Address.fromMultiSignatureAsset(multiSignatureAsset), knownAttributes); - wallet.publicKey = Identities.PublicKey.fromMultiSignatureAsset(multiSignatureAsset); - wallet.balance = Utils.BigNumber.make(100390000000); + wallet.setPublicKey(Identities.PublicKey.fromMultiSignatureAsset(multiSignatureAsset)); + wallet.setBalance(Utils.BigNumber.make(100390000000)); wallet.setAttribute("multiSignature", multiSignatureAsset); return wallet; diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts index 45ac04e78c..5bcc851e4a 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-registration.test.ts @@ -286,7 +286,7 @@ describe("BusinessRegistration", () => { }); it("should throw if wallet has insufficient balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(bridgechainRegistrationTransaction, senderWallet), ).rejects.toThrowError(InsufficientBalanceError); @@ -301,7 +301,7 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainRegistrationTransaction); @@ -310,7 +310,7 @@ describe("BusinessRegistration", () => { .bridgechainAsset, ).toEqual(bridgechainRegistrationAsset); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(bridgechainRegistrationTransaction.data.amount) .minus(bridgechainRegistrationTransaction.data.fee), @@ -324,7 +324,7 @@ describe("BusinessRegistration", () => { }); it("should be ok without custom wallet repository", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainRegistrationTransaction); @@ -333,7 +333,7 @@ describe("BusinessRegistration", () => { .bridgechainAsset, ).toEqual(bridgechainRegistrationAsset); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(bridgechainRegistrationTransaction.data.amount) .minus(bridgechainRegistrationTransaction.data.fee), @@ -349,7 +349,7 @@ describe("BusinessRegistration", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainRegistrationTransaction); @@ -364,11 +364,11 @@ describe("BusinessRegistration", () => { senderWallet.hasAttribute("business.bridgechains")[bridgechainRegistrationAsset.genesisHash], ).toBeUndefined(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); it("should be ok without custom wallet repository", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainRegistrationTransaction); @@ -383,7 +383,7 @@ describe("BusinessRegistration", () => { senderWallet.hasAttribute("business.bridgechains")[bridgechainRegistrationAsset.genesisHash], ).toBeUndefined(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); }); }); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts index 84b953ab7d..81ffcccc17 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-resignation.test.ts @@ -26,7 +26,7 @@ import { Mempool } from "@packages/core-transaction-pool"; import { InsufficientBalanceError } from "@packages/core-transactions/dist/errors"; import { TransactionHandler } from "@packages/core-transactions/src/handlers"; import { TransactionHandlerRegistry } from "@packages/core-transactions/src/handlers/handler-registry"; -import {Crypto, Interfaces, Managers, Transactions, Utils} from "@packages/crypto"; +import { Crypto, Interfaces, Managers, Transactions, Utils } from "@packages/crypto"; import { configManager } from "@packages/crypto/src/managers"; import _ from "lodash"; @@ -234,7 +234,7 @@ describe("BusinessRegistration", () => { }); it("should throw if wallet has insufficient balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(bridgechainResignationTransaction, senderWallet), ).rejects.toThrowError(InsufficientBalanceError); @@ -259,7 +259,7 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainResignationTransaction); @@ -267,7 +267,7 @@ describe("BusinessRegistration", () => { senderWallet.getAttribute("business.bridgechains")[bridgechainRegistrationAsset.genesisHash].resigned, ).toBeTrue(); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(bridgechainResignationTransaction.data.amount) .minus(bridgechainResignationTransaction.data.fee), @@ -283,7 +283,7 @@ describe("BusinessRegistration", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainResignationTransaction); @@ -297,7 +297,7 @@ describe("BusinessRegistration", () => { senderWallet.getAttribute("business.bridgechains")[bridgechainRegistrationAsset.genesisHash].resigned, ).toBeFalse(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); it("should throw if transaction asset is missing", async () => { diff --git a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts index 93a1fb244d..a2200910b5 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/bridgechain-update.test.ts @@ -24,7 +24,7 @@ import { BridgechainRegistrationTransactionHandler, BridgechainUpdateTransactionHandler, BusinessRegistrationTransactionHandler, - EntityTransactionHandler + EntityTransactionHandler, } from "@packages/core-magistrate-transactions/src/handlers"; import { Wallets } from "@packages/core-state"; import { StateStore } from "@packages/core-state/src/stores/state"; @@ -126,7 +126,7 @@ describe("BusinessRegistration", () => { .build(); senderWallet.setAttribute("business.businessAsset", businessRegistrationAsset); - senderWallet.nonce = Utils.BigNumber.make("1"); + senderWallet.setNonce(Utils.BigNumber.make("1")); const businessAttributes = senderWallet.getAttribute("business"); @@ -305,7 +305,7 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(bridgechainUpdateTransaction); @@ -320,7 +320,7 @@ describe("BusinessRegistration", () => { ...bridgechainUpdateAssetClone, }); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(bridgechainUpdateTransaction.data.amount) .minus(bridgechainUpdateTransaction.data.fee), @@ -343,7 +343,7 @@ describe("BusinessRegistration", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); const bridgechainUpdateAssetClone = Object.assign({}, bridgechainUpdateAsset); delete bridgechainUpdateAssetClone.bridgechainId; @@ -352,7 +352,7 @@ describe("BusinessRegistration", () => { ...bridgechainRegistrationAsset, ...bridgechainUpdateAssetClone, }; - senderWallet.nonce = Utils.BigNumber.make("2"); + senderWallet.setNonce(Utils.BigNumber.make("2")); const secondBridgechainUpdateAsset: IBridgechainUpdateAsset = { bridgechainId: bridgechainRegistrationAsset.genesisHash, @@ -404,7 +404,7 @@ describe("BusinessRegistration", () => { ...bridgechainUpdateAssetClone, }); - expect(senderWallet.balance).toEqual(senderBalance); + expect(senderWallet.getBalance()).toEqual(senderBalance); }); }); }); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts index f90ff58dd7..a62e96bd85 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-registration.test.ts @@ -6,7 +6,10 @@ import { Enums, Transactions as MagistrateTransactions } from "@packages/core-ma import { BusinessRegistrationBuilder } from "@packages/core-magistrate-crypto/src/builders"; import { BusinessAlreadyRegisteredError } from "@packages/core-magistrate-transactions/src/errors"; import { MagistrateApplicationEvents } from "@packages/core-magistrate-transactions/src/events"; -import { BusinessRegistrationTransactionHandler, EntityTransactionHandler } from "@packages/core-magistrate-transactions/src/handlers"; +import { + BusinessRegistrationTransactionHandler, + EntityTransactionHandler, +} from "@packages/core-magistrate-transactions/src/handlers"; import { MagistrateIndex } from "@packages/core-magistrate-transactions/src/wallet-indexes"; import { Wallets } from "@packages/core-state"; import { StateStore } from "@packages/core-state/src/stores/state"; @@ -144,7 +147,6 @@ describe("BusinessRegistration", () => { await expect(handler.throwIfCannotBeApplied(businessRegistrationTransaction, senderWallet)).toResolve(); }); - it("should throw if business already registered", async () => { senderWallet.setAttribute("business", {}); await expect( @@ -153,7 +155,7 @@ describe("BusinessRegistration", () => { }); it("should throw if wallet has insufficient balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(businessRegistrationTransaction, senderWallet), ).rejects.toThrowError(InsufficientBalanceError); @@ -176,20 +178,20 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(businessRegistrationTransaction); expect(senderWallet.hasAttribute("business")).toBeTrue(); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessRegistrationAsset); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(businessRegistrationTransaction.data.amount) .minus(businessRegistrationTransaction.data.fee), ); - expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.publicKey!)).toEqual( + expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.getPublicKey()!)).toEqual( senderWallet, ); }); @@ -203,7 +205,7 @@ describe("BusinessRegistration", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(businessRegistrationTransaction); @@ -212,7 +214,7 @@ describe("BusinessRegistration", () => { await handler.revert(businessRegistrationTransaction); expect(senderWallet.hasAttribute("business")).toBeFalse(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); // ! not related to search // ! test failing due to index changes diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts index fb36b2421d..46251fdfc8 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-resignation.test.ts @@ -13,7 +13,7 @@ import { MagistrateApplicationEvents } from "@packages/core-magistrate-transacti import { BusinessRegistrationTransactionHandler, BusinessResignationTransactionHandler, - EntityTransactionHandler + EntityTransactionHandler, } from "@packages/core-magistrate-transactions/src/handlers"; import { MagistrateIndex } from "@packages/core-magistrate-transactions/src/wallet-indexes"; import { Wallets } from "@packages/core-state"; @@ -177,7 +177,7 @@ describe("BusinessRegistration", () => { }); it("should throw if wallet has insufficient balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(businessResignationTransaction, senderWallet), ).rejects.toThrowError(InsufficientBalanceError); @@ -200,9 +200,9 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); - expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.publicKey!)).toEqual( + expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.getPublicKey()!)).toEqual( senderWallet, ); @@ -211,13 +211,13 @@ describe("BusinessRegistration", () => { expect(senderWallet.hasAttribute("business")).toBeTrue(); expect(senderWallet.getAttribute("business.resigned")).toBeTrue(); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(businessResignationTransaction.data.amount) .minus(businessResignationTransaction.data.fee), ); - expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.publicKey!)).toEqual( + expect(walletRepository.findByIndex(MagistrateIndex.Businesses, senderWallet.getPublicKey()!)).toEqual( senderWallet, ); }); @@ -225,7 +225,7 @@ describe("BusinessRegistration", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(businessResignationTransaction); @@ -234,7 +234,7 @@ describe("BusinessRegistration", () => { await handler.revert(businessResignationTransaction); expect(senderWallet.hasAttribute("business.resigned")).toBeFalse(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); }); }); diff --git a/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts b/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts index f889f2915c..47f391547a 100644 --- a/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts +++ b/__tests__/unit/core-magistrate-transactions/handlers/business-update.test.ts @@ -177,7 +177,7 @@ describe("BusinessRegistration", () => { }); it("should throw if wallet has insufficient balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(businessUpdateTransaction, senderWallet)).rejects.toThrowError( InsufficientBalanceError, ); @@ -200,13 +200,13 @@ describe("BusinessRegistration", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(businessUpdateTransaction); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessUpdateAsset); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(businessUpdateTransaction.data.amount) .minus(businessUpdateTransaction.data.fee), @@ -221,7 +221,7 @@ describe("BusinessRegistration", () => { }); describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(businessUpdateTransaction); @@ -238,7 +238,7 @@ describe("BusinessRegistration", () => { await handler.revert(businessUpdateTransaction); expect(senderWallet.getAttribute("business.businessAsset")).toEqual(businessRegistrationAsset); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); it("should be ok with second update transaction", async () => { @@ -247,7 +247,7 @@ describe("BusinessRegistration", () => { ...businessUpdateAsset, }); - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); const businessRegistrationTransaction = new BusinessRegistrationBuilder() .businessRegistrationAsset(businessRegistrationAsset) @@ -288,7 +288,7 @@ describe("BusinessRegistration", () => { ...businessRegistrationAsset, ...businessUpdateAsset, }); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); }); }); }); diff --git a/__tests__/unit/core-manager/actions/info-core-version.test.ts b/__tests__/unit/core-manager/actions/info-core-version.test.ts index fc0da0f33e..ae337b55f0 100644 --- a/__tests__/unit/core-manager/actions/info-core-version.test.ts +++ b/__tests__/unit/core-manager/actions/info-core-version.test.ts @@ -39,5 +39,5 @@ describe("Info:CoreVersion", () => { await expect(result.currentVersion).toBe("3.0.0"); await expect(result.latestVersion).toBeString(); - }); + }, 10000); }); diff --git a/__tests__/unit/core-p2p/peer-verifier.test.ts b/__tests__/unit/core-p2p/peer-verifier.test.ts index 2bd7b53054..f8f1d1efe8 100644 --- a/__tests__/unit/core-p2p/peer-verifier.test.ts +++ b/__tests__/unit/core-p2p/peer-verifier.test.ts @@ -127,7 +127,13 @@ describe("PeerVerifier", () => { id: ids[ids.length - 1], height: parseInt(ids[ids.length - 1].slice(0, 2)), })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { @@ -192,7 +198,13 @@ describe("PeerVerifier", () => { peerCommunicator.hasCommonBlocks = jest .fn() .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { @@ -232,9 +244,7 @@ describe("PeerVerifier", () => { .mockReturnValueOnce([ { data: { height: claimedState.height }, getHeader: () => claimedState.header }, ]); - databaseInterceptor.getBlocksByHeight = jest - .fn() - .mockReturnValueOnce([{ id: claimedState.header.id }]); + databaseInterceptor.getBlocksByHeight = jest.fn().mockReturnValueOnce([{ id: claimedState.header.id }]); const result = await peerVerifier.checkState(claimedState, Date.now() + 2000); @@ -291,10 +301,28 @@ describe("PeerVerifier", () => { .mockReturnValueOnce({ round: 1, maxDelegates: 51 }); dposState.getRoundDelegates = jest .fn() - .mockReturnValueOnce([{ publicKey: generatorPublicKey }]) - .mockReturnValueOnce([{ publicKey: generatorPublicKey }]); + .mockReturnValueOnce([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]) + .mockReturnValueOnce([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); } else { - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock } peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { @@ -489,7 +517,13 @@ describe("PeerVerifier", () => { .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); jest.spyOn(Blocks.BlockFactory, "fromData").mockImplementation(blockFromDataMock); const generatorPublicKey = "03c5282b639d0e8f94cfac6c0ed242d1634d8a2c93cbd76c6ed2856a9f19cf6a13"; - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock if (returnEmpty) { peerCommunicator.getPeerBlocks = jest.fn().mockResolvedValueOnce([]); @@ -525,7 +559,13 @@ describe("PeerVerifier", () => { .fn() .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { @@ -564,7 +604,13 @@ describe("PeerVerifier", () => { .fn() .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { @@ -602,7 +648,13 @@ describe("PeerVerifier", () => { .fn() .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { @@ -681,9 +733,7 @@ describe("PeerVerifier", () => { { data: { height: ourHeight }, getHeader: () => ourHeader }, { data: { height: claimedState.height }, getHeader: () => claimedState.header }, ]); - databaseInterceptor.getBlocksByHeight = jest - .fn() - .mockReturnValueOnce([{ id: claimedState.header.id }]); + databaseInterceptor.getBlocksByHeight = jest.fn().mockReturnValueOnce([{ id: claimedState.header.id }]); const result = await peerVerifier.checkState(claimedState, Date.now() + 2000); @@ -729,7 +779,13 @@ describe("PeerVerifier", () => { peerCommunicator.hasCommonBlocks = jest .fn() .mockImplementation((_, ids) => ({ id: ids[0], height: parseInt(ids[0].slice(0, 2)) })); - trigger.call = jest.fn().mockReturnValue([{ publicKey: generatorPublicKey }]); // getActiveDelegates mock + trigger.call = jest.fn().mockReturnValue([ + { + getPublicKey: () => { + return generatorPublicKey; + }, + }, + ]); // getActiveDelegates mock peerCommunicator.getPeerBlocks = jest.fn().mockImplementation((_, options) => { const blocks = []; for (let i = options.fromBlockHeight + 1; i <= options.fromBlockHeight + options.blockLimit; i++) { diff --git a/__tests__/unit/core-p2p/socket-server/controllers/internal.test.ts b/__tests__/unit/core-p2p/socket-server/controllers/internal.test.ts index adb49342d4..4e88119715 100644 --- a/__tests__/unit/core-p2p/socket-server/controllers/internal.test.ts +++ b/__tests__/unit/core-p2p/socket-server/controllers/internal.test.ts @@ -102,18 +102,28 @@ describe("InternalController", () => { it("should return the info of the current round", async () => { blockchain.getLastBlock = jest.fn().mockReturnValueOnce(block); + const delegates = [ { - publicKey: "026c598170201caf0357f202ff14f365a3b09322071e347873869f58d776bfc565", + getData: () => { + return { + publicKey: "026c598170201caf0357f202ff14f365a3b09322071e347873869f58d776bfc565", + delegate: "delegate1", + }; + }, getAttribute: () => "delegate1", - delegate: "delegate1", }, { - publicKey: "026c740930201caf0357f202ff14f365a3b09322071e347873869f58d776bfc565", + getData: () => { + return { + publicKey: "026c740930201caf0357f202ff14f365a3b09322071e347873869f58d776bfc565", + delegate: "delegate2", + }; + }, getAttribute: () => "delegate2", - delegate: "delegate2", }, ]; + databaseInteractions.getActiveDelegates = jest.fn().mockReturnValueOnce(delegates); const forgingInfo = { blockTimestamp: 97456, @@ -127,13 +137,17 @@ describe("InternalController", () => { const currentRound = await internalController.getCurrentRound({}, {}); + const delegatesData = delegates.map((delegate) => { + return delegate.getData(); + }); + expect(currentRound).toEqual({ current: roundInfo.round, reward: 0, timestamp: forgingInfo.blockTimestamp, - delegates, - currentForger: delegates[forgingInfo.currentForger], - nextForger: delegates[forgingInfo.nextForger], + delegates: delegatesData, + currentForger: delegatesData[forgingInfo.currentForger], + nextForger: delegatesData[forgingInfo.nextForger], lastBlock: block.data, canForge: forgingInfo.canForge, }); diff --git a/__tests__/unit/core-state/__utils__/build-delegate-and-vote-balances.ts b/__tests__/unit/core-state/__utils__/build-delegate-and-vote-balances.ts index 0c19d37942..2fc849f365 100644 --- a/__tests__/unit/core-state/__utils__/build-delegate-and-vote-balances.ts +++ b/__tests__/unit/core-state/__utils__/build-delegate-and-vote-balances.ts @@ -19,18 +19,16 @@ export const buildDelegateAndVoteWallets = (numberDelegates: number, walletRepo: for (let i = 0; i < numberDelegates; i++) { const delegateKey = delegateKeys[i]; const delegate = walletRepo.createWallet(Identities.Address.fromPublicKey(delegateKey)); - delegate.publicKey = delegateKey; + delegate.setPublicKey(delegateKey); delegate.setAttribute("delegate.username", `delegate${i}`); delegate.setAttribute("delegate.voteBalance", CryptoUtils.BigNumber.ZERO); - const voter = walletRepo.createWallet( - Identities.Address.fromPublicKey(delegateKeys[numberDelegates - 1 - i]), - ); + const voter = walletRepo.createWallet(Identities.Address.fromPublicKey(delegateKeys[numberDelegates - 1 - i])); const totalBalance = CryptoUtils.BigNumber.make(i + 1) .times(1000) .times(SATOSHI); - voter.balance = totalBalance.div(2); - voter.publicKey = `v${delegateKey}`; + voter.setBalance(totalBalance.div(2)); + voter.setPublicKey(`v${delegateKey}`); voter.setAttribute("vote", delegateKey); // TODO: is this correct? // that buildVoteBalances should only be triggered if there is a htlc lockedBalance? diff --git a/__tests__/unit/core-state/block-state.test.ts b/__tests__/unit/core-state/block-state.test.ts index 6aba32fc85..d0c0c06b56 100644 --- a/__tests__/unit/core-state/block-state.test.ts +++ b/__tests__/unit/core-state/block-state.test.ts @@ -186,9 +186,9 @@ describe("BlockState", () => { const voteWeight = Utils.BigNumber.make(5678); - votingWallet.balance = voteWeight; + votingWallet.setBalance(voteWeight); - votingWallet.setAttribute("vote", forgingWallet.publicKey); + votingWallet.setAttribute("vote", forgingWallet.getPublicKey()); blockState.increaseWalletDelegateVoteBalance(votingWallet, voteWeight); @@ -218,9 +218,9 @@ describe("BlockState", () => { const voteWeight = Utils.BigNumber.make(5678); - votingWallet.balance = voteWeight; + votingWallet.setBalance(voteWeight); - votingWallet.setAttribute("vote", forgingWallet.publicKey); + votingWallet.setAttribute("vote", forgingWallet.getPublicKey()); blockState.decreaseWalletDelegateVoteBalance(votingWallet, voteWeight); @@ -237,7 +237,7 @@ describe("BlockState", () => { const testTransaction = blocks[0].transactions[0]; const sender = walletRepo.findByPublicKey(testTransaction.data.senderPublicKey); - sender.balance = sendersBalance; + sender.setBalance(sendersBalance); const votedForDelegate: Contracts.State.Wallet = walletRepo.findByPublicKey(voteAddress); const delegateBalanceBefore = Utils.BigNumber.make(4918); @@ -271,7 +271,7 @@ describe("BlockState", () => { }); it("should apply the block data to the forger", async () => { - const balanceBefore = forgingWallet.balance; + const balanceBefore = forgingWallet.getBalance(); const reward = Utils.BigNumber.make(50); const totalFee = Utils.BigNumber.make(50); @@ -294,11 +294,11 @@ describe("BlockState", () => { expect(delegateAfter.forgedRewards).toEqual(reward); expect(delegateAfter.lastBlock).toEqual(blocks[0].data); - expect(forgingWallet.balance).toEqual(balanceBefore.plus(balanceIncrease)); + expect(forgingWallet.getBalance()).toEqual(balanceBefore.plus(balanceIncrease)); }); it("should revert the block data for the forger", async () => { - const balanceBefore = forgingWallet.balance; + const balanceBefore = forgingWallet.getBalance(); const reward = Utils.BigNumber.make(52); const totalFee = Utils.BigNumber.make(49); @@ -308,7 +308,7 @@ describe("BlockState", () => { await blockState.applyBlock(blocks[0]); - expect(forgingWallet.balance).toEqual(balanceBefore.plus(balanceIncrease)); + expect(forgingWallet.getBalance()).toEqual(balanceBefore.plus(balanceIncrease)); await blockState.revertBlock(blocks[0]); @@ -324,7 +324,7 @@ describe("BlockState", () => { expect(delegate.forgedRewards).toEqual(Utils.BigNumber.ZERO); expect(delegate.lastBlock).toEqual(undefined); - expect(forgingWallet.balance).toEqual(balanceBefore); + expect(forgingWallet.getBalance()).toEqual(balanceBefore); }); it("should update sender's and recipient's delegate's vote balance when applying transaction", async () => { @@ -334,18 +334,22 @@ describe("BlockState", () => { const senderDelegateBefore = sendersDelegate.getAttribute("delegate.voteBalance"); const amount: Utils.BigNumber = Utils.BigNumber.make(2345); - sendingWallet.balance = amount; + sendingWallet.setBalance(amount); const recipientsDelegateBefore: Utils.BigNumber = recipientsDelegate.getAttribute("delegate.voteBalance"); - sendingWallet.setAttribute("vote", sendersDelegate.publicKey); - recipientWallet.setAttribute("vote", recipientsDelegate.publicKey); + sendingWallet.setAttribute("vote", sendersDelegate.getPublicKey()); + recipientWallet.setAttribute("vote", recipientsDelegate.getPublicKey()); walletRepo.index([sendersDelegate, recipientsDelegate, sendingWallet, recipientWallet]); const transferTransaction = factory .get("Transfer") - .withOptions({ amount, senderPublicKey: sendingWallet.publicKey, recipientId: recipientWallet.address }) + .withOptions({ + amount, + senderPublicKey: sendingWallet.getPublicKey(), + recipientId: recipientWallet.getAddress(), + }) .make(); // @ts-ignore @@ -372,18 +376,22 @@ describe("BlockState", () => { .make(); const amount: Utils.BigNumber = Utils.BigNumber.make(2345); - sendingWallet.balance = amount; + sendingWallet.setBalance(amount); const recipientDelegateBefore = recipientsDelegate.getAttribute("delegate.voteBalance"); - sendingWallet.setAttribute("vote", sendersDelegate.publicKey); - recipientWallet.setAttribute("vote", recipientsDelegate.publicKey); + sendingWallet.setAttribute("vote", sendersDelegate.getPublicKey()); + recipientWallet.setAttribute("vote", recipientsDelegate.getPublicKey()); walletRepo.index([sendersDelegate, recipientsDelegate, sendingWallet, recipientWallet]); const transferTransaction = factory .get("Transfer") - .withOptions({ amount, senderPublicKey: sendingWallet.publicKey, recipientId: recipientWallet.address }) + .withOptions({ + amount, + senderPublicKey: sendingWallet.getPublicKey(), + recipientId: recipientWallet.getAddress(), + }) .make(); // @ts-ignore @@ -416,7 +424,11 @@ describe("BlockState", () => { multiPaymentTransaction = factory .get("MultiPayment") - .withOptions({ amount, senderPublicKey: sendingWallet.publicKey, recipientId: recipientWallet.address }) + .withOptions({ + amount, + senderPublicKey: sendingWallet.getPublicKey(), + recipientId: recipientWallet.getAddress(), + }) .make(); // @ts-ignore @@ -438,8 +450,8 @@ describe("BlockState", () => { // @ts-ignore multiPaymentTransaction.type = multiPaymentTransaction.data.type; - sendingWallet.setAttribute("vote", sendersDelegate.publicKey); - recipientWallet.setAttribute("vote", recipientsDelegate.publicKey); + sendingWallet.setAttribute("vote", sendersDelegate.getPublicKey()); + recipientWallet.setAttribute("vote", recipientsDelegate.getPublicKey()); walletRepo.index([sendersDelegate, recipientsDelegate, sendingWallet, recipientWallet]); }); @@ -515,7 +527,11 @@ describe("BlockState", () => { const delegateReg = factory .get("DelegateRegistration") - .withOptions({ username: "dummy", senderPublicKey: sender.publicKey, recipientId: recipientWallet.address }) + .withOptions({ + username: "dummy", + senderPublicKey: sender.getPublicKey(), + recipientId: recipientWallet.getAddress(), + }) .make() // @ts-ignore .sign("delegatePassphrase") @@ -537,7 +553,11 @@ describe("BlockState", () => { const delegateRes = factory .get("DelegateResignation") - .withOptions({ username: "dummy", senderPublicKey: sender.publicKey, recipientId: recipientWallet.address }) + .withOptions({ + username: "dummy", + senderPublicKey: sender.getPublicKey(), + recipientId: recipientWallet.getAddress(), + }) .make() // @ts-ignore .sign("delegatePassphrase") @@ -545,12 +565,12 @@ describe("BlockState", () => { const ipfs = factory .get("Ipfs") - .withOptions({ senderPublicKey: sender.publicKey, recipientId: recipientWallet.address }) + .withOptions({ senderPublicKey: sender.getPublicKey(), recipientId: recipientWallet.getAddress() }) .make(); const htlcLock = factory .get("HtlcLock") - .withOptions({ senderPublicKey: sender.publicKey, recipientId: recipientWallet.address }) + .withOptions({ senderPublicKey: sender.getPublicKey(), recipientId: recipientWallet.getAddress() }) .make(); const htlcRefund = factory @@ -696,8 +716,8 @@ describe("BlockState", () => { const recipientsDelegate = walletRepo.findByPublicKey( "034151a3ec46b5670a682b0a63394f863587d1bc97483b1b6c70eb58e7f0aed192", ); - sender.setAttribute("vote", forgingWallet.publicKey); - recipientWallet.setAttribute("vote", recipientsDelegate.publicKey); + sender.setAttribute("vote", forgingWallet.getPublicKey()); + recipientWallet.setAttribute("vote", recipientsDelegate.getPublicKey()); await blockState.applyTransaction(htlcClaimTransaction); @@ -713,7 +733,7 @@ describe("BlockState", () => { }); it("should update vote balances for lock transactions", async () => { - sender.setAttribute("vote", forgingWallet.publicKey); + sender.setAttribute("vote", forgingWallet.getPublicKey()); const forgingWalletBefore = Utils.BigNumber.ZERO; forgingWallet.setAttribute("delegate.voteBalance", forgingWalletBefore); diff --git a/__tests__/unit/core-state/dpos/dpos.test.ts b/__tests__/unit/core-state/dpos/dpos.test.ts index 6afd6fdb51..13e6295a72 100644 --- a/__tests__/unit/core-state/dpos/dpos.test.ts +++ b/__tests__/unit/core-state/dpos/dpos.test.ts @@ -66,8 +66,8 @@ describe("dpos", () => { delegates[1].setAttribute("delegate.voteBalance", Utils.BigNumber.make(5467)); delegates[2].setAttribute("delegate.voteBalance", Utils.BigNumber.make(5467)); - delegates[1].publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; - delegates[2].publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; + delegates[1].setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); + delegates[2].setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); walletRepo.index(delegates[2]); expect(() => dposState.buildDelegateRanking()).toThrow( @@ -109,7 +109,7 @@ describe("dpos", () => { expect(roundDelegates).toEqual(delegates.slice(0, 4)); for (let i = 0; i < round.maxDelegates; i++) { - const delegate = walletRepo.findByPublicKey(roundDelegates[i].publicKey); + const delegate = walletRepo.findByPublicKey(roundDelegates[i].getPublicKey()!); expect(delegate.getAttribute("delegate.round")).toEqual(round.round); } // TODO: when we remove Assertion checks, this won't throw diff --git a/__tests__/unit/core-state/round-state.test.ts b/__tests__/unit/core-state/round-state.test.ts index 4a485cdcd6..f14063203b 100644 --- a/__tests__/unit/core-state/round-state.test.ts +++ b/__tests__/unit/core-state/round-state.test.ts @@ -98,7 +98,9 @@ const generateDelegates = (count: number): any[] => { for (let i = 1; i <= count; i++) { const delegate: any = { - publicKey: "public_key_" + i, + getPublicKey: () => { + return "public_key_" + i; + }, username: "username_" + i, getAttribute: jest.fn().mockImplementation((key) => { return key === "delegate.username" ? "username_" + i : i; @@ -171,7 +173,7 @@ describe("RoundState", () => { const roundDelegateModel = { publicKey: delegatePublicKey, balance: delegateVoteBalance }; databaseService.getRound.mockResolvedValueOnce([roundDelegateModel]); - const newDelegateWallet = { setAttribute: jest.fn(), clone: jest.fn() }; + const newDelegateWallet = { setAttribute: jest.fn(), clone: jest.fn(), setPublicKey: jest.fn() }; walletRepository.createWallet.mockReturnValueOnce(newDelegateWallet); const oldDelegateWallet = { getAttribute: jest.fn() }; @@ -363,7 +365,7 @@ describe("RoundState", () => { blocksInCurrentRound = generateBlocks(3); walletRepository.findByPublicKey = jest.fn().mockImplementation((publicKey) => { - return delegates.find((delegate) => delegate.publicKey === publicKey); + return delegates.find((delegate) => delegate.getPublicKey() === publicKey); }); }); @@ -394,7 +396,7 @@ describe("RoundState", () => { describe("applyRound", () => { it("should build delegates, save round, dispatch events when height is 1", async () => { - const forgingDelegate = { getAttribute: jest.fn() }; + const forgingDelegate = { getAttribute: jest.fn(), getPublicKey: jest.fn() }; const forgingDelegateRound = 1; forgingDelegate.getAttribute.mockReturnValueOnce(forgingDelegateRound); // @ts-ignore @@ -403,7 +405,12 @@ describe("RoundState", () => { // @ts-ignore roundState.blocksInCurrentRound = []; - const delegateWallet = { publicKey: "delegate public key", getAttribute: jest.fn() }; + const delegateWallet = { + getPublicKey: () => { + return "delegate public key"; + }, + getAttribute: jest.fn(), + }; const dposStateRoundDelegates = [delegateWallet]; dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates); dposState.getRoundDelegates.mockReturnValueOnce(dposStateRoundDelegates); @@ -432,7 +439,7 @@ describe("RoundState", () => { }); it("should build delegates, save round, dispatch events, and skip missing round checks when first round has genesis block only", async () => { - const forgingDelegate = { getAttribute: jest.fn() }; + const forgingDelegate = { getAttribute: jest.fn(), getPublicKey: jest.fn() }; const forgingDelegateRound = 1; forgingDelegate.getAttribute.mockReturnValueOnce(forgingDelegateRound); // @ts-ignore diff --git a/__tests__/unit/core-state/setup.ts b/__tests__/unit/core-state/setup.ts index c358204213..de7b791865 100644 --- a/__tests__/unit/core-state/setup.ts +++ b/__tests__/unit/core-state/setup.ts @@ -217,8 +217,8 @@ export const setUp = async (setUpOptions = setUpDefaults, skipBoot = false): Pro return dispatchSpy(data); } - public dispatchSync(data) { - return dispatchSyncSpy(data); + public dispatchSync(...data) { + return dispatchSyncSpy(...data); } } diff --git a/__tests__/unit/core-state/state-builder.test.ts b/__tests__/unit/core-state/state-builder.test.ts index 608058a2e3..6bc87f4b65 100644 --- a/__tests__/unit/core-state/state-builder.test.ts +++ b/__tests__/unit/core-state/state-builder.test.ts @@ -63,10 +63,10 @@ describe("StateBuilder", () => { // sender wallet balance should always be enough for default transactions (unless it is overridden) const wallet = walletRepo.findByPublicKey(senderKey); - wallet.balance = Utils.BigNumber.make(100000); + wallet.setBalance(Utils.BigNumber.make(100000)); }); - it("should call block repository to get intial block rewards", async () => { + it("should call block repository to get initial block rewards", async () => { await stateBuilder.run(); expect(getBlockRewardsSpy).toHaveBeenCalled(); @@ -86,34 +86,35 @@ describe("StateBuilder", () => { it("should apply block rewards to generator wallet", async () => { const wallet = walletRepo.findByPublicKey(generatorKey); - wallet.balance = Utils.BigNumber.ZERO; + wallet.setBalance(Utils.BigNumber.ZERO); walletRepo.index(wallet); - const expectedBalance = wallet.balance.plus(getBlockRewardsDefault.rewards); + const expectedBalance = wallet.getBalance().plus(getBlockRewardsDefault.rewards); await stateBuilder.run(); - expect(wallet.balance).toEqual(expectedBalance); + expect(wallet.getBalance()).toEqual(expectedBalance); }); it("should apply the transaction data to the sender", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.balance = Utils.BigNumber.make(80000); + wallet.setBalance(Utils.BigNumber.make(80000)); walletRepo.index(wallet); - const expectedBalance = wallet.balance + const expectedBalance = wallet + .getBalance() .minus(getSentTransactionDefault.amount) .minus(getSentTransactionDefault.fee); await stateBuilder.run(); - expect(wallet.nonce).toEqual(getSentTransactionDefault.nonce); - expect(wallet.balance).toEqual(expectedBalance); + expect(wallet.getNonce()).toEqual(getSentTransactionDefault.nonce); + expect(wallet.getBalance()).toEqual(expectedBalance); }); it("should fail if any wallet balance is negative and not whitelisted", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.balance = Utils.BigNumber.make(-80000); - wallet.publicKey = senderKey; + wallet.setBalance(Utils.BigNumber.make(-80000)); + wallet.setPublicKey(senderKey); walletRepo.index(wallet); @@ -131,8 +132,8 @@ describe("StateBuilder", () => { .reduce((acc, curr) => [...acc, curr.senderPublicKey], []); const wallet = walletRepo.findByPublicKey(genesisPublicKeys[0]); - wallet.balance = Utils.BigNumber.make(-80000); - wallet.publicKey = genesisPublicKeys[0]; + wallet.setBalance(Utils.BigNumber.make(-80000)); + wallet.setPublicKey(genesisPublicKeys[0]); walletRepo.index(wallet); @@ -144,15 +145,15 @@ describe("StateBuilder", () => { it("should not fail if the publicKey is whitelisted", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.nonce = getSentTransactionDefault.nonce; + wallet.setNonce(getSentTransactionDefault.nonce); const allowedWalletNegativeBalance = Utils.BigNumber.make(5555); - wallet.balance = allowedWalletNegativeBalance; - wallet.publicKey = senderKey; + wallet.setBalance(allowedWalletNegativeBalance); + wallet.setPublicKey(senderKey); walletRepo.index(wallet); const balance: Record> = { [senderKey]: { - [wallet.nonce.toString()]: allowedWalletNegativeBalance.toString(), + [wallet.getNonce().toString()]: allowedWalletNegativeBalance.toString(), }, }; @@ -168,14 +169,14 @@ describe("StateBuilder", () => { it("should fail if the whitelisted key doesn't have the allowed negative balance", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.nonce = getSentTransactionDefault.nonce; - wallet.balance = Utils.BigNumber.make(-90000); - wallet.publicKey = senderKey; + wallet.setNonce(getSentTransactionDefault.nonce); + wallet.setBalance(Utils.BigNumber.make(-90000)); + wallet.setPublicKey(senderKey); walletRepo.index(wallet); const balance: Record> = { [senderKey]: { - [wallet.nonce.toString()]: Utils.BigNumber.make(-80000).toString(), + [wallet.getNonce().toString()]: Utils.BigNumber.make(-80000).toString(), }, }; @@ -193,14 +194,14 @@ describe("StateBuilder", () => { it("should not fail if the whitelisted key has the allowed negative balance", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.nonce = getSentTransactionDefault.nonce; - wallet.balance = Utils.BigNumber.make(-90000); - wallet.publicKey = senderKey; + wallet.setNonce(getSentTransactionDefault.nonce); + wallet.setBalance(Utils.BigNumber.make(-90000)); + wallet.setPublicKey(senderKey); walletRepo.index(wallet); const balance: Record> = { [senderKey]: { - [wallet.nonce.toString()]: Utils.BigNumber.make(-90000).toString(), + [wallet.getNonce().toString()]: Utils.BigNumber.make(-90000).toString(), }, }; @@ -216,7 +217,7 @@ describe("StateBuilder", () => { it("should not fail if delegates vote balance isn't below 0", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.balance = Utils.BigNumber.ZERO; + wallet.setBalance(Utils.BigNumber.ZERO); walletRepo.index(wallet); wallet.setAttribute("delegate.voteBalance", Utils.BigNumber.make(100)); @@ -230,14 +231,15 @@ describe("StateBuilder", () => { it("should fail if the wallet has no public key", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.nonce = getSentTransactionDefault.nonce; - wallet.balance = Utils.BigNumber.make(-90000); - wallet.publicKey = null; + wallet.setNonce(getSentTransactionDefault.nonce); + wallet.setBalance(Utils.BigNumber.make(-90000)); + // @ts-ignore + wallet.publicKey = undefined; walletRepo.index(wallet); const balance: Record> = { [senderKey]: { - [wallet.nonce.toString()]: Utils.BigNumber.make(-90000).toString(), + [wallet.getNonce().toString()]: Utils.BigNumber.make(-90000).toString(), }, }; @@ -261,7 +263,7 @@ describe("StateBuilder", () => { it("should exit app if any vote balance is negative", async () => { const wallet = walletRepo.findByPublicKey(senderKey); - wallet.balance = Utils.BigNumber.ZERO; + wallet.setBalance(Utils.BigNumber.ZERO); walletRepo.index(wallet); wallet.setAttribute("delegate.voteBalance", Utils.BigNumber.make(-100)); diff --git a/__tests__/unit/core-state/wallets/wallet-index.test.ts b/__tests__/unit/core-state/wallets/wallet-index.test.ts index b6b6bcf1a3..eb36cc4c5c 100644 --- a/__tests__/unit/core-state/wallets/wallet-index.test.ts +++ b/__tests__/unit/core-state/wallets/wallet-index.test.ts @@ -17,7 +17,7 @@ beforeAll(async () => { beforeEach(() => { wallet = factory.make(); walletIndex = new WalletIndex((index, wallet) => { - index.set(wallet.address, wallet); + index.set(wallet.getAddress(), wallet); }, true); }); @@ -26,36 +26,36 @@ describe("WalletIndex", () => { walletIndex.index(wallet); const entries = walletIndex.entries(); expect(entries.length).toEqual(1); - expect(entries[0][0]).toEqual(entries[0][1].address); - expect(entries[0][0]).toEqual(wallet.address); + expect(entries[0][0]).toEqual(entries[0][1].getAddress()); + expect(entries[0][0]).toEqual(wallet.getAddress()); }); it("should return keys", () => { walletIndex.index(wallet); - expect(walletIndex.keys()).toContain(wallet.address); + expect(walletIndex.keys()).toContain(wallet.getAddress()); }); it("should return walletKeys", () => { expect(walletIndex.walletKeys(wallet)).toEqual([]); walletIndex.index(wallet); - expect(walletIndex.walletKeys(wallet)).toEqual([wallet.address]); + expect(walletIndex.walletKeys(wallet)).toEqual([wallet.getAddress()]); }); describe("set", () => { it("should set and get addresses", () => { - expect(walletIndex.has(wallet.address)).toBeFalse(); + expect(walletIndex.has(wallet.getAddress())).toBeFalse(); walletIndex.index(wallet); - walletIndex.set(wallet.address, wallet); + walletIndex.set(wallet.getAddress(), wallet); - expect(walletIndex.get(wallet.address)).toBe(wallet); - expect(walletIndex.has(wallet.address)).toBeTrue(); + expect(walletIndex.get(wallet.getAddress())).toBe(wallet); + expect(walletIndex.has(wallet.getAddress())).toBeTrue(); expect(walletIndex.values()).toContain(wallet); walletIndex.clear(); - expect(walletIndex.has(wallet.address)).toBeFalse(); + expect(walletIndex.has(wallet.getAddress())).toBeFalse(); }); it("should override key with new wallet", () => { @@ -73,27 +73,27 @@ describe("WalletIndex", () => { describe("forget", () => { it("should index and forget wallets", () => { - expect(walletIndex.has(wallet.address)).toBeFalse(); + expect(walletIndex.has(wallet.getAddress())).toBeFalse(); walletIndex.index(wallet); - expect(walletIndex.has(wallet.address)).toBeTrue(); + expect(walletIndex.has(wallet.getAddress())).toBeTrue(); - walletIndex.forget(wallet.address); - expect(walletIndex.has(wallet.address)).toBeFalse(); + walletIndex.forget(wallet.getAddress()); + expect(walletIndex.has(wallet.getAddress())).toBeFalse(); }); it("should not throw if key is not indexed", () => { - walletIndex.forget(wallet.address); + walletIndex.forget(wallet.getAddress()); }); }); describe("forgetWallet", () => { it("should forget wallet", () => { walletIndex.index(wallet); - expect(walletIndex.get(wallet.address)).toBe(wallet); + expect(walletIndex.get(wallet.getAddress())).toBe(wallet); walletIndex.forgetWallet(wallet); - expect(walletIndex.get(wallet.address)).toBeUndefined(); + expect(walletIndex.get(wallet.getAddress())).toBeUndefined(); }); it("should not throw if wallet is not indexed", () => { diff --git a/__tests__/unit/core-state/wallets/wallet-repository-clone.test.ts b/__tests__/unit/core-state/wallets/wallet-repository-clone.test.ts index 2f6857b5ed..1887d41d4e 100644 --- a/__tests__/unit/core-state/wallets/wallet-repository-clone.test.ts +++ b/__tests__/unit/core-state/wallets/wallet-repository-clone.test.ts @@ -120,7 +120,7 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.createWallet("address"); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.address).toEqual("address"); + expect(wallet.getAddress()).toEqual("address"); }); }); @@ -237,7 +237,7 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.findByAddress("address"); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.address).toEqual("address"); + expect(wallet.getAddress()).toEqual("address"); expect(walletRepositoryClone.hasByAddress("address")).toBeTrue(); expect(walletRepositoryBlockchain.hasByAddress("address")).toBeFalse(); }); @@ -248,7 +248,7 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.findByAddress("address"); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.address).toEqual("address"); + expect(wallet.getAddress()).toEqual("address"); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has("address")).toBeTrue(); expect(spyOnCreateWallet).toHaveBeenCalled(); @@ -273,10 +273,10 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.findByPublicKey(publicKey); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.publicKey).toEqual(publicKey); + expect(wallet.getPublicKey()).toEqual(publicKey); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.PublicKeys).has(publicKey)).toBeTrue(); expect( - walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.address), + walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.getAddress()), ).toBeTrue(); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Ipfs).has("key")).toBeTrue(); @@ -288,14 +288,14 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.findByPublicKey(publicKey); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.publicKey).toEqual(publicKey); + expect(wallet.getPublicKey()).toEqual(publicKey); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.PublicKeys).has(publicKey)).toBeTrue(); expect( - walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.address), + walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.getAddress()), ).toBeTrue(); expect(walletRepositoryBlockchain.hasByPublicKey(publicKey)).toBeFalse(); - expect(walletRepositoryBlockchain.hasByAddress(wallet.address)).toBeFalse(); + expect(walletRepositoryBlockchain.hasByAddress(wallet.getAddress())).toBeFalse(); }); it("should return existing wallet", () => { @@ -304,7 +304,7 @@ describe("Wallet Repository Clone", () => { const wallet = walletRepositoryClone.findByPublicKey(publicKey); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.publicKey).toEqual(publicKey); + expect(wallet.getPublicKey()).toEqual(publicKey); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.PublicKeys).has(publicKey)).toBeTrue(); expect(spyOnCreateWallet).toHaveBeenCalled(); @@ -389,7 +389,7 @@ describe("Wallet Repository Clone", () => { expect(wallet.getAttribute("delegate.username")).toEqual(username); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Usernames).has(username)).toBeTrue(); expect( - walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.address), + walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Addresses).has(wallet.getAddress()), ).toBeTrue(); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Ipfs).has("key")).toBeTrue(); }); @@ -402,7 +402,7 @@ describe("Wallet Repository Clone", () => { walletRepositoryClone.index(wallet); expect(wallet).toBeInstanceOf(Wallet); - expect(wallet.address).toEqual("address"); + expect(wallet.getAddress()).toEqual("address"); expect(wallet.getAttribute("delegate.username")).toEqual(username); expect(walletRepositoryClone.getIndex(Contracts.State.WalletIndexes.Usernames).has(username)).toBeTrue(); expect(spyOnCreateWallet).toHaveBeenCalled(); @@ -625,7 +625,7 @@ describe("Wallet Repository Clone", () => { it("should return nonce if wallet exists only in blockchain wallet repository", () => { const wallet = walletRepositoryBlockchain.findByPublicKey(publicKey); - wallet.nonce = Utils.BigNumber.make("10"); + wallet.setNonce(Utils.BigNumber.make("10")); expect(walletRepositoryClone.getNonce(publicKey)).toEqual(Utils.BigNumber.make("10")); expect( @@ -636,10 +636,10 @@ describe("Wallet Repository Clone", () => { it("should return nonce if wallet exists on copy wallet repository", () => { const blockchainWallet = walletRepositoryBlockchain.findByPublicKey(publicKey); - blockchainWallet.nonce = Utils.BigNumber.make("10"); + blockchainWallet.setNonce(Utils.BigNumber.make("10")); const wallet = walletRepositoryClone.findByPublicKey(publicKey); - wallet.nonce = Utils.BigNumber.make("20"); + wallet.setNonce(Utils.BigNumber.make("20")); expect(walletRepositoryClone.getNonce(publicKey)).toEqual(Utils.BigNumber.make("20")); expect( diff --git a/__tests__/unit/core-state/wallets/wallet-repository-copy-on-write.test.ts b/__tests__/unit/core-state/wallets/wallet-repository-copy-on-write.test.ts index 3f7563161c..4c175b10c8 100644 --- a/__tests__/unit/core-state/wallets/wallet-repository-copy-on-write.test.ts +++ b/__tests__/unit/core-state/wallets/wallet-repository-copy-on-write.test.ts @@ -31,7 +31,7 @@ beforeEach(() => { describe("Wallet Repository Copy On Write", () => { it("should create a wallet", () => { const wallet = walletRepoCopyOnWrite.createWallet("abcd"); - expect(wallet.address).toEqual("abcd"); + expect(wallet.getAddress()).toEqual("abcd"); expect(wallet).toBeInstanceOf(Wallet); }); @@ -50,7 +50,7 @@ describe("Wallet Repository Copy On Write", () => { const spyFindByAddress = jest.spyOn(walletRepo, "findByAddress"); const clonedWallet = walletRepoCopyOnWrite.findByAddress("notexisting"); expect(spyFindByAddress).toHaveBeenCalledWith("notexisting"); - const originalWallet = walletRepo.findByAddress(clonedWallet.address); + const originalWallet = walletRepo.findByAddress(clonedWallet.getAddress()); expect(originalWallet).not.toBe(clonedWallet); }); @@ -82,11 +82,11 @@ describe("Wallet Repository Copy On Write", () => { const address = "ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"; const wallet = walletRepoCopyOnWrite.createWallet(address); const publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); expect(walletRepoCopyOnWrite.findByAddress(address)).not.toEqual(wallet); walletRepoCopyOnWrite.getIndex("publicKeys").set(publicKey, wallet); - expect(walletRepoCopyOnWrite.findByPublicKey(publicKey).publicKey).toBeDefined(); + expect(walletRepoCopyOnWrite.findByPublicKey(publicKey).getPublicKey()).toBeDefined(); expect(walletRepoCopyOnWrite.findByPublicKey(publicKey)).toEqual(wallet); /** @@ -94,7 +94,7 @@ describe("Wallet Repository Copy On Write", () => { * TempWalletRepository calls index inside findByPublicKey (unlike WalletRepository). * This has the effect that these are now defined without needing to index */ - expect(walletRepoCopyOnWrite.findByAddress(address).publicKey).toBeDefined(); + expect(walletRepoCopyOnWrite.findByAddress(address).getPublicKey()).toBeDefined(); expect(walletRepoCopyOnWrite.findByAddress(address)).toEqual(wallet); }); @@ -155,8 +155,8 @@ describe("Wallet Repository Copy On Write", () => { walletRepoCopyOnWrite.index(wallet); - expect(walletRepo.findByAddress(wallet.address)).not.toBe( - walletRepoCopyOnWrite.findByAddress(wallet.address), + expect(walletRepo.findByAddress(wallet.getAddress())).not.toBe( + walletRepoCopyOnWrite.findByAddress(wallet.getAddress()), ); }); }); @@ -166,25 +166,25 @@ describe("Wallet Repository Copy On Write", () => { const wallet = walletRepo.createWallet("abcdef"); walletRepo.index(wallet); - const tempWallet = walletRepoCopyOnWrite.findByAddress(wallet.address); - tempWallet.balance = Utils.BigNumber.ONE; + const tempWallet = walletRepoCopyOnWrite.findByAddress(wallet.getAddress()); + tempWallet.setBalance(Utils.BigNumber.ONE); - expect(wallet.balance).not.toEqual(tempWallet.balance); + expect(wallet.getBalance()).not.toEqual(tempWallet.getBalance()); }); }); describe("findByPublicKey", () => { it("should return a copy", () => { const wallet = walletRepo.createWallet("ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"); - wallet.publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; - wallet.balance = Utils.BigNumber.SATOSHI; + wallet.setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); + wallet.setBalance(Utils.BigNumber.SATOSHI); walletRepo.index(wallet); - const tempWallet = walletRepoCopyOnWrite.findByPublicKey(wallet.publicKey); - tempWallet.balance = Utils.BigNumber.ZERO; + const tempWallet = walletRepoCopyOnWrite.findByPublicKey(wallet.getPublicKey()!); + tempWallet.setBalance(Utils.BigNumber.ZERO); - expect(wallet.balance).toEqual(Utils.BigNumber.SATOSHI); - expect(tempWallet.balance).toEqual(Utils.BigNumber.ZERO); + expect(wallet.getBalance()).toEqual(Utils.BigNumber.SATOSHI); + expect(tempWallet.getBalance()).toEqual(Utils.BigNumber.ZERO); }); }); @@ -195,9 +195,9 @@ describe("Wallet Repository Copy On Write", () => { walletRepo.index(wallet); const tempWallet = walletRepoCopyOnWrite.findByUsername(wallet.getAttribute("delegate.username")); - tempWallet.balance = Utils.BigNumber.ONE; + tempWallet.setBalance(Utils.BigNumber.ONE); - expect(wallet.balance).not.toEqual(tempWallet.balance); + expect(wallet.getBalance()).not.toEqual(tempWallet.getBalance()); }); }); @@ -206,17 +206,17 @@ describe("Wallet Repository Copy On Write", () => { const wallet = walletRepo.createWallet("abcdef"); walletRepo.index(wallet); - expect(walletRepoCopyOnWrite.hasByAddress(wallet.address)).toBeTrue(); + expect(walletRepoCopyOnWrite.hasByAddress(wallet.getAddress())).toBeTrue(); }); }); describe("hasByPublicKey", () => { it("should be ok", () => { const wallet = walletRepo.createWallet("ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"); - wallet.publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; + wallet.setPublicKey("03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"); walletRepo.index(wallet); - expect(walletRepoCopyOnWrite.hasByPublicKey(wallet.publicKey)).toBeTrue(); + expect(walletRepoCopyOnWrite.hasByPublicKey(wallet.getPublicKey()!)).toBeTrue(); }); }); @@ -248,7 +248,7 @@ describe("Wallet Repository Copy On Write", () => { const clone = walletRepoCopyOnWrite.findByIndex(Contracts.State.WalletIndexes.Usernames, "test"); expect(clone).not.toBe(wallet); - expect(clone.address).toEqual(wallet.address); + expect(clone.getAddress()).toEqual(wallet.getAddress()); expect(clone.getAttribute("delegate.username")).toEqual(wallet.getAttribute("delegate.username")); }); }); diff --git a/__tests__/unit/core-state/wallets/wallet-repository.test.ts b/__tests__/unit/core-state/wallets/wallet-repository.test.ts index 4dfbbe93fc..ca1871fc15 100644 --- a/__tests__/unit/core-state/wallets/wallet-repository.test.ts +++ b/__tests__/unit/core-state/wallets/wallet-repository.test.ts @@ -63,7 +63,7 @@ describe("Wallet Repository", () => { it("should create a wallet", () => { const wallet = walletRepo.createWallet("abcd"); - expect(wallet.address).toEqual("abcd"); + expect(wallet.getAddress()).toEqual("abcd"); expect(wallet).toBeInstanceOf(Wallet); }); @@ -92,19 +92,19 @@ describe("Wallet Repository", () => { const address = "ATtEq2tqNumWgR9q9zF6FjGp34Mp5JpKGp"; const wallet = walletRepo.createWallet(address); const publicKey = "03720586a26d8d49ec27059bd4572c49ba474029c3627715380f4df83fb431aece"; - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); expect(walletRepo.findByAddress(address)).not.toEqual(wallet); walletRepo.getIndex("publicKeys").set(publicKey, wallet); - expect(walletRepo.findByPublicKey(publicKey).publicKey).toBeDefined(); + expect(walletRepo.findByPublicKey(publicKey).getPublicKey()).toBeDefined(); expect(walletRepo.findByPublicKey(publicKey)).toEqual(wallet); - expect(walletRepo.findByAddress(address).publicKey).toBeUndefined(); + expect(walletRepo.findByAddress(address).getPublicKey()).toBeUndefined(); expect(walletRepo.findByAddress(address)).not.toEqual(wallet); walletRepo.index(wallet); - expect(walletRepo.findByAddress(address).publicKey).toBe(publicKey); + expect(walletRepo.findByAddress(address).getPublicKey()).toBe(publicKey); expect(walletRepo.findByAddress(address)).toEqual(wallet); }); @@ -224,6 +224,7 @@ describe("Wallet Repository", () => { it("should do nothing if forgotten wallet does not exist", () => { const wallet1 = walletRepo.createWallet("wallet1"); walletRepo.index(wallet1); + // @ts-ignore wallet1.publicKey = undefined; expect(walletRepo.has("wallet2")).toBeFalse(); }); @@ -259,11 +260,11 @@ describe("Wallet Repository", () => { it("should get the nonce of a wallet", () => { const wallet1 = walletRepo.createWallet("wallet1"); - wallet1.nonce = Utils.BigNumber.make(100); - wallet1.publicKey = "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34"; + wallet1.setNonce(Utils.BigNumber.make(100)); + wallet1.setPublicKey("02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34"); walletRepo.index(wallet1); - expect(walletRepo.getNonce(wallet1.publicKey)).toEqual(Utils.BigNumber.make(100)); + expect(walletRepo.getNonce(wallet1.getPublicKey()!)).toEqual(Utils.BigNumber.make(100)); }); it("should return 0 nonce if there is no wallet", () => { diff --git a/__tests__/unit/core-state/wallets/wallet.test.ts b/__tests__/unit/core-state/wallets/wallet.test.ts index c63e736fe5..eb01673549 100644 --- a/__tests__/unit/core-state/wallets/wallet.test.ts +++ b/__tests__/unit/core-state/wallets/wallet.test.ts @@ -1,12 +1,12 @@ import "jest-extended"; +import { Container, Contracts } from "@arkecosystem/core-kernel"; +import { Utils } from "@arkecosystem/crypto"; import { Services } from "@packages/core-kernel"; -import { Wallet } from "@packages/core-state/src/wallets"; +import { Wallet, WalletEvent } from "@packages/core-state/src/wallets"; import { getWalletAttributeSet } from "@packages/core-test-framework/src/internal/wallet-attributes"; -import { setUp, Setup } from "../setup"; -import { Container, Contracts } from "@arkecosystem/core-kernel"; -import { Utils } from "@arkecosystem/crypto"; +import { Setup, setUp } from "../setup"; let setup: Setup; @@ -24,7 +24,77 @@ describe("Models - Wallet", () => { it("returns the address", () => { const address = "Abcde"; const wallet = new Wallet(address, attributeMap); - expect(wallet.address).toBe(address); + expect(wallet.getAddress()).toBe(address); + }); + + it("should set and get publicKey", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getPublicKey()).toBeUndefined(); + + wallet.setPublicKey("publicKey"); + expect(wallet.getPublicKey()).toEqual("publicKey"); + }); + + it("should set and get balance", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getBalance()).toEqual(Utils.BigNumber.ZERO); + + wallet.setBalance(Utils.BigNumber.ONE); + expect(wallet.getBalance()).toEqual(Utils.BigNumber.ONE); + }); + + it("should set and get nonce", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getNonce()).toEqual(Utils.BigNumber.ZERO); + + wallet.setNonce(Utils.BigNumber.ONE); + expect(wallet.getNonce()).toEqual(Utils.BigNumber.ONE); + }); + + it("should increase balance", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getBalance()).toEqual(Utils.BigNumber.ZERO); + + expect(wallet.increaseBalance(Utils.BigNumber.ONE)).toBe(wallet); + expect(wallet.getBalance()).toEqual(Utils.BigNumber.ONE); + }); + + it("should decrease balance", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getBalance()).toEqual(Utils.BigNumber.ZERO); + + expect(wallet.decreaseBalance(Utils.BigNumber.ONE)).toBe(wallet); + expect(wallet.getBalance()).toEqual(Utils.BigNumber.make("-1")); + }); + + it("should increase nonce", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getNonce()).toEqual(Utils.BigNumber.ZERO); + + wallet.increaseNonce(); + expect(wallet.getNonce()).toEqual(Utils.BigNumber.ONE); + }); + + it("should decrease nonce", () => { + const address = "Abcde"; + const wallet = new Wallet(address, attributeMap); + + expect(wallet.getNonce()).toEqual(Utils.BigNumber.ZERO); + + wallet.decreaseNonce(); + expect(wallet.getNonce()).toEqual(Utils.BigNumber.make("-1")); }); it("should get, set and forget custom attributes", () => { @@ -116,16 +186,108 @@ describe("Original", () => { jest.resetAllMocks(); }); - it("should emit on property set", async () => { - wallet.balance = Utils.BigNumber.make("100"); + it("should emit on setPublicKey", async () => { + wallet.setPublicKey("dummyPublicKey"); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: "dummyPublicKey", + key: "publicKey", + previousValue: undefined, + value: "dummyPublicKey", + wallet, + }); + }); + + it("should emit on setBalance", async () => { + wallet.setBalance(Utils.BigNumber.ONE); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "balance", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.ONE, + wallet, + }); + }); + + it("should emit on increaseBalance", async () => { + wallet.increaseBalance(Utils.BigNumber.ONE); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "balance", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.ONE, + wallet, + }); + }); + + it("should emit on decreaseBalance", async () => { + wallet.decreaseBalance(Utils.BigNumber.ONE); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "balance", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.make("-1"), + wallet, + }); + }); + + it("should emit on setNonce", async () => { + wallet.setNonce(Utils.BigNumber.ONE); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "nonce", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.ONE, + wallet, + }); + }); + + it("should emit on increaseNonce", async () => { + wallet.increaseNonce(); + + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "nonce", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.ONE, + wallet, + }); + }); + + it("should emit on decreaseNonce", async () => { + wallet.decreaseNonce(); expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "nonce", + previousValue: Utils.BigNumber.ZERO, + value: Utils.BigNumber.make("-1"), + wallet, + }); }); it("should emit on setAttribute", async () => { wallet.setAttribute("delegate.username", "dummy"); expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(1); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "delegate.username", + previousValue: undefined, + value: "dummy", + wallet, + }); }); it("should emit on forgetAttribute", async () => { @@ -133,13 +295,20 @@ describe("Original", () => { wallet.forgetAttribute("delegate.username"); expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledTimes(2); + expect(setup.spies.dispatchSyncSpy).toHaveBeenCalledWith(WalletEvent.PropertySet, { + publicKey: undefined, + key: "delegate.username", + previousValue: "dummy", + value: undefined, + wallet, + }); }); it("should clone", async () => { wallet.setAttribute("delegate.username", "dummy"); const clone = wallet.clone(); - expect(clone.address).toEqual("Abcde"); + expect(clone.getAddress()).toEqual("Abcde"); expect(clone.getAttribute("delegate.username")).toEqual("dummy"); }); }); diff --git a/__tests__/unit/core-test-framework/factories/factories/round.test.ts b/__tests__/unit/core-test-framework/factories/factories/round.test.ts index 9854941223..ad9d7c00b7 100644 --- a/__tests__/unit/core-test-framework/factories/factories/round.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/round.test.ts @@ -21,10 +21,10 @@ describe("RoundFactory", () => { entity.forEach((delegate) => { expect(delegate).toBeInstanceOf(Wallets.Wallet); - expect(delegate.address).toBeString(); - expect(delegate.publicKey).toBeString(); - expect(delegate.balance).toBeInstanceOf(Utils.BigNumber); - expect(delegate.nonce).toBeInstanceOf(Utils.BigNumber); + expect(delegate.getAddress()).toBeString(); + expect(delegate.getPublicKey()).toBeString(); + expect(delegate.getBalance()).toBeInstanceOf(Utils.BigNumber); + expect(delegate.getNonce()).toBeInstanceOf(Utils.BigNumber); expect(delegate.isDelegate()).toBeTrue(); }); }); diff --git a/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts b/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts index e152fca084..707f1c4da9 100644 --- a/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts +++ b/__tests__/unit/core-test-framework/factories/factories/wallet.test.ts @@ -16,16 +16,16 @@ describe("WalletFactory", () => { const entity: Wallets.Wallet = factory.get("Wallet").make(); expect(entity).toBeInstanceOf(Wallets.Wallet); - expect(entity.address).toBeString(); - expect(entity.publicKey).toBeString(); + expect(entity.getAddress()).toBeString(); + expect(entity.getPublicKey()).toBeString(); }); it("should make a wallet with a second public key", () => { const entity: Wallets.Wallet = factory.get("Wallet").withStates("secondPublicKey").make(); expect(entity).toBeInstanceOf(Wallets.Wallet); - expect(entity.address).toBeString(); - expect(entity.publicKey).toBeString(); + expect(entity.getAddress()).toBeString(); + expect(entity.getPublicKey()).toBeString(); expect(entity.getAttribute("secondPublicKey")).toBeString(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/__support__/app.ts b/__tests__/unit/core-transactions/handlers/__support__/app.ts index df39b82d83..01094ee146 100644 --- a/__tests__/unit/core-transactions/handlers/__support__/app.ts +++ b/__tests__/unit/core-transactions/handlers/__support__/app.ts @@ -182,7 +182,7 @@ export const buildSenderWallet = ( }) .make(); - wallet.balance = Utils.BigNumber.make(7527654310); + wallet.setBalance(Utils.BigNumber.make(7527654310)); return wallet; }; @@ -205,7 +205,7 @@ export const buildSecondSignatureWallet = (factoryBuilder: FactoryBuilder): Wall }) .make(); - wallet.balance = Utils.BigNumber.make(7527654310); + wallet.setBalance(Utils.BigNumber.make(7527654310)); wallet.setAttribute("secondPublicKey", "038082dad560a22ea003022015e3136b21ef1ffd9f2fd50049026cbe8e2258ca17"); return wallet; @@ -225,8 +225,8 @@ export const buildMultiSignatureWallet = (): Wallets.Wallet => { Identities.Address.fromMultiSignatureAsset(multiSignatureAsset), new Services.Attributes.AttributeMap(getWalletAttributeSet()), ); - wallet.publicKey = Identities.PublicKey.fromMultiSignatureAsset(multiSignatureAsset); - wallet.balance = Utils.BigNumber.make(100390000000); + wallet.setPublicKey(Identities.PublicKey.fromMultiSignatureAsset(multiSignatureAsset)); + wallet.setBalance(Utils.BigNumber.make(100390000000)); wallet.setAttribute("multiSignature", multiSignatureAsset); return wallet; diff --git a/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts index 7d8a4c3312..c8ca5c3d77 100644 --- a/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/one/multi-signature-registration.test.ts @@ -1,6 +1,6 @@ import "jest-extended"; -import { Application, Contracts, Services, Exceptions } from "@packages/core-kernel"; +import { Application, Contracts, Exceptions, Services } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; import { Wallets } from "@packages/core-state"; import { StateStore } from "@packages/core-state/src/stores/state"; @@ -97,7 +97,7 @@ describe("MultiSignatureRegistrationTransaction", () => { 1, ); - senderWallet.balance = Utils.BigNumber.make(100390000000); + senderWallet.setBalance(Utils.BigNumber.make(100390000000)); multiSignatureAsset = { publicKeys: [ @@ -120,7 +120,7 @@ describe("MultiSignatureRegistrationTransaction", () => { .multiSignatureAsset(multiSignatureAsset) .senderPublicKey(Identities.PublicKey.fromPassphrase(passphrases[0])) .nonce("1") - .recipientId(recipientWallet.publicKey!) + .recipientId(recipientWallet.getPublicKey()!) .multiSign(passphrases[0], 0) // ! implicitly sets version to 2 .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -257,7 +257,7 @@ describe("MultiSignatureRegistrationTransaction", () => { describe("revertForSender", () => { it("should be ok", async () => { - senderWallet.nonce = Utils.BigNumber.ONE; + senderWallet.setNonce(Utils.BigNumber.ONE); await expect(handler.revertForSender(multiSignatureTransaction)).toResolve(); }); diff --git a/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts index b488fc8bdc..e022c546c4 100644 --- a/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/delegate-registration.test.ts @@ -394,7 +394,7 @@ describe("DelegateRegistrationTransaction", () => { }); it("should throw if wallet has insufficient funds", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(delegateRegistrationTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, @@ -402,7 +402,7 @@ describe("DelegateRegistrationTransaction", () => { }); it("should throw if wallet nonce is invalid", async () => { - senderWallet.nonce = Utils.BigNumber.ONE; + senderWallet.setNonce(Utils.BigNumber.ONE); await expect(handler.throwIfCannotBeApplied(delegateRegistrationTransaction, senderWallet)).rejects.toThrow( UnexpectedNonceError, @@ -432,7 +432,7 @@ describe("DelegateRegistrationTransaction", () => { }) .make(); - anotherWallet.balance = Utils.BigNumber.make(7527654310); + anotherWallet.setBalance(Utils.BigNumber.make(7527654310)); walletRepository.index(anotherWallet); @@ -479,7 +479,7 @@ describe("DelegateRegistrationTransaction", () => { describe("apply and revert", () => { it("should resolve", async () => { - const walletBalance = senderWallet.balance; + const walletBalance = senderWallet.getBalance(); jest.spyOn(TransactionHandler.prototype, "applyToSender"); @@ -487,8 +487,8 @@ describe("DelegateRegistrationTransaction", () => { expect(TransactionHandler.prototype.applyToSender).toHaveBeenCalledTimes(1); - expect(senderWallet.balance).toEqual(walletBalance.minus(delegateRegistrationTransaction.data.fee)); - expect(senderWallet.nonce).toEqual(Utils.BigNumber.ONE); + expect(senderWallet.getBalance()).toEqual(walletBalance.minus(delegateRegistrationTransaction.data.fee)); + expect(senderWallet.getNonce()).toEqual(Utils.BigNumber.ONE); expect(senderWallet.getAttribute("delegate.username")).toBe("dummy"); expect(walletRepository.getIndex(Contracts.State.WalletIndexes.Usernames).has("dummy")).toBeTrue(); expect(walletRepository.getIndex(Contracts.State.WalletIndexes.Usernames).get("dummy")).toBe(senderWallet); @@ -499,8 +499,8 @@ describe("DelegateRegistrationTransaction", () => { expect(TransactionHandler.prototype.revertForSender).toHaveBeenCalledTimes(1); - expect(senderWallet.balance).toEqual(walletBalance); - expect(senderWallet.nonce).toEqual(Utils.BigNumber.ZERO); + expect(senderWallet.getBalance()).toEqual(walletBalance); + expect(senderWallet.getNonce()).toEqual(Utils.BigNumber.ZERO); expect(senderWallet.hasAttribute("delegate.username")).toBeFalse(); expect(walletRepository.getIndex(Contracts.State.WalletIndexes.Usernames).has("dummy")).toBeFalse(); }); diff --git a/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts b/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts index 0a08da5bfc..3798536dc4 100644 --- a/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/delegate-resignation.test.ts @@ -125,7 +125,7 @@ describe("DelegateResignationTransaction", () => { }) .make(); - delegateWallet.balance = Utils.BigNumber.make(66 * 1e8); + delegateWallet.setBalance(Utils.BigNumber.make(66 * 1e8)); delegateWallet.setAttribute("delegate", { username: "dummy" }); walletRepository.index(delegateWallet); @@ -231,7 +231,7 @@ describe("DelegateResignationTransaction", () => { }); it("should throw if wallet has insufficient funds", async () => { - delegateWallet.balance = Utils.BigNumber.ZERO; + delegateWallet.setBalance(Utils.BigNumber.ZERO); await expect( handler.throwIfCannotBeApplied(delegateResignationTransaction, delegateWallet), ).rejects.toThrow(InsufficientBalanceError); @@ -318,7 +318,7 @@ describe("DelegateResignationTransaction", () => { expect(delegateWallet.getAttribute("delegate.resigned")).toBeTrue(); const voteTransaction = BuilderFactory.vote() - .votesAsset(["+" + delegateWallet.publicKey]) + .votesAsset(["+" + delegateWallet.getPublicKey()]) .nonce("1") .sign(passphrases[0]) .build(); diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts index 472fc553ee..0655ef9566 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-claim.test.ts @@ -141,7 +141,7 @@ describe("Htlc claim", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(claimWallet.address) + .recipientId(claimWallet.getAddress()) .amount(amount.toString()) .nonce("1") .sign(lockPassphrase) @@ -184,7 +184,7 @@ describe("Htlc claim", () => { lockTransactionId: htlcLockTransaction.id!, }) .nonce("1") - .senderPublicKey(multiSignatureWallet.publicKey!) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -303,7 +303,7 @@ describe("Htlc claim", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(claimWallet.address) + .recipientId(claimWallet.getAddress()) .amount(amount.toString()) .nonce("1") .vendorField("dummy") @@ -429,7 +429,7 @@ describe("Htlc claim", () => { it("should apply htlc claim transaction", async () => { await expect(handler.throwIfCannotBeApplied(htlcClaimTransaction, claimWallet)).toResolve(); - const balanceBefore = claimWallet.balance; + const balanceBefore = claimWallet.getBalance(); expect(lockWallet.getAttribute("htlc.locks")).toBeDefined(); expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); @@ -437,7 +437,7 @@ describe("Htlc claim", () => { await handler.apply(htlcClaimTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(claimWallet.balance).toEqual( + expect(claimWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcClaimTransaction.data.fee), ); }); @@ -472,7 +472,7 @@ describe("Htlc claim", () => { await expect(handler.throwIfCannotBeApplied(htlcClaimTransaction, dummyWallet)).toResolve(); - const balanceBefore = claimWallet.balance; + const balanceBefore = claimWallet.getBalance(); expect(lockWallet.getAttribute("htlc.locks")).not.toBeEmpty(); expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); @@ -480,7 +480,7 @@ describe("Htlc claim", () => { await handler.apply(htlcClaimTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(claimWallet.balance).toEqual( + expect(claimWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcClaimTransaction.data.fee), ); }); @@ -518,12 +518,12 @@ describe("Htlc claim", () => { Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(htlcLockTransaction)]); - const balanceBefore = claimWallet.balance; + const balanceBefore = claimWallet.getBalance(); await handler.apply(htlcClaimTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(claimWallet.balance).toEqual( + expect(claimWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcClaimTransaction.data.fee), ); @@ -543,7 +543,7 @@ describe("Htlc claim", () => { }); expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); - expect(claimWallet.balance).toEqual(balanceBefore); + expect(claimWallet.getBalance()).toEqual(balanceBefore); }); it("should be ok if lockWallet contains another locks", async () => { @@ -567,11 +567,11 @@ describe("Htlc claim", () => { walletRepository.index(lockWallet); - const balanceBefore = claimWallet.balance; + const balanceBefore = claimWallet.getBalance(); await handler.apply(htlcClaimTransaction); expect(lockWallet.hasAttribute("htlc.locks")).toBeTrue(); - expect(claimWallet.balance).toEqual( + expect(claimWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcClaimTransaction.data.fee), ); @@ -590,8 +590,10 @@ describe("Htlc claim", () => { ...htlcLockTransaction.data.asset!.lock, }); - expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount.plus(amount)); - expect(claimWallet.balance).toEqual(balanceBefore); + expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual( + htlcLockTransaction.data.amount.plus(amount), + ); + expect(claimWallet.getBalance()).toEqual(balanceBefore); }); it("should be ok if lock transaction has vendorField", async () => { @@ -601,12 +603,12 @@ describe("Htlc claim", () => { Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(htlcLockTransaction)]); - const balanceBefore = claimWallet.balance; + const balanceBefore = claimWallet.getBalance(); await handler.apply(htlcClaimTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(claimWallet.balance).toEqual( + expect(claimWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcClaimTransaction.data.fee), ); @@ -620,7 +622,7 @@ describe("Htlc claim", () => { expect(foundLockWallet).toBeDefined(); expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); - expect(claimWallet.balance).toEqual(balanceBefore); + expect(claimWallet.getBalance()).toEqual(balanceBefore); }); }); @@ -638,7 +640,7 @@ describe("Htlc claim", () => { await expect(handler.apply(htlcClaimTransaction)).toResolve(); htlcClaimTransaction.data.asset = undefined; - claimWallet.nonce = Utils.BigNumber.ONE; + claimWallet.setNonce(Utils.BigNumber.ONE); await expect(handler.revertForSender(htlcClaimTransaction)).rejects.toThrow( Exceptions.Runtime.AssertionException, diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts index 0be4252222..48503e9bd2 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-lock.test.ts @@ -108,7 +108,7 @@ describe("Htlc lock", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .sign(passphrases[0]) @@ -119,7 +119,7 @@ describe("Htlc lock", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .sign(passphrases[1]) @@ -131,8 +131,8 @@ describe("Htlc lock", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .senderPublicKey(multiSignatureWallet.publicKey!) - .recipientId(recipientWallet.address) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .multiSign(passphrases[0], 0) @@ -155,7 +155,7 @@ describe("Htlc lock", () => { const locks = senderWallet.getAttribute("htlc.locks"); expect(locks[htlcLockTransaction.id].amount).toEqual(Utils.BigNumber.make("1")); - expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.address); + expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.getAddress()); expect(locks[htlcLockTransaction.id].timetamp).toEqual(htlcLockTransaction.timestamp); expect(locks[htlcLockTransaction.id].secretHash).toEqual(htlcSecretHashHex); expect(locks[htlcLockTransaction.id].expiration).toEqual(expiration); @@ -177,7 +177,7 @@ describe("Htlc lock", () => { const locks = senderWallet.getAttribute("htlc.locks"); expect(locks[htlcLockTransaction.id].amount).toEqual(Utils.BigNumber.make("1")); - expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.address); + expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.getAddress()); expect(locks[htlcLockTransaction.id].timetamp).toEqual(htlcLockTransaction.timestamp); expect(locks[htlcLockTransaction.id].secretHash).toEqual(htlcSecretHashHex); expect(locks[htlcLockTransaction.id].expiration).toEqual(expiration); @@ -189,7 +189,7 @@ describe("Htlc lock", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .vendorField("64756d6d79") @@ -210,7 +210,7 @@ describe("Htlc lock", () => { const locks = senderWallet.getAttribute("htlc.locks"); expect(locks[htlcLockTransaction.id].amount).toEqual(Utils.BigNumber.make("1")); - expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.address); + expect(locks[htlcLockTransaction.id].recipientId).toEqual(recipientWallet.getAddress()); expect(locks[htlcLockTransaction.id].timetamp).toEqual(htlcLockTransaction.timestamp); expect(locks[htlcLockTransaction.id].vendorField).toEqual("dummy"); expect(locks[htlcLockTransaction.id].secretHash).toEqual(htlcSecretHashHex); @@ -244,7 +244,7 @@ describe("Htlc lock", () => { }); it("should throw if wallet has insufficient funds", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(htlcLockTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, @@ -280,7 +280,7 @@ describe("Htlc lock", () => { it("should apply htlc lock transaction", async () => { await expect(handler.throwIfCannotBeApplied(htlcLockTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); expect(senderWallet.hasAttribute("htlc.locks")).toBeFalse(); @@ -288,7 +288,7 @@ describe("Htlc lock", () => { expect(senderWallet.getAttribute("htlc.locks", {})[htlcLockTransaction.id!]).toBeDefined(); expect(senderWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( balanceBefore.minus(htlcLockTransaction.data.fee).minus(htlcLockTransaction.data.amount), ); }); @@ -308,7 +308,7 @@ describe("Htlc lock", () => { it("should be ok", async () => { await expect(handler.throwIfCannotBeApplied(htlcLockTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); await handler.apply(htlcLockTransaction); @@ -316,7 +316,7 @@ describe("Htlc lock", () => { expect(senderWallet.getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO)).toEqual( htlcLockTransaction.data.amount, ); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( balanceBefore.minus(htlcLockTransaction.data.fee).minus(htlcLockTransaction.data.amount), ); @@ -326,7 +326,7 @@ describe("Htlc lock", () => { expect(senderWallet.getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO)).toEqual( Utils.BigNumber.ZERO, ); - expect(senderWallet.balance).toEqual(balanceBefore); + expect(senderWallet.getBalance()).toEqual(balanceBefore); }); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts b/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts index 989ddc22f6..1704cfc0ed 100644 --- a/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/htlc-refund.test.ts @@ -124,7 +124,7 @@ describe("Htlc refund", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount(amount.toString()) .nonce("1") // .vendorField("dummy") @@ -165,7 +165,7 @@ describe("Htlc refund", () => { lockTransactionId: htlcLockTransaction.id!, }) .nonce("1") - .senderPublicKey(multiSignatureWallet.publicKey!) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -269,7 +269,7 @@ describe("Htlc refund", () => { secretHash: htlcSecretHashHex, expiration: expiration, }) - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount(amount.toString()) .nonce("1") .sign(lockPassphrase) @@ -375,7 +375,7 @@ describe("Htlc refund", () => { it("should apply htlc refund transaction", async () => { await expect(handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet)).toResolve(); - const balanceBefore = lockWallet.balance; + const balanceBefore = lockWallet.getBalance(); // @ts-ignore expect(lockWallet.getAttribute("htlc.locks")[htlcLockTransaction.id]).toBeDefined(); @@ -384,7 +384,7 @@ describe("Htlc refund", () => { await handler.apply(htlcRefundTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(lockWallet.balance).toEqual( + expect(lockWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcRefundTransaction.data.fee), ); }); @@ -392,7 +392,7 @@ describe("Htlc refund", () => { it("should apply htlc refund transaction if lockWallet contains another locks", async () => { await expect(handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet)).toResolve(); - const balanceBefore = lockWallet.balance; + const balanceBefore = lockWallet.getBalance(); lockWallet.setAttribute("htlc.lockedBalance", Utils.BigNumber.make(amount).plus(amount)); lockWallet.setAttribute("htlc.locks", { @@ -411,13 +411,15 @@ describe("Htlc refund", () => { walletRepository.index(lockWallet); // @ts-ignore expect(lockWallet.getAttribute("htlc.locks")[htlcLockTransaction.id]).toBeDefined(); - expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount.plus(amount)); + expect(lockWallet.getAttribute("htlc.lockedBalance")).toEqual( + htlcLockTransaction.data.amount.plus(amount), + ); await handler.apply(htlcRefundTransaction); expect(lockWallet.hasAttribute("htlc.locks")).toBeTrue(); expect(lockWallet.getAttribute("htlc.locks")).toContainKey("dummy_id"); - expect(lockWallet.balance).toEqual( + expect(lockWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcRefundTransaction.data.fee), ); }); @@ -451,7 +453,7 @@ describe("Htlc refund", () => { await expect(handler.throwIfCannotBeApplied(htlcRefundTransaction, dummyWallet)).toResolve(); - const balanceBefore = lockWallet.balance; + const balanceBefore = lockWallet.getBalance(); // @ts-ignore expect(lockWallet.getAttribute("htlc.locks")[htlcLockTransaction.id]).toBeDefined(); @@ -460,7 +462,7 @@ describe("Htlc refund", () => { await handler.apply(htlcRefundTransaction); expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(lockWallet.balance).toEqual( + expect(lockWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcRefundTransaction.data.fee), ); }); @@ -492,13 +494,13 @@ describe("Htlc refund", () => { await expect(handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet)).toResolve(); Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(htlcLockTransaction)]); - const balanceBefore = lockWallet.balance; + const balanceBefore = lockWallet.getBalance(); await handler.apply(htlcRefundTransaction); // @ts-ignore expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(lockWallet.balance).toEqual( + expect(lockWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcRefundTransaction.data.fee), ); @@ -516,7 +518,7 @@ describe("Htlc refund", () => { }); expect(foundLockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); - expect(foundLockWallet.balance).toEqual(balanceBefore); + expect(foundLockWallet.getBalance()).toEqual(balanceBefore); }); it("should be ok if lcok transaction has vendor field", async () => { @@ -525,13 +527,13 @@ describe("Htlc refund", () => { await expect(handler.throwIfCannotBeApplied(htlcRefundTransaction, lockWallet)).toResolve(); Mocks.TransactionRepository.setTransactions([Mapper.mapTransactionToModel(htlcLockTransaction)]); - const balanceBefore = lockWallet.balance; + const balanceBefore = lockWallet.getBalance(); await handler.apply(htlcRefundTransaction); // @ts-ignore expect(lockWallet.hasAttribute("htlc")).toBe(false); - expect(lockWallet.balance).toEqual( + expect(lockWallet.getBalance()).toEqual( balanceBefore.plus(htlcLockTransaction.data.amount).minus(htlcRefundTransaction.data.fee), ); @@ -544,7 +546,7 @@ describe("Htlc refund", () => { expect(foundLockWallet).toBeDefined(); expect(foundLockWallet.getAttribute("htlc.lockedBalance")).toEqual(htlcLockTransaction.data.amount); - expect(foundLockWallet.balance).toEqual(balanceBefore); + expect(foundLockWallet.getBalance()).toEqual(balanceBefore); }); it("should throw if asset is undefined", async () => { diff --git a/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts b/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts index 56265491e3..2daaf34c29 100644 --- a/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/ipfs.test.ts @@ -97,7 +97,7 @@ describe("Ipfs", () => { .build(); multiSignatureIpfsTransaction = BuilderFactory.ipfs() - .senderPublicKey(multiSignatureWallet.publicKey!) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) .ipfsAsset("QmR45FmbVVrixReBwJkhEKde2qwHYaQzGxu4ZoDeswuF9w") .nonce("1") .multiSign(passphrases[0], 0) @@ -249,7 +249,7 @@ describe("Ipfs", () => { }); it("should throw if wallet has insufficient funds", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(ipfsTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, @@ -277,7 +277,7 @@ describe("Ipfs", () => { it("should apply ipfs transaction", async () => { await expect(handler.throwIfCannotBeApplied(ipfsTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); await handler.apply(ipfsTransaction); @@ -286,7 +286,7 @@ describe("Ipfs", () => { ipfsTransaction.data.asset!.ipfs! ], ).toBeTrue(); - expect(senderWallet.balance).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); + expect(senderWallet.getBalance()).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); }); it("should apply ipfs transaction if wallet have ipfs attribute", async () => { @@ -294,7 +294,7 @@ describe("Ipfs", () => { await expect(handler.throwIfCannotBeApplied(ipfsTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); await handler.apply(ipfsTransaction); @@ -303,7 +303,7 @@ describe("Ipfs", () => { ipfsTransaction.data.asset!.ipfs! ], ).toBeTrue(); - expect(senderWallet.balance).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); + expect(senderWallet.getBalance()).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); }); }); @@ -319,7 +319,7 @@ describe("Ipfs", () => { describe("revertForSender", () => { it("should throw if asset is undefined", async () => { - senderWallet.nonce = Utils.BigNumber.make("1"); + senderWallet.setNonce(Utils.BigNumber.make("1")); ipfsTransaction.data.asset = undefined; @@ -333,11 +333,11 @@ describe("Ipfs", () => { it("should be ok", async () => { await expect(handler.throwIfCannotBeApplied(ipfsTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); await handler.apply(ipfsTransaction); - expect(senderWallet.balance).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); + expect(senderWallet.getBalance()).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); expect( senderWallet.getAttribute("ipfs.hashes")[ ipfsTransaction.data.asset!.ipfs! @@ -347,19 +347,19 @@ describe("Ipfs", () => { await handler.revert(ipfsTransaction); expect(senderWallet.hasAttribute("ipfs")).toBeFalse(); - expect(senderWallet.balance).toEqual(balanceBefore); + expect(senderWallet.getBalance()).toEqual(balanceBefore); }); it("should be ok if wallet have many ipfs attributes", async () => { await expect(handler.throwIfCannotBeApplied(ipfsTransaction, senderWallet)).toResolve(); - const balanceBefore = senderWallet.balance; + const balanceBefore = senderWallet.getBalance(); await handler.apply(ipfsTransaction); senderWallet.getAttribute("ipfs.hashes")["dummy_ipfs_hash"] = true; - expect(senderWallet.balance).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); + expect(senderWallet.getBalance()).toEqual(balanceBefore.minus(ipfsTransaction.data.fee)); expect( senderWallet.getAttribute("ipfs.hashes")[ ipfsTransaction.data.asset!.ipfs! @@ -369,7 +369,7 @@ describe("Ipfs", () => { await handler.revert(ipfsTransaction); expect(senderWallet.hasAttribute("ipfs")).toBeTrue(); - expect(senderWallet.balance).toEqual(balanceBefore); + expect(senderWallet.getBalance()).toEqual(balanceBefore); }); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts b/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts index 34821b6e2f..9d06ab3712 100644 --- a/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/multi-payment.test.ts @@ -113,7 +113,7 @@ describe("MultiPaymentTransaction", () => { .addPayment("AUsi9ZcFkcwG7WMpRE121TR4HaTjnAP7qD", "40") .addPayment("ARugw4i18i2pVnYZEMWKJj2mAnQQ97wuat", "50") .nonce("1") - .senderPublicKey(multiSignatureWallet.publicKey!) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -171,14 +171,14 @@ describe("MultiPaymentTransaction", () => { }); it("should throw if wallet has insufficient funds", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(multiPaymentTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); }); it("should throw if wallet has insufficient funds send all payouts", async () => { - senderWallet.balance = Utils.BigNumber.make(150); // short by the fee + senderWallet.setBalance(Utils.BigNumber.make(150)); // short by the fee await expect(handler.throwIfCannotBeApplied(multiPaymentTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); @@ -187,7 +187,7 @@ describe("MultiPaymentTransaction", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); const totalPaymentsAmount = multiPaymentTransaction.data.asset!.payments!.reduce( (prev, curr) => prev.plus(curr.amount), Utils.BigNumber.ZERO, @@ -195,13 +195,13 @@ describe("MultiPaymentTransaction", () => { await handler.apply(multiPaymentTransaction); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance).minus(totalPaymentsAmount).minus(multiPaymentTransaction.data.fee), ); for (const { recipientId, amount } of multiPaymentTransaction.data.asset!.payments!) { const paymentRecipientWallet = walletRepository.findByAddress(recipientId); - expect(paymentRecipientWallet.balance).toEqual(amount); + expect(paymentRecipientWallet.getBalance()).toEqual(amount); } }); }); @@ -230,12 +230,12 @@ describe("MultiPaymentTransaction", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; - senderWallet.nonce = Utils.BigNumber.make(1); + const senderBalance = senderWallet.getBalance(); + senderWallet.setNonce(Utils.BigNumber.make(1)); for (const { recipientId, amount } of multiPaymentTransaction.data.asset!.payments!) { const paymentRecipientWallet = walletRepository.findByAddress(recipientId); - paymentRecipientWallet.balance = amount; + paymentRecipientWallet.setBalance(amount); } const totalPaymentsAmount = multiPaymentTransaction.data.asset!.payments!.reduce( (prev, curr) => prev.plus(curr.amount), @@ -243,18 +243,18 @@ describe("MultiPaymentTransaction", () => { ); await handler.revert(multiPaymentTransaction); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance).plus(totalPaymentsAmount).plus(multiPaymentTransaction.data.fee), ); - expect(senderWallet.nonce.isZero()).toBeTrue(); - expect(recipientWallet.balance).toEqual(Utils.BigNumber.ZERO); + expect(senderWallet.getNonce().isZero()).toBeTrue(); + expect(recipientWallet.getBalance()).toEqual(Utils.BigNumber.ZERO); }); }); describe("revertForSender", () => { it("should throw if asset is undefined", async () => { - senderWallet.nonce = Utils.BigNumber.ONE; + senderWallet.setNonce(Utils.BigNumber.ONE); multiPaymentTransaction.data.asset = undefined; diff --git a/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts index 859c37cc6b..ec054a1ee6 100644 --- a/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/multi-signature-registration.test.ts @@ -86,7 +86,7 @@ describe("MultiSignatureRegistrationTransaction", () => { 2, ); - senderWallet.balance = Utils.BigNumber.make(100390000000); + senderWallet.setBalance(Utils.BigNumber.make(100390000000)); multiSignatureAsset = { publicKeys: [ @@ -106,9 +106,9 @@ describe("MultiSignatureRegistrationTransaction", () => { multiSignatureTransaction = BuilderFactory.multiSignature() .multiSignatureAsset(multiSignatureAsset) - .senderPublicKey(senderWallet.publicKey!) + .senderPublicKey(senderWallet.getPublicKey()!) .nonce("1") - .recipientId(recipientWallet.publicKey!) + .recipientId(recipientWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -126,7 +126,7 @@ describe("MultiSignatureRegistrationTransaction", () => { }) .senderPublicKey(Identities.PublicKey.fromPassphrase(passphrases[1])) .nonce("1") - .recipientId(recipientWallet.publicKey!) + .recipientId(recipientWallet.getPublicKey()!) .multiSign(passphrases[1], 0) .multiSign(passphrases[0], 1) .multiSign(passphrases[2], 2) @@ -279,7 +279,7 @@ describe("MultiSignatureRegistrationTransaction", () => { ]; const participantWallet = walletRepository.findByPublicKey(participants[0]); - participantWallet.balance = Utils.BigNumber.make(1e8 * 100); + participantWallet.setBalance(Utils.BigNumber.make(1e8 * 100)); multiSignatureTransaction = BuilderFactory.multiSignature() .multiSignatureAsset({ @@ -288,7 +288,7 @@ describe("MultiSignatureRegistrationTransaction", () => { }) .senderPublicKey(Identities.PublicKey.fromPassphrase(passphrases[0])) .nonce("1") - .recipientId(recipientWallet.publicKey!) + .recipientId(recipientWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -307,14 +307,14 @@ describe("MultiSignatureRegistrationTransaction", () => { expect(multiSigWallet.hasMultiSignature()).toBeTrue(); - multiSigWallet.balance = Utils.BigNumber.make(1e8 * 100); + multiSigWallet.setBalance(Utils.BigNumber.make(1e8 * 100)); const transferBuilder = factoryBuilder .get("Transfer") .withOptions({ amount: 10000000, - senderPublicKey: senderWallet.publicKey, - recipientId: multiSigWallet.address, + senderPublicKey: senderWallet.getPublicKey(), + recipientId: multiSigWallet.getAddress(), }) .make() // @ts-ignore @@ -342,7 +342,7 @@ describe("MultiSignatureRegistrationTransaction", () => { it("should throw if wallet has insufficient funds", async () => { senderWallet.forgetAttribute("multiSignature"); - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(multiSignatureTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, @@ -379,9 +379,9 @@ describe("MultiSignatureRegistrationTransaction", () => { const multiSignatureTransactionWithSameAddress = BuilderFactory.multiSignature() .multiSignatureAsset(multiSignatureAsset) - .senderPublicKey(anotherSenderWallet.publicKey!) + .senderPublicKey(anotherSenderWallet.getPublicKey()!) .nonce("1") - .recipientId(recipientWallet.publicKey!) + .recipientId(recipientWallet.getPublicKey()!) .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) .multiSign(passphrases[2], 2) @@ -406,13 +406,13 @@ describe("MultiSignatureRegistrationTransaction", () => { expect(senderWallet.hasAttribute("multiSignature")).toBeFalse(); expect(recipientWallet.hasAttribute("multiSignature")).toBeFalse(); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(100390000000)); - expect(recipientWallet.balance).toEqual(Utils.BigNumber.ZERO); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(100390000000)); + expect(recipientWallet.getBalance()).toEqual(Utils.BigNumber.ZERO); await handler.apply(multiSignatureTransaction); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(98390000000)); - expect(recipientWallet.balance).toEqual(Utils.BigNumber.ZERO); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(98390000000)); + expect(recipientWallet.getBalance()).toEqual(Utils.BigNumber.ZERO); expect(senderWallet.hasAttribute("multiSignature")).toBeFalse(); expect(recipientWallet.getAttribute("multiSignature")).toEqual( @@ -435,11 +435,11 @@ describe("MultiSignatureRegistrationTransaction", () => { describe("revert", () => { it("should be ok", async () => { - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setNonce(Utils.BigNumber.make(1)); await handler.revert(multiSignatureTransaction); - expect(senderWallet.nonce.isZero()).toBeTrue(); + expect(senderWallet.getNonce().isZero()).toBeTrue(); expect(senderWallet.hasMultiSignature()).toBeFalse(); expect(recipientWallet.hasMultiSignature()).toBeFalse(); }); diff --git a/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts b/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts index 8f1336cffd..935be8083c 100644 --- a/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/second-signature-registration.test.ts @@ -165,7 +165,7 @@ describe("SecondSignatureRegistrationTransaction", () => { }); it("should throw if wallet has insufficient funds", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(secondSignatureTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, diff --git a/__tests__/unit/core-transactions/handlers/two/transaction.test.ts b/__tests__/unit/core-transactions/handlers/two/transaction.test.ts index be241d2cee..3b8c1bde06 100644 --- a/__tests__/unit/core-transactions/handlers/two/transaction.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/transaction.test.ts @@ -1,7 +1,7 @@ import "jest-extended"; -import ByteBuffer from "bytebuffer"; - +import { TransactionTypeGroup } from "@arkecosystem/crypto/dist/enums"; +import { TransactionSchema } from "@arkecosystem/crypto/dist/transactions/types/schemas"; import { Application, Contracts } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; import { Wallets } from "@packages/core-state"; @@ -26,6 +26,7 @@ import { Crypto, Enums, Identities, Interfaces, Managers, Transactions, Utils } import { IMultiSignatureAsset } from "@packages/crypto/src/interfaces"; import { configManager } from "@packages/crypto/src/managers"; import { BuilderFactory } from "@packages/crypto/src/transactions"; +import ByteBuffer from "bytebuffer"; import { buildMultiSignatureWallet, @@ -34,8 +35,6 @@ import { buildSenderWallet, initApp, } from "../__support__/app"; -import { TransactionTypeGroup } from "@arkecosystem/crypto/dist/enums"; -import { TransactionSchema } from "@arkecosystem/crypto/dist/transactions/types/schemas"; let app: Application; let senderWallet: Wallets.Wallet; @@ -148,14 +147,14 @@ describe("General Tests", () => { ); transferTransaction = BuilderFactory.transfer() - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("10000000") .nonce("1") .sign(passphrases[0]) .build(); transactionWithSecondSignature = BuilderFactory.transfer() - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("10000000") .nonce("1") .sign(passphrases[0]) @@ -163,8 +162,8 @@ describe("General Tests", () => { .build(); multiSignatureTransferTransaction = BuilderFactory.transfer() - .senderPublicKey(multiSignatureWallet.publicKey!) - .recipientId(recipientWallet.address) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .multiSign(passphrases[0], 0) @@ -205,9 +204,7 @@ describe("General Tests", () => { // @ts-ignore Managers.configManager.config.network.name = "devnet"; - await expect( - handler.throwIfCannotBeApplied(transactionWithSecondSignature, senderWallet), - ).toResolve(); + await expect(handler.throwIfCannotBeApplied(transactionWithSecondSignature, senderWallet)).toResolve(); // @ts-ignore Managers.configManager.config.network.name = "testnet"; @@ -232,7 +229,7 @@ describe("General Tests", () => { }); it("should throw if nonce is invalid", async () => { - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setNonce(Utils.BigNumber.make(1)); await expect(handler.throwIfCannotBeApplied(transferTransaction, senderWallet)).rejects.toThrowError( UnexpectedNonceError, ); @@ -317,7 +314,7 @@ describe("General Tests", () => { it("should throw if wallet has not enough balance", async () => { // 1 arktoshi short - senderWallet.balance = transferTransaction.data.amount.plus(transferTransaction.data.fee).minus(1); + senderWallet.setBalance(transferTransaction.data.amount.plus(transferTransaction.data.fee).minus(1)); await expect(handler.throwIfCannotBeApplied(transferTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); @@ -325,7 +322,7 @@ describe("General Tests", () => { it("should be true even with publicKey case mismatch", async () => { transferTransaction.data.senderPublicKey = transferTransaction.data.senderPublicKey!.toUpperCase(); - senderWallet.publicKey = senderWallet.publicKey!.toLowerCase(); + senderWallet.setPublicKey(senderWallet.getPublicKey()!.toLowerCase()); const instance: Interfaces.ITransaction = Transactions.TransactionFactory.fromData( transferTransaction.data, @@ -349,7 +346,7 @@ describe("General Tests", () => { transferTransaction = BuilderFactory.transfer() .amount("10000000") - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .sign("secret") .nonce("0") .build(); @@ -410,11 +407,11 @@ describe("General Tests", () => { transactionData.senderPublicKey = transactionData.senderPublicKey?.toUpperCase(); const instance = Transactions.TransactionFactory.fromData(transactionData); - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.apply(instance); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance).minus(instance.data.amount).minus(instance.data.fee), ); }); @@ -429,7 +426,7 @@ describe("General Tests", () => { configManager.getMilestone().aip11 = false; transferTransaction = BuilderFactory.transfer() - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("10000000") .nonce("1") .sign(passphrases[0]) @@ -439,13 +436,13 @@ describe("General Tests", () => { }); it("should throw with negative balance", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.apply(transferTransaction)).rejects.toThrow(InsufficientBalanceError); }); it("should throw with negative balance if environment is not test", async () => { process.env.CORE_ENV === "unitest"; - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.apply(transferTransaction)).rejects.toThrow(InsufficientBalanceError); }); }); @@ -466,30 +463,30 @@ describe("General Tests", () => { it("should throw if nonce is undefined", async () => { await expect(handler.apply(transferTransaction)).toResolve(); transferTransaction.data.nonce = undefined; - await expect(handler.revert(transferTransaction)).rejects.toThrow(UnexpectedNonceError) + await expect(handler.revert(transferTransaction)).rejects.toThrow(UnexpectedNonceError); }); it("should throw if nonce is invalid", async () => { await expect(handler.apply(transferTransaction)).toResolve(); - senderWallet.nonce = Utils.BigNumber.make(100); + senderWallet.setNonce(Utils.BigNumber.make(100)); await expect(handler.revert(transferTransaction)).rejects.toThrow(UnexpectedNonceError); }); it("should not fail due to case mismatch", async () => { - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setNonce(Utils.BigNumber.make(1)); const transactionData: Interfaces.ITransactionData = transferTransaction.data; transactionData.senderPublicKey = transactionData.senderPublicKey?.toUpperCase(); const instance = Transactions.TransactionFactory.fromData(transactionData); - const senderBalance = senderWallet.balance; + const senderBalance = senderWallet.getBalance(); await handler.revert(instance); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance).plus(instance.data.amount).plus(instance.data.fee), ); - expect(senderWallet.nonce.isZero()).toBeTrue(); + expect(senderWallet.getNonce().isZero()).toBeTrue(); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/transfer.test.ts b/__tests__/unit/core-transactions/handlers/two/transfer.test.ts index 88b683a298..ef13b92ddf 100644 --- a/__tests__/unit/core-transactions/handlers/two/transfer.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/transfer.test.ts @@ -89,14 +89,14 @@ describe("TransferTransaction", () => { ); transferTransaction = BuilderFactory.transfer() - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("10000000") .sign(passphrases[0]) .nonce("1") .build(); secondSignatureTransferTransaction = BuilderFactory.transfer() - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .sign(passphrases[1]) @@ -104,8 +104,8 @@ describe("TransferTransaction", () => { .build(); multiSignatureTransferTransaction = BuilderFactory.transfer() - .senderPublicKey(multiSignatureWallet.publicKey!) - .recipientId(recipientWallet.address) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) + .recipientId(recipientWallet.getAddress()) .amount("1") .nonce("1") .multiSign(passphrases[0], 0) @@ -156,7 +156,7 @@ describe("TransferTransaction", () => { }); it("should throw if wallet has insufficient funds for vote", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(transferTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); @@ -171,11 +171,11 @@ describe("TransferTransaction", () => { }) .make(); - coldWallet.balance = Utils.BigNumber.ZERO; + coldWallet.setBalance(Utils.BigNumber.ZERO); transferTransaction = BuilderFactory.transfer() .amount("10000000") - .recipientId(recipientWallet.address) + .recipientId(recipientWallet.getAddress()) .nonce("1") .sign(passphrases[3]) .build(); @@ -194,11 +194,11 @@ describe("TransferTransaction", () => { }) .make(); - coldWallet.balance = Utils.BigNumber.ZERO; + coldWallet.setBalance(Utils.BigNumber.ZERO); transferTransaction = BuilderFactory.transfer() .amount("10000000") - .recipientId(coldWallet.address) + .recipientId(coldWallet.getAddress()) .nonce("1") .sign(passphrases[0]) .build(); @@ -223,18 +223,18 @@ describe("TransferTransaction", () => { describe("apply", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; - const recipientBalance = recipientWallet.balance; + const senderBalance = senderWallet.getBalance(); + const recipientBalance = recipientWallet.getBalance(); await handler.apply(transferTransaction); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(transferTransaction.data.amount) .minus(transferTransaction.data.fee), ); - expect(recipientWallet.balance).toEqual( + expect(recipientWallet.getBalance()).toEqual( Utils.BigNumber.make(recipientBalance).plus(transferTransaction.data.amount), ); }); @@ -242,26 +242,26 @@ describe("TransferTransaction", () => { describe("revert", () => { it("should be ok", async () => { - const senderBalance = senderWallet.balance; - const recipientBalance = recipientWallet.balance; + const senderBalance = senderWallet.getBalance(); + const recipientBalance = recipientWallet.getBalance(); await handler.apply(transferTransaction); - expect(senderWallet.balance).toEqual( + expect(senderWallet.getBalance()).toEqual( Utils.BigNumber.make(senderBalance) .minus(transferTransaction.data.amount) .minus(transferTransaction.data.fee), ); - expect(recipientWallet.balance).toEqual( + expect(recipientWallet.getBalance()).toEqual( Utils.BigNumber.make(recipientBalance).plus(transferTransaction.data.amount), ); await handler.revert(transferTransaction); - expect(senderWallet.balance).toEqual(Utils.BigNumber.make(senderBalance)); + expect(senderWallet.getBalance()).toEqual(Utils.BigNumber.make(senderBalance)); - expect(recipientWallet.balance).toEqual(recipientBalance); + expect(recipientWallet.getBalance()).toEqual(recipientBalance); }); }); }); diff --git a/__tests__/unit/core-transactions/handlers/two/vote.test.ts b/__tests__/unit/core-transactions/handlers/two/vote.test.ts index 8bc2b42df6..de6c52f239 100644 --- a/__tests__/unit/core-transactions/handlers/two/vote.test.ts +++ b/__tests__/unit/core-transactions/handlers/two/vote.test.ts @@ -1,6 +1,6 @@ import "jest-extended"; -import { Application, Contracts, Exceptions, Enums as AppEnums } from "@packages/core-kernel"; +import { Application, Contracts, Enums as AppEnums, Exceptions } from "@packages/core-kernel"; import { Identifiers } from "@packages/core-kernel/src/ioc"; import { Wallets } from "@packages/core-state"; import { StateStore } from "@packages/core-state/src/stores/state"; @@ -119,21 +119,21 @@ describe("VoteTransaction", () => { walletRepository.index(delegateWallet2); voteTransaction = BuilderFactory.vote() - .votesAsset(["+" + delegateWallet1.publicKey!]) + .votesAsset(["+" + delegateWallet1.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); secondSignatureVoteTransaction = BuilderFactory.vote() - .votesAsset(["+" + delegateWallet1.publicKey!]) + .votesAsset(["+" + delegateWallet1.getPublicKey()!]) .nonce("1") .sign(passphrases[1]) .secondSign(passphrases[2]) .build(); multiSignatureVoteTransaction = BuilderFactory.vote() - .senderPublicKey(multiSignatureWallet.publicKey!) - .votesAsset(["+" + delegateWallet1.publicKey!]) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) + .votesAsset(["+" + delegateWallet1.getPublicKey()!]) .nonce("1") .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) @@ -141,21 +141,21 @@ describe("VoteTransaction", () => { .build(); unvoteTransaction = BuilderFactory.vote() - .votesAsset(["-" + delegateWallet1.publicKey!]) + .votesAsset(["-" + delegateWallet1.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); secondSignatureUnvoteTransaction = BuilderFactory.vote() - .votesAsset(["-" + delegateWallet1.publicKey!]) + .votesAsset(["-" + delegateWallet1.getPublicKey()!]) .nonce("1") .sign(passphrases[1]) .secondSign(passphrases[2]) .build(); multiSignatureUnvoteTransaction = BuilderFactory.vote() - .senderPublicKey(multiSignatureWallet.publicKey!) - .votesAsset(["-" + delegateWallet1.publicKey!]) + .senderPublicKey(multiSignatureWallet.getPublicKey()!) + .votesAsset(["-" + delegateWallet1.getPublicKey()!]) .nonce("1") .multiSign(passphrases[0], 0) .multiSign(passphrases[1], 1) @@ -163,25 +163,25 @@ describe("VoteTransaction", () => { .build(); voteUnvoteTransaction = BuilderFactory.vote() - .votesAsset(["+" + delegateWallet1.publicKey!, "-" + delegateWallet1.publicKey!]) + .votesAsset(["+" + delegateWallet1.getPublicKey()!, "-" + delegateWallet1.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); unvoteVoteTransaction = BuilderFactory.vote() - .votesAsset(["-" + delegateWallet1.publicKey!, "+" + delegateWallet2.publicKey!]) + .votesAsset(["-" + delegateWallet1.getPublicKey()!, "+" + delegateWallet2.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); voteVoteTransaction = BuilderFactory.vote() - .votesAsset(["+" + delegateWallet1.publicKey!, "+" + delegateWallet2.publicKey!]) + .votesAsset(["+" + delegateWallet1.getPublicKey()!, "+" + delegateWallet2.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); unvoteUnvoteTransaction = BuilderFactory.vote() - .votesAsset(["-" + delegateWallet1.publicKey!, "-" + delegateWallet2.publicKey!]) + .votesAsset(["-" + delegateWallet1.getPublicKey()!, "-" + delegateWallet2.getPublicKey()!]) .nonce("1") .sign(passphrases[0]) .build(); @@ -206,7 +206,7 @@ describe("VoteTransaction", () => { transactionHistoryService.streamByCriteria.mockImplementationOnce(async function* () { yield voteTransaction.data; }); - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.bootstrap()).rejects.toThrow(AlreadyVotedError); }); @@ -304,26 +304,26 @@ describe("VoteTransaction", () => { }); it("should not throw if the unvote is valid and the wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.throwIfCannotBeApplied(unvoteTransaction, senderWallet)).toResolve(); }); it("should not throw - second sign unvote", async () => { - secondSignatureWallet.setAttribute("vote", delegateWallet1.publicKey); + secondSignatureWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect( handler.throwIfCannotBeApplied(secondSignatureUnvoteTransaction, secondSignatureWallet), ).toResolve(); }); it("should not throw - multi sign unvote", async () => { - multiSignatureWallet.setAttribute("vote", delegateWallet1.publicKey); + multiSignatureWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect( handler.throwIfCannotBeApplied(multiSignatureUnvoteTransaction, multiSignatureWallet), ).toResolve(); }); it("should throw if wallet has already voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.throwIfCannotBeApplied(voteTransaction, senderWallet)).rejects.toThrow( AlreadyVotedError, ); @@ -349,15 +349,15 @@ describe("VoteTransaction", () => { }); it("should throw if wallet has insufficient funds for vote", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; + senderWallet.setBalance(Utils.BigNumber.ZERO); await expect(handler.throwIfCannotBeApplied(voteTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); }); it("should throw if wallet has insufficient funds for unvote", async () => { - senderWallet.balance = Utils.BigNumber.ZERO; - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setBalance(Utils.BigNumber.ZERO); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.throwIfCannotBeApplied(unvoteTransaction, senderWallet)).rejects.toThrow( InsufficientBalanceError, ); @@ -384,7 +384,7 @@ describe("VoteTransaction", () => { }); it("should throw on vote+unvote transaction when wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.throwIfCannotBeApplied(voteUnvoteTransaction, senderWallet)).rejects.toThrow( AlreadyVotedError, @@ -392,7 +392,7 @@ describe("VoteTransaction", () => { }); it("should not throw on unvote+vote transaction when wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await handler.throwIfCannotBeApplied(unvoteVoteTransaction, senderWallet); }); @@ -410,7 +410,7 @@ describe("VoteTransaction", () => { }); it("should throw on unvote+unvote transaction when wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.throwIfCannotBeApplied(unvoteUnvoteTransaction, senderWallet)).rejects.toThrow( NoVoteError, @@ -442,7 +442,7 @@ describe("VoteTransaction", () => { }); it("should not be ok", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); expect(senderWallet.getAttribute("vote")).not.toBeUndefined(); @@ -454,7 +454,7 @@ describe("VoteTransaction", () => { describe("unvote", () => { it("should remove the vote from the wallet", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); expect(senderWallet.getAttribute("vote")).not.toBeUndefined(); @@ -472,7 +472,7 @@ describe("VoteTransaction", () => { }); it("should throw when wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await expect(handler.apply(voteUnvoteTransaction)).rejects.toThrow(AlreadyVotedError); }); @@ -480,11 +480,11 @@ describe("VoteTransaction", () => { describe("unvote+vote", () => { it("should apply when wallet has voted", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); await handler.apply(unvoteVoteTransaction); - expect(senderWallet.getAttribute("vote")).toEqual(delegateWallet2.publicKey); + expect(senderWallet.getAttribute("vote")).toEqual(delegateWallet2.getPublicKey()); }); it("should throw when wallet has not voted", async () => { @@ -492,7 +492,7 @@ describe("VoteTransaction", () => { }); it("should throw when wallet has voted for different delegate", async () => { - senderWallet.setAttribute("vote", delegateWallet2.publicKey); + senderWallet.setAttribute("vote", delegateWallet2.getPublicKey()); await expect(handler.apply(unvoteUnvoteTransaction)).rejects.toThrow(UnvoteMismatchError); }); @@ -520,34 +520,34 @@ describe("VoteTransaction", () => { describe("revert", () => { describe("vote", () => { it("should remove the vote from the wallet", async () => { - senderWallet.setAttribute("vote", delegateWallet1.publicKey); - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setAttribute("vote", delegateWallet1.getPublicKey()); + senderWallet.setNonce(Utils.BigNumber.make(1)); expect(senderWallet.getAttribute("vote")).not.toBeUndefined(); await handler.revert(voteTransaction); - expect(senderWallet.nonce.isZero()).toBeTrue(); + expect(senderWallet.getNonce().isZero()).toBeTrue(); expect(senderWallet.hasAttribute("vote")).toBeFalse(); }); }); describe("unvote", () => { it("should add the vote to the wallet", async () => { - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setNonce(Utils.BigNumber.make(1)); expect(senderWallet.hasAttribute("vote")).toBeFalse(); await handler.revert(unvoteTransaction); - expect(senderWallet.nonce.isZero()).toBeTrue(); - expect(senderWallet.getAttribute("vote")).toBe(delegateWallet1.publicKey); + expect(senderWallet.getNonce().isZero()).toBeTrue(); + expect(senderWallet.getAttribute("vote")).toBe(delegateWallet1.getPublicKey()); }); }); describe("vote+unvote", () => { it("should revert when wallet has no vote", async () => { - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setNonce(Utils.BigNumber.make(1)); await handler.revert(voteUnvoteTransaction); @@ -557,12 +557,12 @@ describe("VoteTransaction", () => { describe("unvote+vote", () => { it("should revert when wallet has no vote", async () => { - senderWallet.setAttribute("vote", delegateWallet2.publicKey); - senderWallet.nonce = Utils.BigNumber.make(1); + senderWallet.setAttribute("vote", delegateWallet2.getPublicKey()); + senderWallet.setNonce(Utils.BigNumber.make(1)); await handler.revert(unvoteVoteTransaction); - expect(senderWallet.getAttribute("vote")).toEqual(delegateWallet1.publicKey); + expect(senderWallet.getAttribute("vote")).toEqual(delegateWallet1.getPublicKey()); }); }); }); @@ -571,7 +571,7 @@ describe("VoteTransaction", () => { it("should throw if asset.vote is undefined", async () => { voteTransaction.data.asset!.votes = undefined; - senderWallet.nonce = Utils.BigNumber.ONE; + senderWallet.setNonce(Utils.BigNumber.ONE); await expect(handler.revertForSender(voteTransaction)).rejects.toThrow( Exceptions.Runtime.AssertionException, @@ -581,7 +581,7 @@ describe("VoteTransaction", () => { it("should throw if asset is undefined", async () => { voteTransaction.data.asset = undefined; - senderWallet.nonce = Utils.BigNumber.ONE; + senderWallet.setNonce(Utils.BigNumber.ONE); await expect(handler.revertForSender(voteTransaction)).rejects.toThrow( Exceptions.Runtime.AssertionException, diff --git a/packages/core-api/src/resources/block-with-transactions.ts b/packages/core-api/src/resources/block-with-transactions.ts index 94b132656a..2a9753bbc3 100644 --- a/packages/core-api/src/resources/block-with-transactions.ts +++ b/packages/core-api/src/resources/block-with-transactions.ts @@ -49,8 +49,8 @@ export class BlockWithTransactionsResource implements Resource { username: generator.hasAttribute("delegate.username") ? generator.getAttribute("delegate.username") : undefined, - address: generator.address, - publicKey: generator.publicKey, + address: generator.getAddress(), + publicKey: generator.getPublicKey(), }, signature: blockData.blockSignature, confirmations: lastBlock ? lastBlock.data.height - blockData.height : 0, diff --git a/packages/core-api/src/resources/transaction-with-block.ts b/packages/core-api/src/resources/transaction-with-block.ts index e1e68f4b09..947c36cea4 100644 --- a/packages/core-api/src/resources/transaction-with-block.ts +++ b/packages/core-api/src/resources/transaction-with-block.ts @@ -21,7 +21,7 @@ export class TransactionWithBlockResource implements Resource { AppUtils.assert.defined(transactionData.senderPublicKey); - const sender: string = this.walletRepository.findByPublicKey(transactionData.senderPublicKey).address; + const sender: string = this.walletRepository.findByPublicKey(transactionData.senderPublicKey).getAddress(); const recipient: string = transactionData.recipientId ?? sender; const signSignature: string | undefined = transactionData.signSignature ?? transactionData.secondSignature; const confirmations: number = this.stateStore.getLastHeight() - blockData.height + 1; diff --git a/packages/core-api/src/resources/transaction.ts b/packages/core-api/src/resources/transaction.ts index a151649ff5..660b84ab02 100644 --- a/packages/core-api/src/resources/transaction.ts +++ b/packages/core-api/src/resources/transaction.ts @@ -35,7 +35,7 @@ export class TransactionResource implements Resource { public transform(resource: Interfaces.ITransactionData): object { AppUtils.assert.defined(resource.senderPublicKey); - const sender: string = this.walletRepository.findByPublicKey(resource.senderPublicKey).address; + const sender: string = this.walletRepository.findByPublicKey(resource.senderPublicKey).getAddress(); return { id: resource.id, diff --git a/packages/core-api/src/services/delegate-search-service.ts b/packages/core-api/src/services/delegate-search-service.ts index 88877286f3..9f66b32c71 100644 --- a/packages/core-api/src/services/delegate-search-service.ts +++ b/packages/core-api/src/services/delegate-search-service.ts @@ -35,7 +35,7 @@ export class DelegateSearchService { } private getDelegateResourceFromWallet(wallet: Contracts.State.Wallet): DelegateResource { - AppUtils.assert.defined(wallet.publicKey); + AppUtils.assert.defined(wallet.getPublicKey()); const delegateAttribute = wallet.getAttribute("delegate"); @@ -51,8 +51,8 @@ export class DelegateSearchService { return { username: delegateAttribute.username, - address: wallet.address, - publicKey: wallet.publicKey, + address: wallet.getAddress(), + publicKey: wallet.getPublicKey()!, votes: delegateAttribute.voteBalance, rank: delegateAttribute.rank, isResigned: !!delegateAttribute.resigned, diff --git a/packages/core-api/src/services/lock-search-service.ts b/packages/core-api/src/services/lock-search-service.ts index f970c31479..123ab3408a 100644 --- a/packages/core-api/src/services/lock-search-service.ts +++ b/packages/core-api/src/services/lock-search-service.ts @@ -54,9 +54,9 @@ export class LockSearchService { AppUtils.assert.defined(lockAttribute); AppUtils.assert.defined(lockAttribute.recipientId); - AppUtils.assert.defined(wallet.publicKey); + AppUtils.assert.defined(wallet.getPublicKey()); - const senderPublicKey = wallet.publicKey; + const senderPublicKey = wallet.getPublicKey()!; const lastBlock = this.stateStore.getLastBlock(); const isExpired = AppUtils.expirationCalculator.calculateLockExpirationStatus( lastBlock, diff --git a/packages/core-api/src/services/wallet-search-service.ts b/packages/core-api/src/services/wallet-search-service.ts index 0b9b555990..96afd63074 100644 --- a/packages/core-api/src/services/wallet-search-service.ts +++ b/packages/core-api/src/services/wallet-search-service.ts @@ -58,10 +58,10 @@ export class WalletSearchService { private getWalletResourceFromWallet(wallet: Contracts.State.Wallet): WalletResource { return { - address: wallet.address, - publicKey: wallet.publicKey, - balance: wallet.balance, - nonce: wallet.nonce, + address: wallet.getAddress(), + publicKey: wallet.getPublicKey(), + balance: wallet.getBalance(), + nonce: wallet.getNonce(), attributes: wallet.getAttributes(), }; } diff --git a/packages/core-blockchain/src/processor/block-processor.ts b/packages/core-blockchain/src/processor/block-processor.ts index fba4ae5742..7a8a7780a7 100644 --- a/packages/core-blockchain/src/processor/block-processor.ts +++ b/packages/core-blockchain/src/processor/block-processor.ts @@ -236,14 +236,18 @@ export class BlockProcessor { block.data.generatorPublicKey }) is allowed to forge block ${block.data.height.toLocaleString()}`, ); - } /* istanbul ignore next */ else if (forgingDelegate.publicKey !== block.data.generatorPublicKey) { - AppUtils.assert.defined(forgingDelegate.publicKey); + } /* istanbul ignore next */ else if (forgingDelegate.getPublicKey() !== block.data.generatorPublicKey) { + AppUtils.assert.defined(forgingDelegate.getPublicKey()); - const forgingWallet: Contracts.State.Wallet = walletRepository.findByPublicKey(forgingDelegate.publicKey); + const forgingWallet: Contracts.State.Wallet = walletRepository.findByPublicKey( + forgingDelegate.getPublicKey()!, + ); const forgingUsername: string = forgingWallet.getAttribute("delegate.username"); this.logger.warning( - `Delegate ${generatorUsername} (${block.data.generatorPublicKey}) not allowed to forge, should be ${forgingUsername} (${forgingDelegate.publicKey})`, + `Delegate ${generatorUsername} (${ + block.data.generatorPublicKey + }) not allowed to forge, should be ${forgingUsername} (${forgingDelegate.getPublicKey()})`, ); return false; diff --git a/packages/core-blockchain/src/processor/handlers/unchained-handler.ts b/packages/core-blockchain/src/processor/handlers/unchained-handler.ts index ef568ad98e..ee6fe9c1bf 100644 --- a/packages/core-blockchain/src/processor/handlers/unchained-handler.ts +++ b/packages/core-blockchain/src/processor/handlers/unchained-handler.ts @@ -89,7 +89,7 @@ export class UnchainedHandler implements BlockHandler { roundInfo, })) as Contracts.State.Wallet[]; - if (delegates.some((delegate) => delegate.publicKey === block.data.generatorPublicKey)) { + if (delegates.some((delegate) => delegate.getPublicKey() === block.data.generatorPublicKey)) { return BlockProcessorResult.Rollback; } diff --git a/packages/core-database/src/repositories/round-repository.ts b/packages/core-database/src/repositories/round-repository.ts index 800ef6a36a..9e877cb3ae 100644 --- a/packages/core-database/src/repositories/round-repository.ts +++ b/packages/core-database/src/repositories/round-repository.ts @@ -25,7 +25,7 @@ export class RoundRepository extends Repository { public async save(delegates: readonly Contracts.State.Wallet[]): Promise { const round: { publicKey: string; balance: Utils.BigNumber; round: number }[] = delegates.map( (delegate: Contracts.State.Wallet) => ({ - publicKey: delegate.publicKey!, + publicKey: delegate.getPublicKey()!, balance: delegate.getAttribute("delegate.voteBalance"), round: delegate.getAttribute("delegate.round"), }), diff --git a/packages/core-database/src/transaction-filter.ts b/packages/core-database/src/transaction-filter.ts index 0d0bff2da7..ef7c0e1c78 100644 --- a/packages/core-database/src/transaction-filter.ts +++ b/packages/core-database/src/transaction-filter.ts @@ -120,8 +120,8 @@ export class TransactionFilter implements Contracts.Database.TransactionFilter { ): Promise> { const senderWallet = this.walletRepository.findByAddress(criteria); - if (senderWallet && senderWallet.publicKey) { - return { op: "equal", property: "senderPublicKey", value: senderWallet.publicKey }; + if (senderWallet && senderWallet.getPublicKey()) { + return { op: "equal", property: "senderPublicKey", value: senderWallet.getPublicKey() }; } else { return { op: "false" }; } @@ -146,13 +146,13 @@ export class TransactionFilter implements Contracts.Database.TransactionFilter { }; const recipientWallet = this.walletRepository.findByAddress(criteria); - if (recipientWallet && recipientWallet.publicKey) { + if (recipientWallet && recipientWallet.getPublicKey()) { const delegateRegistrationExpression: Contracts.Search.AndExpression = { op: "and", expressions: [ { op: "equal", property: "typeGroup", value: Enums.TransactionTypeGroup.Core }, { op: "equal", property: "type", value: Enums.TransactionType.DelegateRegistration }, - { op: "equal", property: "senderPublicKey", value: recipientWallet.publicKey }, + { op: "equal", property: "senderPublicKey", value: recipientWallet.getPublicKey() }, ], }; diff --git a/packages/core-database/src/wallets-table-service.ts b/packages/core-database/src/wallets-table-service.ts index 62bd08db29..2ef739b996 100644 --- a/packages/core-database/src/wallets-table-service.ts +++ b/packages/core-database/src/wallets-table-service.ts @@ -38,7 +38,7 @@ export class WalletsTableService implements Contracts.Database.WalletsTableServi const batchWallets = wallets.slice(i, i + batchSize); const params = batchWallets - .map((w) => [w.address, w.publicKey, w.balance.toFixed(), w.nonce.toFixed(), w.getAttributes()]) + .map((w) => [w.getAddress(), w.getPublicKey(), w.getBalance().toFixed(), w.getNonce().toFixed(), w.getAttributes()]) .flat(); const values = batchWallets diff --git a/packages/core-forger/src/delegate-tracker.ts b/packages/core-forger/src/delegate-tracker.ts index a18697535b..2e15bf566c 100644 --- a/packages/core-forger/src/delegate-tracker.ts +++ b/packages/core-forger/src/delegate-tracker.ts @@ -75,9 +75,10 @@ export class DelegateTracker { .get(Container.Identifiers.TriggerService) .call("getActiveDelegates", { roundInfo: round })) as Contracts.State.Wallet[]; - const activeDelegatesPublicKeys: (string | undefined)[] = activeDelegates.map( - (delegate: Contracts.State.Wallet) => delegate.publicKey, - ); + const activeDelegatesPublicKeys: ( + | string + | undefined + )[] = activeDelegates.map((delegate: Contracts.State.Wallet) => delegate.getPublicKey()); const blockTimeLookup = await Utils.forgingInfoCalculator.getBlockTimeLookup(this.app, height); diff --git a/packages/core-kernel/src/contracts/p2p/server.ts b/packages/core-kernel/src/contracts/p2p/server.ts index 91a7b461fd..53fdf9f764 100644 --- a/packages/core-kernel/src/contracts/p2p/server.ts +++ b/packages/core-kernel/src/contracts/p2p/server.ts @@ -1,12 +1,12 @@ import { Interfaces } from "@arkecosystem/crypto"; -import { Wallet, WalletDelegateAttributes } from "../state"; +import { WalletData, WalletDelegateAttributes } from "../state"; export interface Response { data: T; } -export interface DelegateWallet extends Wallet { +export interface DelegateWallet extends WalletData { delegate: WalletDelegateAttributes; } diff --git a/packages/core-kernel/src/contracts/state/wallets.ts b/packages/core-kernel/src/contracts/state/wallets.ts index 551da87fbc..6b07615b92 100644 --- a/packages/core-kernel/src/contracts/state/wallets.ts +++ b/packages/core-kernel/src/contracts/state/wallets.ts @@ -33,30 +33,38 @@ export enum WalletIndexes { BridgeChains = "bridgechains", } -export interface Wallet { - /** - * @type {string} - * @memberof Wallet - */ +export interface WalletData { address: string; + publicKey?: string; + balance: Utils.BigNumber; + nonce: Utils.BigNumber; + attributes: Record; +} - /** - * @type {(string | undefined)} - * @memberof Wallet - */ - publicKey: string | undefined; +export interface Wallet { + getAddress(): string; - /** - * @type {Utils.BigNumber} - * @memberof Wallet - */ - balance: Utils.BigNumber; + getPublicKey(): string | undefined; - /** - * @type {Utils.BigNumber} - * @memberof Wallet - */ - nonce: Utils.BigNumber; + setPublicKey(publicKey: string): void; + + getBalance(): Utils.BigNumber; + + setBalance(balance: Utils.BigNumber): void; + + getNonce(): Utils.BigNumber; + + setNonce(nonce: Utils.BigNumber): void; + + increaseBalance(balance: Utils.BigNumber): Wallet; + + decreaseBalance(balance: Utils.BigNumber): Wallet; + + increaseNonce(): void; + + decreaseNonce(): void; + + getData(): WalletData; /** * @returns {Record} diff --git a/packages/core-magistrate-api/src/services/entity-search-service.ts b/packages/core-magistrate-api/src/services/entity-search-service.ts index 19ad88832c..6afaa3a248 100644 --- a/packages/core-magistrate-api/src/services/entity-search-service.ts +++ b/packages/core-magistrate-api/src/services/entity-search-service.ts @@ -39,12 +39,12 @@ export class EntitySearchService { const entityAttribute = entitiesAttribute[entityId]; AppUtils.assert.defined(entityAttribute); - AppUtils.assert.defined(wallet.publicKey); + AppUtils.assert.defined(wallet.getPublicKey()); return { id: entityId, - address: wallet.address, - publicKey: wallet.publicKey, + address: wallet.getAddress(), + publicKey: wallet.getPublicKey()!, isResigned: !!entityAttribute.resigned, type: entityAttribute.type, subType: entityAttribute.subType, diff --git a/packages/core-magistrate-transactions/src/handlers/bridgechain-update.ts b/packages/core-magistrate-transactions/src/handlers/bridgechain-update.ts index beb91799d8..d7cfd3efd8 100644 --- a/packages/core-magistrate-transactions/src/handlers/bridgechain-update.ts +++ b/packages/core-magistrate-transactions/src/handlers/bridgechain-update.ts @@ -178,7 +178,7 @@ export class BridgechainUpdateTransactionHandler extends MagistrateTransactionHa // Here we have to "replay" all bridgechain registration and update transactions for this bridgechain id // (except the current one being reverted) to rebuild previous wallet state. const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); - AppUtils.assert.defined(sender.publicKey); + AppUtils.assert.defined(sender.getPublicKey()); const businessAttributes: IBusinessWalletAttributes = sender.getAttribute( "business", @@ -187,13 +187,13 @@ export class BridgechainUpdateTransactionHandler extends MagistrateTransactionHa const bridgechainTransactions = await this.transactionHistoryService.findManyByCriteria([ { - senderPublicKey: sender.publicKey, + senderPublicKey: sender.getPublicKey()!, typeGroup: Enums.MagistrateTransactionGroup, type: Enums.MagistrateTransactionType.BridgechainRegistration, asset: { bridgechainRegistration: { genesisHash: bridgechainId } }, }, { - senderPublicKey: sender.publicKey, + senderPublicKey: sender.getPublicKey()!, typeGroup: Enums.MagistrateTransactionGroup, type: Enums.MagistrateTransactionType.BridgechainUpdate, asset: { bridgechainUpdateAsset: { bridgechainId: bridgechainId } }, diff --git a/packages/core-magistrate-transactions/src/handlers/business-update.ts b/packages/core-magistrate-transactions/src/handlers/business-update.ts index 83e0fe3ed6..50dd140abd 100644 --- a/packages/core-magistrate-transactions/src/handlers/business-update.ts +++ b/packages/core-magistrate-transactions/src/handlers/business-update.ts @@ -119,16 +119,16 @@ export class BusinessUpdateTransactionHandler extends MagistrateTransactionHandl // Here we have to "replay" all business registration and update transactions // (except the current one being reverted) to rebuild previous wallet state. const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); - AppUtils.assert.defined(sender.publicKey); + AppUtils.assert.defined(sender.getPublicKey()); const businessTransactions = await this.transactionHistoryService.findManyByCriteria([ { - senderPublicKey: sender.publicKey, + senderPublicKey: sender.getPublicKey()!, typeGroup: Enums.MagistrateTransactionGroup, type: Enums.MagistrateTransactionType.BusinessRegistration, }, { - senderPublicKey: sender.publicKey, + senderPublicKey: sender.getPublicKey()!, typeGroup: Enums.MagistrateTransactionGroup, type: Enums.MagistrateTransactionType.BusinessUpdate, }, diff --git a/packages/core-magistrate-transactions/src/wallet-indexes.ts b/packages/core-magistrate-transactions/src/wallet-indexes.ts index bcda9ae774..b3aabe3d49 100644 --- a/packages/core-magistrate-transactions/src/wallet-indexes.ts +++ b/packages/core-magistrate-transactions/src/wallet-indexes.ts @@ -8,8 +8,8 @@ export enum MagistrateIndex { export const businessIndexer = (index: Contracts.State.WalletIndex, wallet: Contracts.State.Wallet): void => { if (wallet.hasAttribute("business")) { - Utils.assert.defined(wallet.publicKey); - index.set(wallet.publicKey, wallet); + Utils.assert.defined(wallet.getPublicKey()); + index.set(wallet.getPublicKey()!, wallet); } }; diff --git a/packages/core-p2p/src/peer-verifier.ts b/packages/core-p2p/src/peer-verifier.ts index 209f77ce83..8aa96dc8ac 100644 --- a/packages/core-p2p/src/peer-verifier.ts +++ b/packages/core-p2p/src/peer-verifier.ts @@ -418,8 +418,8 @@ export class PeerVerifier implements Contracts.P2P.PeerVerifier { const delegatesByPublicKey: Record = {}; for (const delegate of delegates) { - Utils.assert.defined(delegate.publicKey); - delegatesByPublicKey[delegate.publicKey] = delegate; + Utils.assert.defined(delegate.getPublicKey()); + delegatesByPublicKey[delegate.getPublicKey()!] = delegate; } return delegatesByPublicKey; } diff --git a/packages/core-p2p/src/socket-server/controllers/internal.ts b/packages/core-p2p/src/socket-server/controllers/internal.ts index 68dce46c11..f5ee19632f 100644 --- a/packages/core-p2p/src/socket-server/controllers/internal.ts +++ b/packages/core-p2p/src/socket-server/controllers/internal.ts @@ -60,7 +60,7 @@ export class InternalController extends Controller { const delegates: Contracts.P2P.DelegateWallet[] = ( await this.databaseInteraction.getActiveDelegates(roundInfo) ).map((wallet) => ({ - ...wallet, + ...wallet.getData(), delegate: wallet.getAttribute("delegate"), })); diff --git a/packages/core-state/src/block-state.ts b/packages/core-state/src/block-state.ts index 8dfba5329c..10641193ae 100644 --- a/packages/core-state/src/block-state.ts +++ b/packages/core-state/src/block-state.ts @@ -203,7 +203,7 @@ export class BlockState implements Contracts.State.BlockState { const balanceIncrease = blockData.reward.plus(blockData.totalFee); this.increaseWalletDelegateVoteBalance(forgerWallet, balanceIncrease); - forgerWallet.balance = forgerWallet.balance.plus(balanceIncrease); + forgerWallet.increaseBalance(balanceIncrease); } private revertBlockFromForger(forgerWallet: Contracts.State.Wallet, blockData: Interfaces.IBlockData) { @@ -215,7 +215,7 @@ export class BlockState implements Contracts.State.BlockState { const balanceDecrease = blockData.reward.plus(blockData.totalFee); this.decreaseWalletDelegateVoteBalance(forgerWallet, balanceDecrease); - forgerWallet.balance = forgerWallet.balance.minus(balanceDecrease); + forgerWallet.decreaseBalance(balanceDecrease); } /** @@ -245,7 +245,7 @@ export class BlockState implements Contracts.State.BlockState { const senderDelegatedAmount = sender .getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO) - .plus(sender.balance) + .plus(sender.getBalance()) // balance already includes reverted fee when updateVoteBalances is called .minus(revert ? transaction.fee : Utils.BigNumber.ZERO); @@ -393,7 +393,7 @@ export class BlockState implements Contracts.State.BlockState { const forgerAddress = Identities.Address.fromPublicKey(forgerPublicKey); const forgerWallet = this.walletRepository.createWallet(forgerAddress); - forgerWallet.publicKey = forgerPublicKey; + forgerWallet.setPublicKey(forgerPublicKey); this.walletRepository.index(forgerWallet); } } diff --git a/packages/core-state/src/dpos/dpos.ts b/packages/core-state/src/dpos/dpos.ts index 77528f17d4..49c228a322 100644 --- a/packages/core-state/src/dpos/dpos.ts +++ b/packages/core-state/src/dpos/dpos.ts @@ -44,7 +44,7 @@ export class DposState implements Contracts.State.DposState { const voteBalance: Utils.BigNumber = delegate.getAttribute("delegate.voteBalance"); const lockedBalance = voter.getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO); - delegate.setAttribute("delegate.voteBalance", voteBalance.plus(voter.balance).plus(lockedBalance)); + delegate.setAttribute("delegate.voteBalance", voteBalance.plus(voter.getBalance()).plus(lockedBalance)); } } } @@ -67,10 +67,10 @@ export class DposState implements Contracts.State.DposState { const diff = voteBalanceB.comparedTo(voteBalanceA); if (diff === 0) { - AppUtils.assert.defined(a.publicKey); - AppUtils.assert.defined(b.publicKey); + AppUtils.assert.defined(a.getPublicKey()); + AppUtils.assert.defined(b.getPublicKey()); - if (a.publicKey === b.publicKey) { + if (a.getPublicKey() === b.getPublicKey()) { const username = a.getAttribute("delegate.username"); throw new Error( `The balance and public key of both delegates are identical! ` + @@ -78,7 +78,7 @@ export class DposState implements Contracts.State.DposState { ); } - return a.publicKey.localeCompare(b.publicKey, "en"); + return a.getPublicKey()!.localeCompare(b.getPublicKey()!, "en"); } return diff; diff --git a/packages/core-state/src/round-state.ts b/packages/core-state/src/round-state.ts index 0e0dc523d2..e8bc0cda9c 100644 --- a/packages/core-state/src/round-state.ts +++ b/packages/core-state/src/round-state.ts @@ -90,7 +90,7 @@ export class RoundState { delegates = (await this.databaseService.getRound(roundInfo.round)).map(({ publicKey, balance }) => { // ! find wallet by public key and clone it const wallet = this.walletRepository.createWallet(Identities.Address.fromPublicKey(publicKey)); - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); const delegate = { voteBalance: Utils.BigNumber.make(balance), @@ -129,7 +129,9 @@ export class RoundState { const delegate: Contracts.State.Wallet = this.forgingDelegates[missedSlot % this.forgingDelegates.length]; this.logger.debug( - `Delegate ${delegate.getAttribute("delegate.username")} (${delegate.publicKey}) just missed a block.`, + `Delegate ${delegate.getAttribute( + "delegate.username", + )} (${delegate.getPublicKey()}) just missed a block.`, ); this.events.dispatch(Enums.ForgerEvent.Missing, { @@ -178,14 +180,16 @@ export class RoundState { private detectMissedRound(): void { for (const delegate of this.forgingDelegates) { const isBlockProduced = this.blocksInCurrentRound.some( - (blockGenerator) => blockGenerator.data.generatorPublicKey === delegate.publicKey, + (blockGenerator) => blockGenerator.data.generatorPublicKey === delegate.getPublicKey(), ); if (!isBlockProduced) { - const wallet: Contracts.State.Wallet = this.walletRepository.findByPublicKey(delegate.publicKey!); + const wallet: Contracts.State.Wallet = this.walletRepository.findByPublicKey(delegate.getPublicKey()!); this.logger.debug( - `Delegate ${wallet.getAttribute("delegate.username")} (${wallet.publicKey}) just missed a round.`, + `Delegate ${wallet.getAttribute( + "delegate.username", + )} (${wallet.getPublicKey()}) just missed a round.`, ); this.events.dispatch(Enums.RoundEvent.Missed, { diff --git a/packages/core-state/src/state-builder.ts b/packages/core-state/src/state-builder.ts index 5b8739aabd..c5974cccf4 100644 --- a/packages/core-state/src/state-builder.ts +++ b/packages/core-state/src/state-builder.ts @@ -63,7 +63,9 @@ export class StateBuilder { this.dposState.buildDelegateRanking(); this.logger.info( - `Number of registered delegates: ${Object.keys(this.walletRepository.allByUsername()).length.toLocaleString()}`, + `Number of registered delegates: ${Object.keys( + this.walletRepository.allByUsername(), + ).length.toLocaleString()}`, ); this.verifyWalletsConsistency(); @@ -79,7 +81,7 @@ export class StateBuilder { for (const block of blocks) { const wallet = this.walletRepository.findByPublicKey(block.generatorPublicKey); - wallet.balance = wallet.balance.plus(block.rewards); + wallet.increaseBalance(Utils.BigNumber.make(block.rewards)); } } @@ -88,8 +90,8 @@ export class StateBuilder { for (const transaction of transactions) { const wallet = this.walletRepository.findByPublicKey(transaction.senderPublicKey); - wallet.nonce = Utils.BigNumber.make(transaction.nonce); - wallet.balance = wallet.balance.minus(transaction.amount).minus(transaction.fee); + wallet.setNonce(Utils.BigNumber.make(transaction.nonce)); + wallet.decreaseBalance(Utils.BigNumber.make(transaction.amount).plus(transaction.fee)); } } @@ -103,8 +105,8 @@ export class StateBuilder { for (const wallet of this.walletRepository.allByAddress()) { if ( - wallet.balance.isLessThan(0) && - (wallet.publicKey === undefined || !genesisPublicKeys[wallet.publicKey]) + wallet.getBalance().isLessThan(0) && + (wallet.getPublicKey() === undefined || !genesisPublicKeys[wallet.getPublicKey()!]) ) { // Senders of whitelisted transactions that result in a negative balance, // also need to be special treated during bootstrap. Therefore, specific @@ -117,21 +119,21 @@ export class StateBuilder { {}, ); - const whitelistedNegativeBalances: Record | undefined = wallet.publicKey - ? negativeBalanceExceptions[wallet.publicKey] + const whitelistedNegativeBalances: Record | undefined = wallet.getPublicKey() + ? negativeBalanceExceptions[wallet.getPublicKey()!] : undefined; if (!whitelistedNegativeBalances) { - logNegativeBalance(wallet, "balance", wallet.balance); + logNegativeBalance(wallet, "balance", wallet.getBalance()); throw new Error("Non-genesis wallet with negative balance."); } - const allowedNegativeBalance = wallet.balance.isEqualTo( - whitelistedNegativeBalances[wallet.nonce.toString()], - ); + const allowedNegativeBalance = wallet + .getBalance() + .isEqualTo(whitelistedNegativeBalances[wallet.getNonce().toString()]); if (!allowedNegativeBalance) { - logNegativeBalance(wallet, "balance", wallet.balance); + logNegativeBalance(wallet, "balance", wallet.getBalance()); throw new Error("Non-genesis wallet with negative balance."); } } diff --git a/packages/core-state/src/wallets/indexers/indexers.ts b/packages/core-state/src/wallets/indexers/indexers.ts index e583b0df79..40adb807ca 100644 --- a/packages/core-state/src/wallets/indexers/indexers.ts +++ b/packages/core-state/src/wallets/indexers/indexers.ts @@ -1,14 +1,14 @@ import { Contracts } from "@arkecosystem/core-kernel"; export const addressesIndexer = (index: Contracts.State.WalletIndex, wallet: Contracts.State.Wallet) => { - if (wallet.address) { - index.set(wallet.address, wallet); + if (wallet.getAddress()) { + index.set(wallet.getAddress(), wallet); } }; export const publicKeysIndexer = (index: Contracts.State.WalletIndex, wallet: Contracts.State.Wallet) => { - if (wallet.publicKey) { - index.set(wallet.publicKey, wallet); + if (wallet.getPublicKey()) { + index.set(wallet.getPublicKey()!, wallet); } }; diff --git a/packages/core-state/src/wallets/wallet-repository-clone.ts b/packages/core-state/src/wallets/wallet-repository-clone.ts index 2b927eaeda..34c1df8286 100644 --- a/packages/core-state/src/wallets/wallet-repository-clone.ts +++ b/packages/core-state/src/wallets/wallet-repository-clone.ts @@ -64,7 +64,7 @@ export class WalletRepositoryClone extends WalletRepository { public findByPublicKey(publicKey: string): Contracts.State.Wallet { if (!super.hasByIndex(Contracts.State.WalletIndexes.PublicKeys, publicKey)) { const wallet = this.findByAddress(Identities.Address.fromPublicKey(publicKey)); - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); super.index(wallet); } @@ -111,11 +111,11 @@ export class WalletRepositoryClone extends WalletRepository { public getNonce(publicKey: string): Utils.BigNumber { if (this.getIndex(Contracts.State.WalletIndexes.PublicKeys).has(publicKey)) { - return this.findByPublicKey(publicKey).nonce; + return this.findByPublicKey(publicKey).getNonce(); } if (this.blockchainWalletRepository.hasByPublicKey(publicKey)) { - return this.blockchainWalletRepository.findByPublicKey(publicKey).nonce; + return this.blockchainWalletRepository.findByPublicKey(publicKey).getNonce(); } return Utils.BigNumber.ZERO; @@ -166,7 +166,7 @@ export class WalletRepositoryClone extends WalletRepository { private cloneAllByIndex(indexName: string) { for (const wallet of this.blockchainWalletRepository.getIndex(indexName).values()) { - this.findByAddress(wallet.address); + this.findByAddress(wallet.getAddress()); } } } diff --git a/packages/core-state/src/wallets/wallet-repository-copy-on-write.ts b/packages/core-state/src/wallets/wallet-repository-copy-on-write.ts index 4828cd5940..b7e2ab53cd 100644 --- a/packages/core-state/src/wallets/wallet-repository-copy-on-write.ts +++ b/packages/core-state/src/wallets/wallet-repository-copy-on-write.ts @@ -33,7 +33,7 @@ export class WalletRepositoryCopyOnWrite extends WalletRepository { public allByUsername(): ReadonlyArray { for (const wallet of this.blockchainWalletRepository.allByUsername()) { - if (!super.hasByAddress(wallet.address)) { + if (!super.hasByAddress(wallet.getAddress())) { this.cloneWallet(this.blockchainWalletRepository, wallet); } } diff --git a/packages/core-state/src/wallets/wallet-repository.ts b/packages/core-state/src/wallets/wallet-repository.ts index 86bef328f4..9d78106c18 100644 --- a/packages/core-state/src/wallets/wallet-repository.ts +++ b/packages/core-state/src/wallets/wallet-repository.ts @@ -70,7 +70,7 @@ export class WalletRepository implements Contracts.State.WalletRepository { const index = this.getIndex(Contracts.State.WalletIndexes.PublicKeys); if (publicKey && !index.has(publicKey)) { const wallet = this.findByAddress(Identities.Address.fromPublicKey(publicKey)); - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); index.set(publicKey, wallet); } const wallet: Contracts.State.Wallet | undefined = index.get(publicKey); @@ -120,7 +120,7 @@ export class WalletRepository implements Contracts.State.WalletRepository { public getNonce(publicKey: string): Utils.BigNumber { if (this.hasByPublicKey(publicKey)) { - return this.findByPublicKey(publicKey).nonce; + return this.findByPublicKey(publicKey).getNonce(); } return Utils.BigNumber.ZERO; diff --git a/packages/core-state/src/wallets/wallet.ts b/packages/core-state/src/wallets/wallet.ts index 19800400e0..07dc395ddc 100644 --- a/packages/core-state/src/wallets/wallet.ts +++ b/packages/core-state/src/wallets/wallet.ts @@ -1,53 +1,105 @@ import { Contracts, Services } from "@arkecosystem/core-kernel"; import { Utils } from "@arkecosystem/crypto"; + import { WalletEvent } from "./wallet-event"; export class Wallet implements Contracts.State.Wallet { - /** - * @type {(string | undefined)} - * @memberof Wallet - */ - public publicKey: string | undefined; - - /** - * @type {Utils.BigNumber} - * @memberof Wallet - */ - public balance: Utils.BigNumber = Utils.BigNumber.ZERO; + protected publicKey: string | undefined; + protected balance: Utils.BigNumber = Utils.BigNumber.ZERO; + protected nonce: Utils.BigNumber = Utils.BigNumber.ZERO; - /** - * @type {Utils.BigNumber} - * @memberof Wallet - */ - public nonce: Utils.BigNumber = Utils.BigNumber.ZERO; - - /** - * @param {string} address - * @memberof Wallet - */ public constructor( - public readonly address: string, + protected readonly address: string, protected readonly attributes: Services.Attributes.AttributeMap, protected readonly events?: Contracts.Kernel.EventDispatcher, - ) { - const proxy = new Proxy(this, { - set: (_, key, value): boolean => { - const previousValue = this[key]; - this[key] = value; - - this.events?.dispatchSync(WalletEvent.PropertySet, { - publicKey: undefined, - key, - value, - previousValue, - wallet: this, - }); - - return true; - }, + ) {} + + public getAddress(): string { + return this.address; + } + + public getPublicKey(): string | undefined { + return this.publicKey; + } + + public setPublicKey(publicKey: string): void { + const previousValue = this.publicKey; + + this.publicKey = publicKey; + + this.events?.dispatchSync(WalletEvent.PropertySet, { + publicKey: this.publicKey, + key: "publicKey", + value: publicKey, + previousValue, + wallet: this, }); + } + + public getBalance(): Utils.BigNumber { + return this.balance; + } + + public setBalance(balance: Utils.BigNumber): void { + const previousValue = this.balance; - return proxy; + this.balance = balance; + + this.events?.dispatchSync(WalletEvent.PropertySet, { + publicKey: this.publicKey, + key: "balance", + value: balance, + previousValue, + wallet: this, + }); + } + + public getNonce(): Utils.BigNumber { + return this.nonce; + } + + public setNonce(nonce: Utils.BigNumber): void { + const previousValue = this.nonce; + + this.nonce = nonce; + + this.events?.dispatchSync(WalletEvent.PropertySet, { + publicKey: this.publicKey, + key: "nonce", + value: nonce, + previousValue, + wallet: this, + }); + } + + public increaseBalance(balance: Utils.BigNumber): Contracts.State.Wallet { + this.setBalance(this.balance.plus(balance)); + + return this; + } + + public decreaseBalance(balance: Utils.BigNumber): Contracts.State.Wallet { + this.setBalance(this.balance.minus(balance)); + + return this; + } + + public increaseNonce(): void { + this.setNonce(this.nonce.plus(Utils.BigNumber.ONE)); + } + + public decreaseNonce(): void { + this.setNonce(this.nonce.minus(Utils.BigNumber.ONE)); + } + + public getData(): Contracts.State.WalletData { + return { + address: this.address, + publicKey: this.publicKey, + balance: this.balance, + nonce: this.nonce, + attributes: this.attributes, + }; } /** diff --git a/packages/core-test-framework/src/factories/factories/round.ts b/packages/core-test-framework/src/factories/factories/round.ts index c3648cdf44..2405dac409 100644 --- a/packages/core-test-framework/src/factories/factories/round.ts +++ b/packages/core-test-framework/src/factories/factories/round.ts @@ -14,7 +14,7 @@ export const registerRoundFactory = (factory: FactoryBuilder): void => { return publicKeys.map((publicKey: string, i: number) => { const wallet = new Wallets.Wallet(Identities.Address.fromPublicKey(publicKey), knownAttributes); - wallet.publicKey = publicKey; + wallet.setPublicKey(publicKey); wallet.setAttribute("delegate", { username: `genesis_${i + 1}`, diff --git a/packages/core-test-framework/src/factories/factories/wallet.ts b/packages/core-test-framework/src/factories/factories/wallet.ts index aea4f2439e..10c60647f1 100644 --- a/packages/core-test-framework/src/factories/factories/wallet.ts +++ b/packages/core-test-framework/src/factories/factories/wallet.ts @@ -14,7 +14,7 @@ export const registerWalletFactory = (factory: FactoryBuilder): void => { Identities.Address.fromPassphrase(passphrase), new Services.Attributes.AttributeMap(getWalletAttributeSet()), ); - wallet.publicKey = Identities.PublicKey.fromPassphrase(passphrase); + wallet.setPublicKey(Identities.PublicKey.fromPassphrase(passphrase)); return wallet; }); diff --git a/packages/core-transactions/src/errors.ts b/packages/core-transactions/src/errors.ts index 3d7b215801..0b85b31f43 100644 --- a/packages/core-transactions/src/errors.ts +++ b/packages/core-transactions/src/errors.ts @@ -48,7 +48,7 @@ export class UnexpectedNonceError extends TransactionError { const action: string = reversal ? "revert" : "apply"; super( `Cannot ${action} a transaction with nonce ${txNonce.toFixed()}: the ` + - `sender ${sender.publicKey} has nonce ${sender.nonce.toFixed()}.`, + `sender ${sender.getPublicKey()} has nonce ${sender.getNonce().toFixed()}.`, ); } } diff --git a/packages/core-transactions/src/handlers/one/transfer.ts b/packages/core-transactions/src/handlers/one/transfer.ts index 164f640501..894aa60943 100644 --- a/packages/core-transactions/src/handlers/one/transfer.ts +++ b/packages/core-transactions/src/handlers/one/transfer.ts @@ -55,7 +55,7 @@ export class TransferTransactionHandler extends TransactionHandler { const recipient: Contracts.State.Wallet = this.walletRepository.findByAddress(transaction.data.recipientId); - recipient.balance = recipient.balance.plus(transaction.data.amount); + recipient.increaseBalance(transaction.data.amount); } public async revertForRecipient(transaction: Interfaces.ITransaction): Promise { @@ -63,6 +63,6 @@ export class TransferTransactionHandler extends TransactionHandler { const recipient: Contracts.State.Wallet = this.walletRepository.findByAddress(transaction.data.recipientId); - recipient.balance = recipient.balance.minus(transaction.data.amount); + recipient.decreaseBalance(transaction.data.amount); } } diff --git a/packages/core-transactions/src/handlers/transaction.ts b/packages/core-transactions/src/handlers/transaction.ts index 33073d2b31..ba8eec5283 100644 --- a/packages/core-transactions/src/handlers/transaction.ts +++ b/packages/core-transactions/src/handlers/transaction.ts @@ -68,11 +68,11 @@ export abstract class TransactionHandler { transaction: Interfaces.ITransaction, sender: Contracts.State.Wallet, ): Promise { - const senderWallet: Contracts.State.Wallet = this.walletRepository.findByAddress(sender.address); + const senderWallet: Contracts.State.Wallet = this.walletRepository.findByAddress(sender.getAddress()); - AppUtils.assert.defined(sender.publicKey); + AppUtils.assert.defined(sender.getPublicKey()); - if (!this.walletRepository.hasByPublicKey(sender.publicKey) && senderWallet.balance.isZero()) { + if (!this.walletRepository.hasByPublicKey(sender.getPublicKey()!) && senderWallet.getBalance().isZero()) { throw new ColdWalletError(); } @@ -108,12 +108,12 @@ export abstract class TransactionHandler { AppUtils.assert.defined(data.nonce); - sender.nonce = data.nonce; + sender.setNonce(data.nonce); } else { - sender.nonce = sender.nonce.plus(1); + sender.increaseNonce(); } - const newBalance: Utils.BigNumber = sender.balance.minus(data.amount).minus(data.fee); + const newBalance: Utils.BigNumber = sender.getBalance().minus(data.amount).minus(data.fee); assert(Utils.isException(transaction.data) || !newBalance.isNegative()); @@ -135,7 +135,7 @@ export abstract class TransactionHandler { // } // } - sender.balance = newBalance; + sender.setBalance(newBalance); } public async revertForSender(transaction: Interfaces.ITransaction): Promise { @@ -145,12 +145,12 @@ export abstract class TransactionHandler { const data: Interfaces.ITransactionData = transaction.data; - sender.balance = sender.balance.plus(data.amount).plus(data.fee); + sender.increaseBalance(data.amount.plus(data.fee)); // TODO: extract version specific code this.verifyTransactionNonceRevert(sender, transaction); - sender.nonce = sender.nonce.minus(1); + sender.decreaseNonce(); } /** @@ -193,11 +193,11 @@ export abstract class TransactionHandler { this.verifyTransactionNonceApply(sender, transaction); - if (sender.balance.minus(data.amount).minus(data.fee).isNegative()) { + if (sender.getBalance().minus(data.amount).minus(data.fee).isNegative()) { throw new InsufficientBalanceError(); } - if (data.senderPublicKey !== sender.publicKey) { + if (data.senderPublicKey !== sender.getPublicKey()) { throw new SenderWalletMismatchError(); } @@ -266,7 +266,7 @@ export abstract class TransactionHandler { const version: number = transaction.data.version || 1; const nonce: AppUtils.BigNumber = transaction.data.nonce || AppUtils.BigNumber.ZERO; - if (version > 1 && !wallet.nonce.plus(1).isEqualTo(nonce)) { + if (version > 1 && !wallet.getNonce().plus(1).isEqualTo(nonce)) { throw new UnexpectedNonceError(nonce, wallet, false); } } @@ -283,7 +283,7 @@ export abstract class TransactionHandler { const version: number = transaction.data.version || 1; const nonce: AppUtils.BigNumber = transaction.data.nonce || AppUtils.BigNumber.ZERO; - if (version > 1 && !wallet.nonce.isEqualTo(nonce)) { + if (version > 1 && !wallet.getNonce().isEqualTo(nonce)) { throw new UnexpectedNonceError(nonce, wallet, true); } } diff --git a/packages/core-transactions/src/handlers/two/htlc-claim.ts b/packages/core-transactions/src/handlers/two/htlc-claim.ts index 584a532659..145b66728d 100644 --- a/packages/core-transactions/src/handlers/two/htlc-claim.ts +++ b/packages/core-transactions/src/handlers/two/htlc-claim.ts @@ -27,7 +27,7 @@ export class HtlcClaimTransactionHandler extends TransactionHandler { const balances = await this.transactionRepository.getClaimedHtlcLockBalances(); for (const { recipientId, claimedBalance } of balances) { const claimWallet: Contracts.State.Wallet = this.walletRepository.findByAddress(recipientId); - claimWallet.balance = claimWallet.balance.plus(claimedBalance); + claimWallet.increaseBalance(Utils.BigNumber.make(claimedBalance)); } } @@ -124,7 +124,7 @@ export class HtlcClaimTransactionHandler extends TransactionHandler { AppUtils.assert.defined(data.nonce); - sender.nonce = data.nonce; + sender.setNonce(data.nonce); AppUtils.assert.defined(data.asset?.claim?.lockTransactionId); @@ -144,9 +144,7 @@ export class HtlcClaimTransactionHandler extends TransactionHandler { const recipientWallet: Contracts.State.Wallet = this.walletRepository.findByAddress(recipientId); - const newBalance: Utils.BigNumber = recipientWallet.balance.plus(locks[lockId].amount).minus(data.fee); - - recipientWallet.balance = newBalance; + recipientWallet.increaseBalance(locks[lockId].amount.minus(data.fee)); const lockedBalance: Utils.BigNumber = lockWallet.getAttribute("htlc.lockedBalance"); const newLockedBalance: Utils.BigNumber = lockedBalance.minus(locks[lockId].amount); @@ -176,7 +174,7 @@ export class HtlcClaimTransactionHandler extends TransactionHandler { this.verifyTransactionNonceRevert(sender, transaction); - sender.nonce = sender.nonce.minus(1); + sender.decreaseNonce(); AppUtils.assert.defined(transaction.data.senderPublicKey); AppUtils.assert.defined(data.asset?.claim?.lockTransactionId); @@ -190,7 +188,7 @@ export class HtlcClaimTransactionHandler extends TransactionHandler { const recipientWallet: Contracts.State.Wallet = this.walletRepository.findByAddress( lockTransaction.recipientId, ); - recipientWallet.balance = recipientWallet.balance.minus(lockTransaction.amount).plus(data.fee); + recipientWallet.decreaseBalance(lockTransaction.amount.minus(data.fee)); AppUtils.assert.defined(lockTransaction.senderPublicKey); diff --git a/packages/core-transactions/src/handlers/two/htlc-lock.ts b/packages/core-transactions/src/handlers/two/htlc-lock.ts index 5e45c7f049..d94f818839 100644 --- a/packages/core-transactions/src/handlers/two/htlc-lock.ts +++ b/packages/core-transactions/src/handlers/two/htlc-lock.ts @@ -44,8 +44,8 @@ export class HtlcLockTransactionHandler extends TransactionHandler { const recipientWallet: Contracts.State.Wallet = this.walletRepository.findByAddress( transaction.recipientId, ); - walletsToIndex[wallet.address] = wallet; - walletsToIndex[recipientWallet.address] = recipientWallet; + walletsToIndex[wallet.getAddress()] = wallet; + walletsToIndex[recipientWallet.getAddress()] = recipientWallet; wallet.setAttribute("htlc.locks", locks); wallet.setAttribute("htlc.lockedBalance", lockedBalance); diff --git a/packages/core-transactions/src/handlers/two/htlc-refund.ts b/packages/core-transactions/src/handlers/two/htlc-refund.ts index df961fbab5..1a24dcdc5a 100644 --- a/packages/core-transactions/src/handlers/two/htlc-refund.ts +++ b/packages/core-transactions/src/handlers/two/htlc-refund.ts @@ -29,7 +29,7 @@ export class HtlcRefundTransactionHandler extends TransactionHandler { for (const { senderPublicKey, refundedBalance } of balances) { // sender is from the original lock const refundWallet: Contracts.State.Wallet = this.walletRepository.findByPublicKey(senderPublicKey); - refundWallet.balance = refundWallet.balance.plus(refundedBalance); + refundWallet.increaseBalance(Utils.BigNumber.make(refundedBalance)); } } @@ -118,7 +118,7 @@ export class HtlcRefundTransactionHandler extends TransactionHandler { AppUtils.assert.defined(data.nonce); - sender.nonce = data.nonce; + sender.setNonce(data.nonce); AppUtils.assert.defined(data.asset?.refund?.lockTransactionId); @@ -131,10 +131,10 @@ export class HtlcRefundTransactionHandler extends TransactionHandler { assert(lockWallet && lockWallet.getAttribute("htlc.locks", {})[lockId]); const locks: Interfaces.IHtlcLocks = lockWallet.getAttribute("htlc.locks", {}); - const newBalance: Utils.BigNumber = lockWallet.balance.plus(locks[lockId].amount).minus(data.fee); + const newBalance: Utils.BigNumber = lockWallet.getBalance().plus(locks[lockId].amount).minus(data.fee); assert(!newBalance.isNegative()); - lockWallet.balance = newBalance; + lockWallet.setBalance(newBalance); const lockedBalance: Utils.BigNumber = lockWallet.getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO); const newLockedBalance: Utils.BigNumber = lockedBalance.minus(locks[lockId].amount); @@ -161,7 +161,7 @@ export class HtlcRefundTransactionHandler extends TransactionHandler { this.verifyTransactionNonceRevert(sender, transaction); - sender.nonce = sender.nonce.minus(1); + sender.decreaseNonce(); AppUtils.assert.defined(transaction.data.asset?.refund?.lockTransactionId); @@ -176,7 +176,7 @@ export class HtlcRefundTransactionHandler extends TransactionHandler { lockTransaction.senderPublicKey, ); - lockWallet.balance = lockWallet.balance.minus(lockTransaction.amount).plus(transaction.data.fee); + lockWallet.decreaseBalance(lockTransaction.amount.minus(transaction.data.fee)); const lockedBalance: Utils.BigNumber = lockWallet.getAttribute("htlc.lockedBalance", Utils.BigNumber.ZERO); lockWallet.setAttribute("htlc.lockedBalance", lockedBalance.plus(lockTransaction.amount)); diff --git a/packages/core-transactions/src/handlers/two/multi-payment.ts b/packages/core-transactions/src/handlers/two/multi-payment.ts index 24413e32e6..969b7f11aa 100644 --- a/packages/core-transactions/src/handlers/two/multi-payment.ts +++ b/packages/core-transactions/src/handlers/two/multi-payment.ts @@ -34,8 +34,8 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.senderPublicKey); for (const payment of transaction.asset.payments) { const recipient: Contracts.State.Wallet = this.walletRepository.findByAddress(payment.recipientId); - recipient.balance = recipient.balance.plus(payment.amount); - sender.balance = sender.balance.minus(payment.amount); + recipient.increaseBalance(payment.amount); + sender.decreaseBalance(payment.amount); } } } @@ -53,7 +53,7 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { const payments: Interfaces.IMultiPaymentItem[] = transaction.data.asset.payments; const totalPaymentsAmount = payments.reduce((a, p) => a.plus(p.amount), Utils.BigNumber.ZERO); - if (wallet.balance.minus(totalPaymentsAmount).minus(transaction.data.fee).isNegative()) { + if (wallet.getBalance().minus(totalPaymentsAmount).minus(transaction.data.fee).isNegative()) { throw new InsufficientBalanceError(); } @@ -74,7 +74,7 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); - sender.balance = sender.balance.minus(totalPaymentsAmount); + sender.decreaseBalance(totalPaymentsAmount); } public async revertForSender(transaction: Interfaces.ITransaction): Promise { @@ -91,7 +91,7 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); - sender.balance = sender.balance.plus(totalPaymentsAmount); + sender.increaseBalance(totalPaymentsAmount); } public async applyToRecipient(transaction: Interfaces.ITransaction): Promise { @@ -100,7 +100,7 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { for (const payment of transaction.data.asset.payments) { const recipient: Contracts.State.Wallet = this.walletRepository.findByAddress(payment.recipientId); - recipient.balance = recipient.balance.plus(payment.amount); + recipient.increaseBalance(payment.amount); } } @@ -110,7 +110,7 @@ export class MultiPaymentTransactionHandler extends TransactionHandler { for (const payment of transaction.data.asset.payments) { const recipient: Contracts.State.Wallet = this.walletRepository.findByAddress(payment.recipientId); - recipient.balance = recipient.balance.minus(payment.amount); + recipient.decreaseBalance(payment.amount); } } } diff --git a/packages/core-transactions/src/handlers/two/transfer.ts b/packages/core-transactions/src/handlers/two/transfer.ts index 77a9a14f29..6e5229aa3d 100644 --- a/packages/core-transactions/src/handlers/two/transfer.ts +++ b/packages/core-transactions/src/handlers/two/transfer.ts @@ -1,4 +1,4 @@ -import { Container, Contracts } from "@arkecosystem/core-kernel"; +import { Container, Contracts, Utils } from "@arkecosystem/core-kernel"; import { Transactions } from "@arkecosystem/crypto"; import { One } from "../index"; @@ -13,7 +13,7 @@ export class TransferTransactionHandler extends One.TransferTransactionHandler { const transactions = await this.transactionRepository.findReceivedTransactions(); for (const transaction of transactions) { const wallet: Contracts.State.Wallet = this.walletRepository.findByAddress(transaction.recipientId); - wallet.balance = wallet.balance.plus(transaction.amount); + wallet.increaseBalance(Utils.BigNumber.make(transaction.amount)); } } }