Skip to content

Commit

Permalink
Add moshi adapter for big decimal numbers; Remove factory (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
elgatovital authored Jul 22, 2020
1 parent 69334e5 commit 7901f0b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package pm.gnosis.common.adapters.moshi

import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonQualifier
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import pm.gnosis.crypto.utils.asEthereumAddressChecksumString
import pm.gnosis.model.Solidity
Expand All @@ -11,19 +10,9 @@ import pm.gnosis.utils.asEthereumAddress
import pm.gnosis.utils.hexAsBigInteger
import pm.gnosis.utils.parseToBigInteger
import pm.gnosis.utils.toHexString
import java.math.BigDecimal
import java.math.BigInteger

object MoshiBuilderFactory {
fun makeMoshiBuilder(): Moshi.Builder {
return Moshi.Builder()
.add(WeiAdapter())
.add(HexNumberAdapter())
.add(DecimalNumberAdapter())
.add(DefaultNumberAdapter())
.add(SolidityAddressAdapter())
}
}

class WeiAdapter {
@ToJson
fun toJson(wei: Wei): String =
Expand Down Expand Up @@ -53,6 +42,15 @@ class DecimalNumberAdapter {
fun fromJson(decimalNumber: String): BigInteger = decimalNumber.toBigInteger()
}

class BigDecimalNumberAdapter {
@ToJson
fun toJson(@BigDecimalNumber bigDecimal: BigDecimal): String = bigDecimal.toString()

@FromJson
@BigDecimalNumber
fun fromJson(decimalNumber: String): BigDecimal = decimalNumber.toBigDecimal()
}

class DefaultNumberAdapter {
@ToJson
fun toJson(hexNumber: BigInteger): String = hexNumber.toHexString()
Expand All @@ -76,3 +74,7 @@ annotation class HexNumber
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class DecimalNumber

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class BigDecimalNumber
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import org.junit.Assert.assertEquals
import org.junit.Test
import pm.gnosis.model.Solidity
import pm.gnosis.models.Wei
import java.math.BigDecimal
import java.math.BigInteger

class TypeAdaptersTest {
Expand Down Expand Up @@ -44,6 +45,18 @@ class TypeAdaptersTest {
assertEquals("1000000000000000000", decimalString)
}

@Test
fun testBigDecimalNumberAdapterFromJson() {
val value = BigDecimalNumberAdapter().fromJson("1000000000000000000")
assertEquals(BigDecimal("1000000000000000000"), value)
}

@Test
fun testBigDecimalNumberAdapterToJson() {
val bigDecimalString = BigDecimalNumberAdapter().toJson(BigDecimal("1000000000000000000"))
assertEquals("1000000000000000000", bigDecimalString)
}

@Test
fun testDefaultNumberAdapterFromJsonWithHexNumber() {
val value = DefaultNumberAdapter().fromJson("0xde0b6b3a7640000")
Expand Down

0 comments on commit 7901f0b

Please sign in to comment.