Skip to content

OpenST/ost-wallet-sdk-ui-ios

Repository files navigation

OST Wallet SDK iOS

warning: this is alpha stage code and NOT ready for production use

Introduction

Wallet SDK is a mobile application development SDK that enables developers to integrate the functionality of a non-custodial crypto-wallet into consumer applications. The SDK:

  • Safely generates and stores keys on the user's mobile device
  • Signs Ethereum transactions and data as defined by contracts using EIP-1077
  • Enables users to recover access to their Brand Tokens in case the user loses their authorized device

Support

  • iOS version : 9.0 and above (recommended version 10.3 )
  • Swift version: 4.2

Dependencies

We use open-source code from the projects listed below. The Setup section below provides instructions on adding the packages to your code.

Setup

github "ostdotcom/ost-wallet-sdk-ios" == 2.2.3
  • Run carthage update --platform iOS
  • A Cartfile.resolved file and a Carthage directory will appear in the same directory where your .xcodeproj or .xcworkspace is
  • Open application target, under General tab, drag the built OstWalletSdk.framework binary from Carthage/Build/iOS into Linked Frameworks and Libraries section.
  • On the application targets’ Build Phases settings tab, click the + icon and choose New Run Script Phase. Add the following command
/usr/local/bin/carthage copy-frameworks
  • Click the + under Input Files and add an entry for each framework:
$(SRCROOT)/Carthage/Build/iOS/Alamofire.framework
$(SRCROOT)/Carthage/Build/iOS/BigInt.framework
$(SRCROOT)/Carthage/Build/iOS/CryptoEthereumSwift.framework
$(SRCROOT)/Carthage/Build/iOS/CryptoSwift.framework
$(SRCROOT)/Carthage/Build/iOS/EthereumKit.framework
$(SRCROOT)/Carthage/Build/iOS/FMDB.framework
$(SRCROOT)/Carthage/Build/iOS/SipHash.framework
$(SRCROOT)/Carthage/Build/iOS/TrustKit.framework
$(SRCROOT)/Carthage/Build/iOS/OstWalletSdk.framework
  • Create OstWalletSdk.plist file. Following is the default configurations.
<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
 <dict>
 <key>BlockGenerationTime</key>
 <integer>3</integer>
 <key>PricePointCurrencySymbol</key>
 <string>USD</string>
 <key>RequestTimeoutDuration</key>
 <integer>30</integer>
 <key>PinMaxRetryCount</key>
 <integer>3</integer>
 <key>SessionBufferTime</key>
 <integer>3600</integer>
 <key>UseSeedPassword</key>
 <false/>
 </dict>
 </plist>
  • BlockGenerationTime: The time in seconds it takes to mine a block on auxiliary chain.
  • PricePointCurrencySymbol: It is the symbol of quote currency used in price conversion.
  • RequestTimeoutDuration: Request timeout in seconds for https calls made by ostWalletSdk.
  • PinMaxRetryCount: Maximum retry count to get the wallet Pin from user.
  • SessionBufferTime: Buffer expiration time for session keys in seconds.
  • UseSeedPassword: Uses mnemonics and password to generate seed.

These configurations are MANDATORY for successful operation. Failing to set them will significantly impact usage.

Enable FaceID Authentication

To authenticate user using FaceID on devices that support it, please add NSFaceIDUsageDescription to your application's Info.plist.

OST Wallet SDK APIs

To use Ost wallet sdk use import OstWalletSdk

Initialize the SDK

The SDK can be initialized by calling the initialize() API which initializes all the required instances and runs migrations of local databases.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    do {
        try OstWalletSdk.initialize(apiEndPoint: <OST_PLATFORM_API_ENDPOINT>)
     } catch let ostError {

     }
     return true
}

Set up the device

The setupDevice API should be called after user login or signup is successful.

Once the user is logged in, then setupDevice should be called every time the app launches, this ensures that the current device is registered before communicating with OST Platform server.

Parameters
 userId: OST Platform user id provided by application server
 tokenId: Token id provided by application server
 delegate: Callback implementation object for application communication

OstWalletSdk.setupDevice(
    userId: String,
    tokenId: String,
    delegate: OstWorkflowDelegate
    )

Activate the user

User activation refers to the deployment of smart-contracts that form the user's Brand Token wallet. An activated user can engage with a Brand Token economy.

