neow3j / neow3j-examples-java

neow3j: Java Examples
Apache License 2.0
11 stars 8 forks source link

getBalance can return null #20

Closed qvanphong closed 2 years ago

qvanphong commented 2 years ago

In FungibleToken example: https://github.com/neow3j/neow3j-examples-java/blob/master/src/main/java/io/neow3j/examples/contractdevelopment/contracts/FungibleToken.java

there is a getBalance method that return a current balance of address passed in. But in most cases, their balance does not exist yet and cause that the assetMap.getInteger will return null. Which gonna lead to "Specified cast is not valid" when invoking transfer.

I would recommend change getBalance to:

    private static int getBalance(Hash160 account) {
        Integer balance = Storage.getInteger(sc, account.toByteArray());
        return balance != null ? balance : 0;
    }
gsmachado commented 2 years ago

Hello @qvanphong Maybe, could the getBalance you proposed return Boolean? DId you test it?

qvanphong commented 2 years ago

Hello @qvanphong Maybe, could the getBalance you proposed return Boolean? DId you test it?

getBalance that I proposed will always return int, if the data does not exist in DB yet, it will return 0.

since getBalance from example will return null if data doesn't exist, I have written a simple test to check if Storage.getInteger really returns null in that case, and yes, it will.

csmuller commented 2 years ago

Thanks @qvanphong for pointing this out. It is definitely better to check for null in the getBalance method before returning. I will adapt the example. In the future we will provide a getInteger method that already does that internally (changes in PR https://github.com/neow3j/neow3j/pull/702).