Skip to content

Commit

Permalink
Merge pull request #1867 from polywrap/kris/kotlin-template
Browse files Browse the repository at this point in the history
Android (Kotlin) app template
  • Loading branch information
dOrgJelli authored Sep 1, 2023
2 parents 7e311f8 + f34219f commit 60ce291
Show file tree
Hide file tree
Showing 45 changed files with 1,103 additions and 2 deletions.
7 changes: 7 additions & 0 deletions .github/workflows/ci-javascript.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ jobs:
with:
go-version: '^1.13.1'

- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: 'corretto'
java-version: '17'
cache: 'gradle'

- name: Install cue lang
run: go install cuelang.org/go/cmd/cue@latest

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/__tests__/e2e/p1/create.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Commands:
wasm [options] <language> <name> Create a Polywrap wasm wrapper. langs:
assemblyscript, rust, golang, interface
app [options] <language> <name> Create a Polywrap application. langs:
typescript, python, rust
typescript, python, rust, android
plugin [options] <language> <name> Create a Polywrap plugin. langs:
typescript, rust, python
template [options] <url> <name> Download template from a URL. formats:
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const urlStr = intlMsg.commands_create_options_t_url();

export const supportedLangs = {
wasm: ["assemblyscript", "rust", "golang", "interface"] as const,
app: ["typescript", "python", "rust"] as const,
app: ["typescript", "python", "rust", "android"] as const,
plugin: ["typescript", "rust", "python"] as const,
};

Expand Down
15 changes: 15 additions & 0 deletions packages/templates/app/android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
1 change: 1 addition & 0 deletions packages/templates/app/android/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
109 changes: 109 additions & 0 deletions packages/templates/app/android/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.serialization")
id("com.github.node-gradle.node")
}

android {
namespace = "io.template.polywrap"
compileSdk = 33

defaultConfig {
applicationId = "io.template.polywrap"
minSdk = 24
targetSdk = 33
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.4.8"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}

dependencies {
// polywrap client
implementation("io.polywrap:polywrap-client:0.10.4")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1")
// polywrap logger plugin
implementation("io.polywrap.plugins:logger:0.10.4")
implementation("com.github.tony19:logback-android:3.0.0")

// ui
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1")

// defaults
implementation("androidx.core:core-ktx:1.10.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")
implementation("androidx.activity:activity-compose:1.7.2")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}

// set up NodeJS to run the Polywrap CLI
// NodeJS installation will be stored in gradle cache
node {
val nullString: String? = null
distBaseUrl.set(nullString)
// Whether to download and install a specific Node.js version or not
// If false, it will use the globally installed Node.js
// If true, it will download node using above parameters
// Note that npm is bundled with Node.js
download.set(true)
}

// run polwyrap codegen
tasks.register<com.github.gradle.node.npm.task.NpxTask>("codegen") {
group = "polywrap"
dependsOn(tasks.npmInstall)
command.set("polywrap")
args.set(listOf("codegen",
"-m", "$rootDir/polywrap.yaml",
"-g", "$projectDir/src/main/java/wrap"
))
}

// set polywrap codegen to run before each build
tasks.withType<KotlinCompile> { dependsOn("codegen") }
21 changes: 21 additions & 0 deletions packages/templates/app/android/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.template.polywrap

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("io.template.polywrap", appContext.packageName)
}
}
28 changes: 28 additions & 0 deletions packages/templates/app/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Template"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Template">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
18 changes: 18 additions & 0 deletions packages/templates/app/android/app/src/main/assets/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<configuration
xmlns="https://tony19.github.io/logback-android/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://tony19.github.io/logback-android/xml https://cdn.jsdelivr.net/gh/tony19/logback-android/logback.xsd"
>
<appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender">
<tagEncoder>
<pattern>%logger{12}</pattern>
</tagEncoder>
<encoder>
<pattern>[%-20thread] %msg</pattern>
</encoder>
</appender>

<root level="DEBUG">
<appender-ref ref="logcat" />
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package io.template.polywrap

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import io.template.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxHeight().padding(16.dp)
) {
Surface(
modifier = Modifier.fillMaxWidth().height(60.dp),
color = MaterialTheme.colorScheme.background
) {
PolywrapDemo()
}
}
}
}
}
}

@Composable
fun PolywrapDemo(demoViewModel: PolywrapDemoViewModel = viewModel()) {
Button(onClick = { demoViewModel.polywrapDemo() }) {
Text(text = "Click here and check the logs!")
}
}

@Preview(showBackground = true)
@Composable
fun PolywrapDemoPreview() {
MyApplicationTheme {
PolywrapDemo()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package io.template.polywrap

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import io.polywrap.client.PolywrapClient
import io.polywrap.configBuilder.polywrapClient
import io.polywrap.plugins.logger.loggerPlugin
import kotlinx.coroutines.launch
import wrap.Ethereum
import wrap.EthereumArgsEncodeParams
import wrap.Logging
import wrap.LoggingArgsLog
import wrap.LoggingLogLevel

class PolywrapDemoViewModel: ViewModel() {

// we can create a custom client
val loggerInterfaceUri = "wrapscan.io/polywrap/logger@1.0"
private val client = polywrapClient {
addDefaults()
setPackage("plugin/logger" to loggerPlugin(null))
addInterfaceImplementation(loggerInterfaceUri, "plugin/logger")
setRedirect(loggerInterfaceUri to "plugin/logger")
}

// and use the custom client to create an SDK class instance
private val logger = Logging(client)
// the client can be shared across SDK instances
private val ethereum = Ethereum(client)

// Because their lifetimes are tied to the client, SDK instances work well as extension properties
val PolywrapClient.eth
get() = ethereum

// or we can create an SDK class instance with a new client using default configuration
private val defaultEth = Ethereum()

fun polywrapDemo() = viewModelScope.launch {
Log.i("polywrapDemo","Invoking: Logging.info(...)")

logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "Hello there")).getOrThrow()
logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "Hello again")).getOrThrow()
logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "One last time...")).getOrThrow()

Log.i("polywrapDemo","Invoking: Ethereum.encodeParams(...)")

val encodeArgs = EthereumArgsEncodeParams(
types = listOf("address", "uint256"),
values = listOf("0xB1B7586656116D546033e3bAFF69BFcD6592225E", "500")
)
val result = client.eth.encodeParams(encodeArgs)

if (result.isSuccess) {
println("Ethereum.encodeParams:\n${result.getOrThrow()}")
} else {
println("Error - Ethereum.encodeParams:\n${result.exceptionOrNull()}")
}
}

override fun onCleared() {
super.onCleared()
// remember to close clients to prevent memory leaks when you're done using them
client.close()
defaultEth.client.close()
}
}


Loading

0 comments on commit 60ce291

Please sign in to comment.