Parameters
 userId: OST Platform user id provided by application server
 pin: User Pin
 passphrasePrefix: Passphrase prefix provided by application server
 spendingLimit: Spending limit in a transaction in atto BT
 expireAfterInSec: Session key validat duration
 delegate: Callback implementation object for application communication

OstWalletSdk.activateUser(
    userId: String,
    userPin: String,
    passphrasePrefix: String,
    spendingLimit: String,
    expireAfterInSec: TimeInterval,
    delegate: OstWorkflowDelegate
    )

Authorize session

A session is a period of time during which a sessionKey is authorized to sign transactions under a pre-set limit on behalf of the user.

The device manager, which controls the tokens, authorizes sessions.

Parameters
 userId: OST Platform user id provided by application server
 spendingLimit: Spending limit in a transaction in atto BT
 expireAfterInSec: Session key validat duration
 delegate: Callback implementation object for application communication

OstWalletSdk.addSession(
    userId: String,
    spendingLimit: String,
    expireAfterInSec: TimeInterval,
    delegate: OstWorkflowDelegate
    )

Execute a transaction

A transaction where Brand Tokens are transferred from a user to another actor within the Brand Token economy are signed using sessionKey if there is an active session. In the absence of an active session, a new session is authorized.

Parameters
 userId: OST Platform user id provided by application server
 tokenHolderAddresses: Token holder addresses of amount receiver
 amounts: Amounts corresponding to tokenHolderAddresses in wei to be transfered
 transactionType: OstExecuteTransactionType value
 meta: meta data of transaction to be associated
Example:-

                           {"name": "transaction name",
                           "type": "user-to-user",
                           "details": "like"}

 options: Map containing options of transactions
Example:-

                           {"currency_code": "USD",
                           "wait_for_finalization": true}

 delegate: Callback implementation object for application communication

OstWalletSdk.executeTransaction(
        userId: String,
        tokenHolderAddresses: [String],
        amounts: [String],
        transactionType: OstExecuteTransactionType,
        meta: [String: String],
        options: [String: Any],
        delegate: OstWorkflowDelegate)

Get Mnemonic Phrase

The mnemonic phrase represents a human-readable way to authorize a new device. This phrase is 12 words long.

Parameters
 userId: OST Platform user id provided by application server
 delegate: Callback implementation object for application communication

OstWalletSdk.getDeviceMnemonics(
    userId: String,
    delegate: OstWorkflowDelegate
    )

Add a device using mnemonics

A user that has stored their mnemonic phrase can enter it into an appropriate user interface on a new mobile device and authorize that device to be able to control their Brand Tokens.

Parameters
 userId: OST Platform user id provided by application server
 mnemonics: Array of mnemonics
 delegate: Callback implementation object for application communication

OstWalletSdk.authorizeCurrentDeviceWithMnemonics(
    userId: String,
    mnemonics: [String],
    delegate: OstWorkflowDelegate
)

Generate a QR Code

A developer can use this method to generate a QR code that displays the information pertinent to the mobile device it is generated on. Scanning this QR code with an authorized mobile device will result in the new device being authorized.

Parameters
 userId: OST Platform user id provided by application server

OstWalletSdk.getAddDeviceQRCode(
    userId: String
    ) throws -> CIImage?

Perform QR action

QR codes can be used to encode transaction data for authorizing devices, making purchases via webstores, etc. This method can be used to process the information scanned off a QR code and act on it.

Parameters
 userId: OST Platform user id provided by application server
 payload: Json string of payload is scanned by QR-Code.
 delegate: Callback implementation object for application communication

OstWalletSdk.performQRAction(
    userId: String,
    payload: String,
    delegate: OstWorkflowDelegate
    )

Reset a User's PIN

The user's PIN is set when activating the user. This method supports re-setting a PIN and re-creating the recoveryOwner as part of that.

Parameters
 userId: OST Platform user id provided by application server
 passphrasePrefix: Passphrase prefix provided by application server
 oldUserPin: Users old Pin
 newUserPin: Users new Pin
 delegate: Callback implementation object for application communication

OstWalletSdk.resetPin(
    userId: String,
    passphrasePrefix: String,
    oldUserPin: String,
    newUserPin: String,
    delegate: OstWorkflowDelegate
    )

Initialize Recovery

A user can control their Brand Tokens using their authorized devices. If they lose their authorized device, they can recover access to their BrandTokens by authorizing a new device via the recovery process .

