From 3c034d09d5f90f3849e740c7ab516a2e23f8768e Mon Sep 17 00:00:00 2001 From: BenRey Date: Mon, 18 Mar 2024 16:33:21 +0100 Subject: [PATCH] Fix test throw error if from balance is 0 --- assembly/__tests__/env-coins.spec.ts | 12 ------------ vm-mock/vm.js | 15 +++++++++------ 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/assembly/__tests__/env-coins.spec.ts b/assembly/__tests__/env-coins.spec.ts index cea85da0..0deccf21 100644 --- a/assembly/__tests__/env-coins.spec.ts +++ b/assembly/__tests__/env-coins.spec.ts @@ -60,18 +60,6 @@ describe('Testing env coins related functions', () => { expect(env.balanceOf(testAddress2.toString())).toBe(amount); }); - it('transferCoins to mock address created with addAddressToLedger', () => { - addAddressToLedger(testAddress3.toString()); - const amount: u64 = 100; - const receiverCurrentBalance = env.balanceOf(testAddress3.toString()); - // given - expect(receiverCurrentBalance).toBe(0); - // when - env.transferCoins(testAddress3.toString(), amount); - // then - expect(env.balanceOf(testAddress3.toString())).toBe(amount); - }); - it('get the balance of an address', () => { const amount: u64 = 100; // given diff --git a/vm-mock/vm.js b/vm-mock/vm.js index 94e06a3f..94f875bb 100644 --- a/vm-mock/vm.js +++ b/vm-mock/vm.js @@ -699,20 +699,23 @@ export default function createMockedABI( if (!ledger.has(fromAddress)) { ERROR(`Sending address ${fromAddress} does not exist in ledger.`); } - const senderBalance = ledger.get(fromAddress).balance; + // We should not have this case, but someone could add a ledger.set without a balance + // Typescript could be used to avoid this kind of error + if (ledger.get(fromAddress).balance === undefined) { + ERROR('not enough balance to transfer ' + amount + ' coins.'); + } + + const senderBalance = ledger.get(fromAddress).balance; if (senderBalance < BigInt(amount)) { ERROR('not enough balance to transfer ' + amount + ' coins.'); } - // We should not have this case, but someone could add a ledger.set without a balance - // Typescript could be used to avoid this kind of error if (ledger.get(toAddress).balance === undefined) { ledger.get(toAddress).balance = BigInt(0); } - if (ledger.get(fromAddress).balance === undefined) { - ledger.get(fromAddress).balance = BigInt(0); - } + + ledger.get(fromAddress).balance = BigInt(0); ledger.get(toAddress).balance += BigInt(amount); ledger.get(fromAddress).balance -= BigInt(amount);