Skip to content

Commit

Permalink
Merge pull request #9 from uport-project/support/get-network-by-name
Browse files Browse the repository at this point in the history
Fetch network using name
  • Loading branch information
Ugo Amanoh authored Dec 17, 2019
2 parents d5175bc + 36c4831 commit 797bcd5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
19 changes: 14 additions & 5 deletions core/src/main/java/me/uport/sdk/core/Networks.kt
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,22 @@ object Networks {
}

/**
* Gets an [EthNetwork] based on a [networkId]
* Gets an [EthNetwork] based on a [networkId] or [name]
*/
fun get(networkId: String): EthNetwork {
val cleanNetId = cleanId(networkId)
fun get(nameOrId: String): EthNetwork {
val cleanNetId = cleanId(nameOrId)
return NETWORK_CONFIG[cleanNetId]
?: NETWORK_CONFIG[networkId]
?: throw IllegalStateException("network [$networkId] not configured")
?: NETWORK_CONFIG[nameOrId]
?: getNetworkByName(nameOrId)
?: throw IllegalStateException("network [$nameOrId] not configured")
}

/**
* Searches for an [EthNetwork] based on a [name]
*/
private fun getNetworkByName(name: String): EthNetwork? {
val queryName = name.toLowerCase()
return NETWORK_CONFIG.values.find { it.name.toLowerCase() == queryName }
}

private fun cleanId(id: String) = id.clean0xPrefix().trimStart('0').prepend0xPrefix()
Expand Down
26 changes: 26 additions & 0 deletions core/src/test/java/me/uport/sdk/core/NetworksTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,32 @@ class NetworksTest {
.isEqualTo(Networks.mainnet.ethrDidRegistry)
}

@Test
fun `can find a registered network using the name`() {

assertThat(Networks.get("mainnet")).isEqualTo(Networks.mainnet)

assertThat(Networks.get("rinkeby")).isEqualTo(Networks.rinkeby)

assertThat(Networks.get("kovan")).isEqualTo(Networks.kovan)

assertThat(Networks.get("ropsten")).isEqualTo(Networks.ropsten)
}

@Test
fun `can find a registered network using the different case name`() {
assertThat(Networks.get("MainNet")).isEqualTo(Networks.mainnet)
}

@Test
fun `throws error if the network name does not match`() {
assertThat {
Networks.get("manet")
}.thrownError {
isInstanceOf(IllegalStateException::class)
}
}

@Test
fun `getting an unknown network throws`() {
assertThat {
Expand Down

0 comments on commit 797bcd5

Please sign in to comment.