# Android SDK

## Prerequisites

* API 16: Android 4.1 (Jelly Bean) or higer
* Java 8 or higher
* Android Studio 3.0.0 or higher
* Android Permission: Internet Permission

## Environment Setup

Klip JavaScript SDK doesn't require a separate registration process and works in any environments where HTTP communication is possible. But since user's consent is received using the mobile app Klip, you need to have Klip installed to make the requests.

You can find a guide for executing Klip Android SDK Sample App in `README.md`.

### 1. Download Klip SDK

Download Klip Android SDK in [Download](https://global.docs.klipwallet.com/a2a-sdk/a2a-sdk-download).

### 2. Add Klip SDK Library

#### Option 1. Build Klip SDK and add to your project

1. Run **Terminal** at the location of downloaded Klip SDK project
2. Run the command `./gradlew :sdk:build` and build Klip SDK project (When building is complete, an AAR file is created at /sdk/build/outputs/aar/)
3. Create a **libs** directory in the project
4. Copy the built AAR file to the project's **libs** directory
5. Add directory reference and dependency to the project's `build.gradle`

```
repositories {
  flatDir {
    dirs 'libs'
  }
}
dependencies {
  // Klip SDK  
  implementation 'com.klipwallet.app2app:klip-a2a-sdk-global-android_release_v1.0.0:1.0.0@aar'
}
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).<br>

#### Option 2. Import Klip SDK source code and add to your project

1. Run the project in **Android Studio**
2. **Android Studio > File > New > Import Module**
3. Select the **sdk** directory in the Klip SDK project downloaded in the **Source Directory**, and click **Next**
4. Copy `gradle.properties` in the Klip SDK project to your project
5. Add the dependency setting in `build.gradle` of your project

```
dependencies {
  // Klip SDK  
  implementation project(path: ':sdk')
}
```

Once the Klip SDK source is copied to your project, you can modify the library code yourself. This may not be a suitable option if you want to maintain single version library code. In this case, add the compiled AAR file as directed in **Option 1**.

### 3. Add Permission

In order to enable HTTP communication on Klip SDK, add `android.permission.INTERNET` in the `AndroidManifest.xml` file as shown below:

```xml
<manifest ...>
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

## API

### Overview

App2App API requests are made in the order: `prepare`, `request`, and `getResult`.

* `prepare` is the step in which requests (from of a total of five) are defined
* `request` is the step in which the function is called and the signing takes place on Klip
* `getResult` is the step in which the result is returned from the function call

In addition, `getCardList` is a function provided for the convenience of BApp developers that returns a list of NFTs of a Klip user.\
If you need help with this document or Klip in general, please visit our [Developer Forum](https://klipforum.zendesk.com).<br>

### KlipGlobal.getInstance

Creates an instance to use Klip SDK.

**Parameters**

| Name    | Type      | Description         |
| ------- | --------- | ------------------- |
| context | `Context` | Application context |

**Return Value**

| Type   | Description   |
| ------ | ------------- |
| `Klip` | Klip instance |

**Example**

```java
public class SampleActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Klip klip = KlipGlobal.getInstance(this);
  }
}
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

### Klip.prepare

Prepares to process an App2App API request and issues a request key.

**Request Objects**

* Connecting Klip(=authentication) `AuthRequest`
* Sending KLAY `KlayTxRequest`
* Sending Token `TokenTxRequest`
* Sending Card `CardTxRequest`
* Executing Contract `ContractTxRequest`

**Parameters**

| Name     | Type                           | Description                                                                                                                               |
| -------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| request  | `KlipRequest`                  | Requested information depending on request type                                                                                           |
| bappInfo | `BAppInfo`                     | Information of the requested BApp                                                                                                         |
| callback | `KlipCallback<KlipTxResponse>` | The callback function to obtain the response. If it's successful, it returns `KlipTxResponse`, and if not it returns `KlipErrorResponse`. |

**Throws**

| Type                   | Description                                                |
| ---------------------- | ---------------------------------------------------------- |
| `KlipRequestException` | Request exception (e.g. a required parameter was ommitted) |

Requesting consent to Klip users will return the data entered in `request` and `bappInfo`. The request key returned in the response serves as a key when requesting transactions to users, and is used with **KlipSDK.shared.getResult** and **KlipSDK.shared.request**.

**Example 1. Obtaining User Information**

```java
// Obtaining user information
AuthRequest req = new AuthRequest();

// BApp information
BAppInfo bappInfo = new BAppInfo("BApp Name");

// Response result Callback
KlipCallback callback = new KlipCallback<KlipTxResponse>() {
  @Override public void onSuccess(final KlipTxResponse res) {}
  @Override public void onFail(final KlipErrorResponse res) {}
}

klip.prepare(req, bappInfo, callback);
```

**Example 2. Sending KLAY**

```java
// Transaction request for sending KLAY
KlayTxRequest req = new KlayTxRequest.Builder()
  .to("0x..receiver address..")
  .amount("10")
  .build();
  
klip.prepare(req, bappInfo, callback); // bappInfo, callback (example 1 참고)
```

**Example 3. Sending Tokens**

```java
// Transaction request for sending tokens
TokenTxRequest req = new TokenTxRequest.Builder()
  .contract("0x..token contract address..")
  .to("0x..receiver address..")
  .amount("10")
  .build();
  
klip.prepare(req, bappInfo, callback); // bappInfo, callback (example 1 참고)
```

**Example 4. Sending Card**

```java
// Transaction request for sending Card
CardTxRequest req = new CardTxRequest.Builder()
  .contract("0x..card contract address..")
  .to("0x..receiver address..")
  .cardId("9")
  .build();
  
klip.prepare(req, bappInfo, callback); // bappInfo, callback (example 1 참고)
```

**Example 5. Executing Contract**

```java
// Transaction request for executing contract
ContractTxRequest req = new ContractTxRequest.Builder()
  .to("0x..contract address..")
  .value("10")
  .abi("{..contract abi..}")
  .params(new ArrayList<Object>(){
    // contract parameters
  })
  .build();
  
klip.prepare(req, bappInfo, callback); // bappInfo, callback (refer to example 1)
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

### Klip.request

Requests authentification or signature using deep link. If the device doesn't have Klip installed, it redirects automatically to the download page on Google Play. To implement the request step using QR code, please refer to [QR Code Tutorial](https://global.docs.klipwallet.com/rest-api/rest-api-a2a#request-qr-code).

**Parameters**

| Name       | Type   | Description                                |
| ---------- | ------ | ------------------------------------------ |
| requestKey | String | Request number (Obtained from Klip Server) |

**Throws**

| Type                   | Description                                                |
| ---------------------- | ---------------------------------------------------------- |
| `KlipRequestException` | Request exception (e.g. a required parameter was ommitted) |

**Example**

```java
klip.request(requestKey);
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

### Klip.getResult

Returns the result of an App2App API request.

**Parameters**

| Name       | Type                           | Description                                                                                                                               |
| ---------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| requestKey | String                         | Request number (Obtained from Klip Server)                                                                                                |
| callback   | `KlipCallback<KlipTxResponse>` | The callback function to obtain the response. If it's successful, it returns `KlipTxResponse`, and if not it returns `KlipErrorResponse`. |

**Throws**

| Type                   | Description                                                |
| ---------------------- | ---------------------------------------------------------- |
| `KlipRequestException` | Request exception (e.g. a required parameter was ommitted) |

**Example**

```java
KlipCallback callback = new KlipCallback<KlipTxResponse>() {
  @Override public void onSuccess(final KlipTxResponse res) {}
  @Override public void onFail(final KlipErrorResponse res) {}
}

Klip klip = KlipGlobal.getInstance();
klip.getResult(requestKey, callback)
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

### Klip.getCardList

Returns a list of certain Cards of a user.

**Parameters**

| Name        | Type                             | Description                                                                                                                               |
| ----------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| cardAddress | String                           | Address of the Card to retrieve                                                                                                           |
| userAddress | String                           | Address of the user to retrieve                                                                                                           |
| cursor      | String                           | (optional) The pointer after which the next request will retrieve the next 100 items if the number of Cards exceeds 100.                  |
| callback    | `KlipCallback<CardListResponse>` | The callback function to return the response. If it'successful, it returns `CardListResponse`, and if not it returns `KlipErrorResponse`. |

**Throws**

| Type                   | Description                                                    |
| ---------------------- | -------------------------------------------------------------- |
| `KlipRequestException` | Request exception (e.g. when a required parameter is ommitted) |

**Example**

```java
KlipCallback callback = new KlipCallback<KlipCardListResponse>() {
  @Override public void onSuccess(final KlipCardListResponse res) {}
  @Override public void onFail(final KlipErrorResponse res) {}
}

Klip klip = KlipGlobal.getInstance();
klip.getCardList("0x..card address..",
  "0x..user address..",
  null,
  callback);
```

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).

## Error Code

You can see the error code via `getErrorCode()` in `KlipErrorResponse`, which is the fail response of `KlipCallback`.

| Http Status | Error Code | Description                                                                   |
| ----------- | ---------- | ----------------------------------------------------------------------------- |
| -           | -          | Same as [Klip REST API Error Code](https://global.docs.klipwallet.com/basics) |
| 500         | 10         | Error in Klip SDK (e.g. HTTP c connection failure)                            |
| 500         | 21         | Error in Klip SDK (Klip REST API unsupported error code)                      |
| 500         | 22         | Error in Klip SDK (Klip protocol error)                                       |

\
If you need help with this document or Klip in general, please visit our \[Developer Forum]\(<https://klipforum.zendesk.com>).
