-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #17 from denmusic1992/task/chornyy-add-websocket
chornyy add web socket implementation
- Loading branch information
Showing
17 changed files
with
683 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
web3/src/androidMain/kotlin/dev/icerock/moko/web3/websockets/Logger.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package dev.icerock.moko.web3.websockets | ||
|
||
import android.util.Log | ||
import io.ktor.client.engine.HttpClientEngine | ||
import io.ktor.client.engine.okhttp.OkHttp | ||
import java.util.concurrent.TimeUnit | ||
|
||
actual fun log(message: String) { | ||
Log.d("KCWS", message) | ||
} | ||
|
||
actual fun createHttpClientEngine(): HttpClientEngine { | ||
return OkHttp.create { | ||
config { | ||
retryOnConnectionFailure(true) | ||
pingInterval(30, TimeUnit.SECONDS) | ||
} | ||
} | ||
} |
61 changes: 61 additions & 0 deletions
61
web3/src/androidTest/kotlin/dev/icerock/moko/web3/Web3SocketTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/* | ||
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
@file:Suppress("EXPERIMENTAL_API_USAGE") | ||
|
||
package dev.icerock.moko.web3 | ||
|
||
import dev.icerock.moko.web3.websockets.SubscriptionParam | ||
import dev.icerock.moko.web3.websockets.createHttpClientEngine | ||
import io.ktor.client.* | ||
import io.ktor.client.features.logging.* | ||
import io.ktor.client.features.websocket.* | ||
import kotlinx.coroutines.GlobalScope | ||
import kotlinx.coroutines.delay | ||
import kotlinx.coroutines.flow.* | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.runBlocking | ||
import kotlinx.serialization.json.Json | ||
import kotlin.test.BeforeTest | ||
import kotlin.test.Test | ||
|
||
class Web3SocketTest { | ||
|
||
private lateinit var web3Socket: Web3Socket | ||
|
||
@BeforeTest | ||
fun `create socket`() { | ||
val httpClient = HttpClient(createHttpClientEngine()) { | ||
install(WebSockets) { | ||
pingInterval = 30 | ||
} | ||
} | ||
|
||
web3Socket = Web3Socket( | ||
httpClient = httpClient, | ||
webSocketUrl = "wss://rinkeby.infura.io/ws/v3/59d7fae3226b40e09d84d713e588305b", | ||
coroutineScope = GlobalScope | ||
) | ||
} | ||
|
||
@Test | ||
fun `test web socket flow`() { | ||
runBlocking { | ||
web3Socket.subscribeWebSocketWithFilter(SubscriptionParam.Logs) | ||
.onEach(::println) | ||
.take(2) | ||
.launchIn(scope = this) | ||
|
||
web3Socket.subscribeWebSocketWithFilter(SubscriptionParam.Logs) | ||
.onEach(::println) | ||
.take(2) | ||
.launchIn(scope = this) | ||
|
||
web3Socket.subscribeWebSocketWithFilter(SubscriptionParam.Logs) | ||
.onEach(::println) | ||
.take(2) | ||
.launchIn(scope = this) | ||
} | ||
} | ||
} |
21 changes: 21 additions & 0 deletions
21
web3/src/commonMain/kotlin/dev.icerock.moko.web3/LogsWeb3SocketEvent.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
/* | ||
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package dev.icerock.moko.web3 | ||
|
||
import kotlinx.serialization.Serializable | ||
|
||
|
||
@Serializable | ||
data class LogsWeb3SocketEvent( | ||
val removed: Boolean, | ||
val logIndex: String, | ||
val transactionIndex: String, | ||
val transactionHash: String, | ||
val blockHash: String, | ||
val blockNumber: String, | ||
val address: String, | ||
val data: String, | ||
val topics: List<String> | ||
) |
26 changes: 26 additions & 0 deletions
26
web3/src/commonMain/kotlin/dev.icerock.moko.web3/NewHeadsWeb3SocketEvent.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
/* | ||
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package dev.icerock.moko.web3 | ||
|
||
import kotlinx.serialization.Serializable | ||
|
||
@Serializable | ||
data class NewHeadsWeb3SocketEvent( | ||
val difficulty: String, | ||
val extraData: String, | ||
val gasLimit: String, | ||
val gasUsed: String, | ||
val logsBloom: String, | ||
val miner: String, | ||
val nonce: String, | ||
val number: String, | ||
val parentHash: String, | ||
val receiptsRoot: String, | ||
val sha3Uncles: String, | ||
val stateRoot: String, | ||
val timestamp: String, | ||
val transactionsRoot: String, | ||
val hash: String | ||
) |
22 changes: 22 additions & 0 deletions
22
web3/src/commonMain/kotlin/dev.icerock.moko.web3/SyncingWeb3SocketEvent.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* | ||
* Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package dev.icerock.moko.web3 | ||
|
||
import kotlinx.serialization.Serializable | ||
|
||
@Serializable | ||
data class SyncingWeb3SocketEvent( | ||
val syncing: Boolean, | ||
val status: Status | ||
) { | ||
@Serializable | ||
data class Status( | ||
val startingBlock: Int, | ||
val currentBlock: Int, | ||
val highestBlock: Int, | ||
val pulledStates: Int, | ||
val knownStates: Int | ||
) | ||
} |
146 changes: 146 additions & 0 deletions
146
web3/src/commonMain/kotlin/dev.icerock.moko.web3/Web3Socket.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
/* | ||
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package dev.icerock.moko.web3 | ||
|
||
import dev.icerock.moko.web3.entity.InfuraRequest | ||
import dev.icerock.moko.web3.entity.Web3SocketResponse | ||
import dev.icerock.moko.web3.websockets.SubscriptionParam | ||
import io.ktor.client.* | ||
import io.ktor.client.features.websocket.* | ||
import io.ktor.http.cio.websocket.* | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.channels.Channel | ||
import kotlinx.coroutines.flow.* | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
import kotlinx.serialization.json.Json | ||
import kotlinx.serialization.json.JsonElement | ||
import kotlinx.serialization.json.decodeFromJsonElement | ||
import kotlinx.serialization.json.encodeToJsonElement | ||
|
||
/** | ||
* Class to work with webSocket connection in Etherium network | ||
* @param httpClient client to work with WebSocket | ||
*/ | ||
class Web3Socket( | ||
private val httpClient: HttpClient, | ||
private val webSocketUrl: String, | ||
private val coroutineScope: CoroutineScope | ||
) { | ||
val json = Json { | ||
isLenient = true | ||
ignoreUnknownKeys = true | ||
} | ||
/** | ||
* channel to receive data from webSocket | ||
*/ | ||
private val responsesFlowSource: MutableSharedFlow<Web3SocketResponse<JsonElement>> = | ||
MutableSharedFlow() | ||
|
||
val responsesFlow: SharedFlow<Web3SocketResponse<JsonElement>> = responsesFlowSource.asSharedFlow() | ||
|
||
/** | ||
* incremental field to filter different incoming messages from websocket | ||
*/ | ||
private var queueID: Int = 0 | ||
|
||
/** | ||
* subscription filter's flow, here we emit new | ||
*/ | ||
private val requestsChannel: Channel<InfuraRequest<JsonElement>> = Channel(capacity = 1) | ||
|
||
init { | ||
// launch websocket connection to work with in over web3Socket lifecycle | ||
coroutineScope.launch { | ||
httpClient.webSocket(webSocketUrl) { | ||
requestsChannel | ||
.consumeAsFlow() | ||
.map { request -> | ||
json.encodeToString( | ||
serializer = InfuraRequest.serializer(JsonElement.serializer()), | ||
value = request | ||
) | ||
} | ||
.map(Frame::Text) | ||
.onEach(outgoing::send) | ||
.launchIn(scope = this) | ||
|
||
incoming | ||
.consumeAsFlow() | ||
.mapNotNull { frame -> | ||
val textFrame = frame as? Frame.Text | ||
return@mapNotNull textFrame?.readText() | ||
} | ||
.map { text -> | ||
json.decodeFromString( | ||
deserializer = Web3SocketResponse.serializer(JsonElement.serializer()), | ||
string = text | ||
) | ||
} | ||
.collect { | ||
responsesFlowSource.emit(it) | ||
} | ||
} | ||
} | ||
} | ||
|
||
suspend inline fun <reified T> sendRpcRequest(request: InfuraRequest<JsonElement>): T? { | ||
val response = sendRpcRequestRaw(request) ?: return null | ||
return json.decodeFromJsonElement(response) | ||
} | ||
suspend fun sendRpcRequestRaw(request: InfuraRequest<JsonElement>): JsonElement? { | ||
val id = request.id | ||
|
||
coroutineScope.launch { | ||
requestsChannel.send(request) | ||
} | ||
|
||
return responsesFlowSource.first { it.id == id }.result | ||
} | ||
|
||
|
||
private val queueMutex = Mutex() | ||
|
||
/** | ||
* Subscription function for current filter | ||
*/ | ||
@OptIn(ExperimentalStdlibApi::class) | ||
fun <T> subscribeWebSocketWithFilter(param: SubscriptionParam<T>): Flow<T> { | ||
var subscriptionID: String? = null | ||
return flow { | ||
val id = queueMutex.withLock { queueID++ } | ||
val request = InfuraRequest( | ||
id = id, | ||
method = "eth_subscribe", | ||
params = buildList { | ||
add(json.encodeToJsonElement(param.name)) | ||
if(param.params != null) | ||
add(json.encodeToJsonElement(param.params)) | ||
} | ||
) | ||
subscriptionID = sendRpcRequest(request) ?: return@flow | ||
|
||
val responses = responsesFlowSource | ||
.filter { | ||
it.params?.subscription == subscriptionID | ||
}.mapNotNull { | ||
json.decodeFromJsonElement ( | ||
param.serializer, | ||
element = it.params?.result ?: return@mapNotNull null | ||
) | ||
} | ||
|
||
emitAll(responses) | ||
}.onCompletion { | ||
val subId = subscriptionID ?: return@onCompletion | ||
val request = InfuraRequest( | ||
method = "eth_unsubscribe", | ||
params = listOf(json.encodeToJsonElement(subId)) | ||
) | ||
sendRpcRequestRaw(request) | ||
} | ||
} | ||
} |
Oops, something went wrong.