Parameters
 userId: OST Platform user id provided by application server
 recoverDeviceAddress: Device address which wants to recover
 passphrasePrefix: Passphrase prefix provided by application server
 userPin: Users Pin
 delegate: Callback implementation object for application communication

OstWalletSdk.initiateDeviceRecovery(
    userId: String,
    recoverDeviceAddress: String,
    userPin: String,
    passphrasePrefix: String,
    delegate: OstWorkflowDelegate
    )

Abort Device Recovery

To abort initiated device recovery.

Parameters
 userId: OST Platform user id provided by application server
 userPin: Users Pin
 passphrasePrefix: Passphrase prefix provided by application server
 delegate: Callback implementation object for application communication

OstWalletSdk.abortDeviceRecovery(
    userId: String,
    userPin: String,
    passphrasePrefix: String,
    delegate: OstWorkflowDelegate)

Revoke Device

To revoke device access.

Parameters
 userId: OST Platform user id provided by application server
 deviceAddressToRevoke: Device address to revoke
 delegate: Callback implementation object for application communication

OstWalletSdk.revokeDevice(
    userId: String,
    deviceAddressToRevoke: String,
    delegate: OstWorkflowDelegate) 

Update Biometric Preference

This method can be used to enable or disable the biometric.

Parameters
 userId: OST Platform user id provided by application server
 enable: Preference to use biometric
 delegate: Callback implementation object for application communication

OstWalletSdk.updateBiometricPreference(
    userId: String,
    enable: Bool,
    delegate: OstWorkflowDelegate) 

Get User

Get user entity for given userId

Parameters
 userId: OST Platform user id provided by application server
 returns: User entity

OstWalletSdk.getUser(userId: String) 

Get Token

Get token entity for given tokenId

Parameters
 tokenId: Token id provided by application server
 returns: Token entity

OstWalletSdk.getToken(tokenId: String) 

Get Current Device

Get current device of user

let user: OstUser = OstWalletSdk.getUser(userId: String)
let device: OstCurrentDevice = user.getCurrentDevice()

Get Biometric preference

Get biometric preference for user

Parameters
 userId: OST Platform user id provided by application server
 returns: Boolean

OstWalletSdk.isBiometricEnabled(userId: String) 

Workflow Callbacks

/// Register device passed as parameter.
///
/// - Parameters:
///   - apiParams: Register Device API parameters.
///   - delegate: To pass response.
func registerDevice(
        _ apiParams: [String: Any],
        delegate: OstDeviceRegisteredDelegate
        )
Argument Description
apiParams
[String: Any]
Device information for registration
delegate
OstDeviceRegisteredDelegate
delegate.deviceRegistered(_ apiResponse: [String: Any] ) should be called to pass the newly created device entity back to SDK.
In case data if there is some issue while registering the device then the current workflow should be canceled by calling delegate.cancelFlow()
/// Pin needed to check the authenticity of the user.
/// Developers should show pin dialog on this callback.
///
/// - Parameters:
///   - userId: User id whose passphrase prefix and pin required.
///   - delegate: To pass pin
func getPin(
        _ userId: String,
        delegate: OstPinAcceptDelegate
        )
Argument Description
userId
String
Unique identifier of the user
delegate
OstPinAcceptDelegate
delegate.pinEntered(_ userPin: String, passphrasePrefix: String) should be called to pass the PIN back to SDK.
For some reason if the developer wants to cancel the current workflow they can do it by calling delegate.cancelFlow()
/// Inform SDK user about invalid pin.
/// Developers should show invalid pin error and ask for pin again on this callback.
///
/// - Parameters:
///   - userId: User id whose passphrase prefix and pin validattion failed.
///   - delegate: To pass another pin.
func invalidPin(
        _ userId: String,
        delegate: OstPinAcceptDelegate
        )
Argument Description
userId
String
Unique identifier of the user
delegate
OstPinAcceptDelegate
delegate.pinEntered(_ userPin: String, passphrasePrefix: String) should be called to again pass the PIN back to SDK.
For some reason if the developer wants to cancel the current workflow they can do it by calling delegate.cancelFlow()
/// Inform SDK user that entered pin is validated.
/// Developers should dismiss pin dialog on this callback.
/// - Parameter userId: Id of user whose pin and passphrase prefix has been validated.
func pinValidated(_ userId: String)
Argument Description
userId
String
Unique identifier of the user
/// Inform SDK user the the flow is complete.
///
/// - Parameter workflowContext: A context that describes the workflow for which the callback was triggered.
/// - Parameter ostContextEntity: Status of the flow.
func flowComplete(
        workflowContext: OstWorkflowContext,
        ostContextEntity: OstContextEntity
        )
Argument Description
ostWorkflowContext
OstWorkflowContext
Information about the workflow
ostContextEntity
OstContextEntity
Information about the entity
/// Inform SDK user that flow is interrupted with errorCode.
/// Developers should dismiss pin dialog (if open) on this callback.
///
/// - Parameter workflowContext: A context that describes the workflow for which the callback was triggered.
/// - Parameter ostError: Reason of interruption.
func flowInterrupted(
        workflowContext: OstWorkflowContext,
        error: OstError
        )
Argument Description
ostWorkflowContext
OstWorkflowContext
Information about the workflow
ostError
OstError
ostError object will have details about the error that interrupted the flow
/// Verify data which is scanned from QR-Code
///
/// - Parameters:
///   - workflowContext: OstWorkflowContext
///   - ostContextEntity: OstContextEntity
///   - delegate: callback
func verifyData(
        workflowContext: OstWorkflowContext,
        ostContextEntity: OstContextEntity,
        delegate: OstValidateDataDelegate
        )
Argument Description
workflowContext
OstWorkflowContext
Information about the current workflow during which this callback will be called
ostContextEntity
OstContextEntity
Information about the entity
delegate
OstValidateDataDelegate
delegate.dataVerified() should be called if the data is verified successfully.
In case data is not verified the current workflow should be canceled by calling delegate.cancelFlow()
/// Acknowledge user about the request which is going to make by SDK.
///
/// - Parameters:
///   - workflowContext: OstWorkflowContext
///   - ostContextEntity: OstContextEntity
func requestAcknowledged(
        workflowContext: OstWorkflowContext,
        ostContextEntity: OstContextEntity
        )
Argument Description
ostWorkflowContext
OstWorkflowContext
Information about the workflow
ostContextEntity
OstContextEntity
Information about the entity

OST JSON APIs

User Balance

Api to get user balance. Balance of only current logged-in user can be fetched.

Parameters
 userId: OST Platform user id provided by application server
 delegate: Callback implementation object for application communication

OstJsonApi.getBalance(
    forUserId userId: String,
    delegate: OstJsonApiDelegate) 

Price Points

Api to get price points. It will provide latest conversion rates of base token to fiat currency.

Parameters
 userId: OST Platform user id provided by application server
 delegate: Callback implementation object for application communication

OstJsonApi.getPricePoint(
    forUserId userId: String,
    delegate: OstJsonApiDelegate) 

Balance With Price Points

Api to get user balance and price points. Balance of only current logged-in user can be fetched. It will also provide latest conversion rates of base token to fiat currency.

Parameters
 userId: OST Platform user id provided by application server
 delegate: Callback implementation object for application communication

OstJsonApi.getBalanceWithPricePoint(
    forUserId userId: String,
    delegate: OstJsonApiDelegate) 

Transactions

Api to get user transactions. Transactions of only current logged-in user can be fetched.

Parameters
 userId: OST Platform user id provided by application server
 requestPayload: request payload. Such as next-page payload, filters etc.
 delegate: Callback implementation object for application communication

OstJsonApi.getTransaction(
    forUserId userId: String,
    params: [String: Any]?,
    delegate: OstJsonApiDelegate) 

Pending Recovery

Api to get pending recovery.

Parameters
 userId: OST Platform user id provided by application server
 delegate: Callback implementation object for application communication

OstJsonApi.getPendingRecovery(
    forUserId userId: String,
    delegate: OstJsonApiDelegate) 

Json Api Response Delegates

/// Success callback for API
///
/// - Parameter data: Success API response
func onOstJsonApiSuccess(data:[String:Any]?);
Argument Description
data
[String: Any]?
Json api success response
/// Failure callback for API
///
/// - Parameters:
///   - error: OstError
///   - errorData: Failure API response
func onOstJsonApiError(error:OstError?, errorData:[String:Any]?);
Argument Description
error
OstError?
ostError object will have details about the error that interrupted the flow
data
[String: Any]?
Json api failure response

Reference

For a sample implementation, please see the Demo App

There are other references are listed below:

About

[ALPHA] UI from SDK for wallet

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages