0.0.20-alpha • Published 20 days ago

@wepin/react-native-sdk v0.0.20-alpha

Weekly downloads
-
License
MIT
Repository
github
Last release
20 days ago

@wepin/react-native-sdk

mit licence npm version. npm downloads

platform - android platform - ios

Wepin React-Native SDK for Android OS and iOS

⏩ Get App ID and Key

Contact to wepin.contact@iotrust.kr

⏩ Install

wepin react native sdk

npm install @wepin/react-native-sdk

or

yarn add @wepin/react-native-sdk

peerDependencies

npm install react-native-device-info
npm install react-native-inappbrowser-reborn
npm install react-native-webview
npm install react-native-encrypted-storage
npm install react-native-permissions
npm install @react-native-clipboard/clipboard

# for ios
cd ios
pod install

or

yarn add react-native-device-info
yarn add react-native-inappbrowser-reborn
yarn add react-native-webview
yarn add react-native-encrypted-storage
yarn add react-native-permissions
yarn add @react-native-clipboard/clipboard

# for ios
cd ios
pod install

Additional Installation (Version 0.0.7-alpha and above)

To enable the web3 provider functionality in the React Native environment, you need to install and configure the rn-nodeify module.

  • Install the rn-nodeify module in your devDependencies.

    npm install --save-dev rn-nodeify

    or

    yarn add --dev rn-nodeify
  • Add the following rn-nodeify command to your project's package.json file as a postinstall script:

    "scripts": {
      	...,
    	"postinstall": "rn-nodeify --install fs,crypto,https,http,stream,path,zlib,assert --hack",
    	...
    }
  • After running the postinstall script, import the generated shim.js file in the root file of your application as follows:

    import './shim'

⏩ Config Deep Link

Deep link scheme format: 'wepin.' + Your wepin app id

‼️ Notice of Change: Deep Link Scheme Value (From SDK Version 0.0.20-alpha) ‼️ For developers using SDK version 0.0.20 and above, please note that the structure of the Deep Link Scheme value has been updated.

  • Before: pakage name or bundle id + '.wepin'
  • After: 'wepin.' + wepin appid

This change is essential for the proper functioning of the Wepin widget. Please ensure to apply the new scheme value for the correct operation of the Wepin widget.

For Android

Add the below line in your app's AndroidMainfest.xml file

<activity
	android:name=".MainActivity"
	....
>
	....
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="wepin.WEPIN_APP_ID" /> <!-- 'wepin.' + app id of your wepin app -->
        </intent-filter>
      </activity>

For iOS

Add the below line in your ios app's AppDelegate.mm file

#import <React/RCTLinkingManager.h>

...

// above @end
- (BOOL)application:(UIApplication *)application
  openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options: options];
}

Add the URL scheme as below:

  1. Open your iOS project with the xcode
  2. Click on Project Navigator
  3. Select Target Project in Targets
  4. Select Info Tab
  5. Click the '+' buttons on URL Types
  6. Enter Identifier and URL Schemes
    • Idenetifier: bundle id of your project
    • URL Schems: 'wepin.' + your Wepin app id

image

⏩ Add Permssion (Version 0.0.20-alpha and above)

To use this SDK, camera access permission is required. The camera function is essential for recognizing addresses in QR code format. [Reference: react-native-permission]

For Android

Add the below line in your app's AndroidMainfest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<uses-permission android:name="android.permission.CAMERA" />
	<!-- ... -->
<mainfest>

For iOS

  1. By default, no permissions are setuped. So first, require the setup script in your Podfile:
# with react-native >= 0.72
- # Resolve react_native_pods.rb with node to allow for hoisting
- require Pod::Executable.execute_command('node', ['-p',
-   'require.resolve(
-     "react-native/scripts/react_native_pods.rb",
-     {paths: [process.argv[1]]},
-   )', __dir__]).strip
+ def node_require(script)
+   # Resolve script with node to allow for hoisting
+   require Pod::Executable.execute_command('node', ['-p',
+     "require.resolve(
+       '#{script}',
+       {paths: [process.argv[1]]},
+     )", __dir__]).strip
+ end
+ node_require('react-native/scripts/react_native_pods.rb')
+ node_require('react-native-permissions/scripts/setup.rb')
# with react-native < 0.72
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
+ require_relative '../node_modules/react-native-permissions/scripts/setup'
  1. Then in the same file, add a setup_permissions call with the wanted permissions:
# …
platform :ios, min_ios_version_supported
prepare_react_native_project!
# ⬇️ uncomment wanted permissions
setup_permissions([
  'Camera',
])
# …
  1. Then execute pod install (📌  Note that it must be re-executed each time you update this config).
  2. Finally, update your Info.plist with the wanted permissions usage descriptions:
<?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>
  <!-- 🚨 Keep only the permissions used in your app 🚨 -->
  <key>NSCameraUsageDescription</key>
  <string>YOUR TEXT</string>
  <!-- … -->
</dict>
</plist>

⏩ Import SDK

import Wepin from '@wepin/react-native-sdk
const wepin = Wepin.getInstance()

Add a <Wepin.WidgetView> component within the main compenent and nest its content inside of it:

function App(): JSX.Element {
    ....
  return (
    <Wepin.WidgetView>
  	  ...
    </Wepin.WidgetView>
  )
}

⏩ Initialize

Methods about initializing Wepin SDK

init

await wepin.init(appId, appSdkKey[, attributes])

Parameters

  • appId \
  • appKey \
  • attributes \ optional
    • Type of attributes is assigned at @wepin/types as IAttributes
      • type: The type of display of widget as wepin is initiated (defalut: 'hide)
        • 'hide' | 'show'
      • defaultLanguage: The language to be displayed on the widget (default: 'ko')
        • Currently, only 'ko' and 'en' are supported.
      • defaultCurrency: The currency to be displayed on the widget (default: 'KRW')
      • loginProviders: An array of login providers to configure the widget. (If not provided, all available login providers will be displayed on the widget.)
        • The loginProviders parameter accepts values defined in the LoginProviders of @wepin/types, starting from version v0.0.11.

Example

await wepin.init('APPID', 'APPKEY', {
  type: 'hide',
  defaultLanguage: 'en',
  defaultCurrency: 'USD',
  loginProviders: ['google', 'apple'],
})

isInitialized

wepin.isInitialized()

The isInitialized() method checks Wepin SDK is initialized.

Return value

  • \
    • true if Wepin SDK is already initialized.

⏩ Methods

Methods can be used after initialization of Wepin SDK.

openWidget

await wepin.openWidget()

The openWidget() method shows Wepin widget. If a user is not logged in, Wepin widget will show login page.

Return value

  • Promise \

closeWidget

await wepin.closeWidget()

The closeWidget() method closes Wepin widget.

Return value

  • Promise \

getAccounts

await wepin.getAccounts()
await wepin.getAccounts(networks)

The getAccounts() method returns user accounts. If user is not logged in, Wepin widget will be opened and show login page. It is recommended to use getAccounts() method without argument to get all user accounts.

Parameters

  • networks \ optional
    • network \ optional

Example

const accounts = await wepin.getAccounts(['Ethereum'])

Return value

  • Promise \
    • If user is logged in, it returns a Promise object resolved with array of account of networks.
      • Type of account is assigned at @wepin/types as IAccount
      • account \
        • address \
        • network \
    • If networks aren't passed, it returns a Promise object resolved with array of account of all networks.
    • Example
      ;[
        {
          address: '0x0000001111112222223333334444445555556666',
          network: 'Ethereum',
        },
      ]
  • Promise \
    • If user is not logged in, it returns Promise \.

getStatus (Support from version 0.0.6-alpha)

wepin.getStatus()

The getStatus() method returns lifecycle of wepin.

Example

var status = wepin.getStatus()

Return value

  • \
    • The WepinLifeCycle is defined at @wepin/types as (Support from version 0.0.7)
      • not_initialized: if wepin is not initialized
      • initializing: if wepin is initializing
      • initialized: if wepin is initialized
      • before_login: if wepin is initialized but the user is not logged in
      • login: if the user is logged in

login(Support from version 0.0.6-alpha)

await wepin.login()

The login() method returns information of the logged-in user. If a user is not logged in, Wepin widget will show login page.

Parameters(Support from version 0.0.14-alpha)

  • email \ optional
    • The email parameter allows users to log in using the specified email address, providing access to the login service.

Example

var userInfo = await wepin.login()
// Use specified Email
var userInfo = await wepin.login('wepin@wepin.io')

Return value

  • Promise \

    • Type of IWepinUser is defined in @wepin/types (Support from version 0.0.7)

      • status \<'success'|'fail'>
      • userInfo \ optional
        • userId \
        • email \
        • provider \<'google'|'apple'|'email'|'naver'|'discord'|'external_token'>
    • Example

      {
      	status: 'success',
      	userInfo: {
      		userID: '123455',
      		email: 'abc@test.com',
      		provider: 'google'
              }
      }

logout (Support from version 0.0.6-alpha)

await wepin.logout()

The logout() method performs a wepin logout .

Return value

  • Promise \

Example

await wepin.logout()

signUpWithEmailAndPassword (Support from version 0.0.9-alpha)

It signs up on the wepin with your email and password.

wepin.signUpWithEmailAndPassword(email, password)

Parameters

  • email \ - User email
  • password \ - User password

Return value

  • Promise \

    • Returns true if the signup is successful.

Exception message

Example

const result = await wepin.signUpWithEmailAndPassword('test@test.com', 'abcd12345')

loginWithEmailAndPassword(Support from version 0.0.9-alpha)

It logs in to the Wepin with your email and password.

wepin.loginWithEmailAndPassword(email, password)

Parameters

  • email \ - User email
  • password \ - User password

Return value

  • Promise \

    • Type of IWepinUser is defined in @wepin/types (Support from version 0.0.8)

      • status \<'success'|'fail'>
      • userInfo \ optional
        • userId \
        • email \
        • provider \<'email'>
    • Example

      {
      	status: 'success',
      	userInfo: {
      		userID: '123455',
      		email: 'test@test.com',
      		provider: 'email'
              }
      }

Exception message

  • Admin Error Message
    • require/wepin-register : If this error occurs, you have to perform the wepin.register(pin) method.

Example

const result = await wepin.loginWithEmailAndPassword('test@test.com', 'abcd12345')

register(Support from version 0.0.9-alpha)

It registers in the Wepin with a wallet pin.

After the signup and login are completed, the Wepin service registration (wallet and account creation) will proceed.

wepin.register(pin)

Parameters

  • pin \ - Wallet PIN

Return value

  • Promise \

    • Returns true if the registeration is successful.
    • After register success, the wepin.login(email, password) method have to be performed again.

Exception message

Example

const result = await wepin.register('123456')

getBalance(Support from version 0.0.9-alpha)

It returns the account's balance information. It can be only usable after widget login.

wepin.getBalance(account)

Parameters

  • account \<IAccount> - Object specifying the account details.

Return value

  • Promise \<IAccountBalance>

    • Type of IAccountBalance and ITokenBalance is defined in @wepin/types (Support from version 0.0.8)

      • symbol \ - symbol of account
      • balance \ - balance of account
      • tokens \<Array<ITokenBalance>> - token balance information for account
        • name \ - token name
        • contract \ - token contract address
        • symbol \ - token symbol
        • balance \ - token balance
    • Example

      {
      	symbol: 'ETH',
              balance: '1.1',
      	tokens:[
      		{
      			name: 'test',
      			contract: '0x123...213',
      			symbol: 'TEST',
      			balance: '10'
      		},
      	]
      }

Exception message

Example

const result = wepin.getBalance({
  address: '0x0000001111112222223333334444445555556666',
  network: 'Ethereum',
})

loginWithExternalToken(Support from version 0.0.19-alpha)

await wepin.loginWithExternalToken(token, sign, withUI?)

It logs in to the Wepin with external token(e.g., idToken). The loginWithExternalToken() method returns information of the logged-in user.

If the user is not registered on Wepin, and the withUI value is set to true, the registration page will be displayed in the widget. However, if the withUI value is set to false or not defined, a require/wepin-register exception will be triggered.

Parameters

  • token <string>
    • External token value to be used for login (e.g., idToken).
  • sign <string>
  • withUI <boolean> optional
    • Indicates whether to display the Wepin widget screen if registration is required.

Example

var userInfo = await wepin.loginWithExternalToken(idToken, sign)

// Use register UI
var userInfo = await wepin.loginWithExternalToken(idToken, sign, true)

Return value

  • Promise <IWepinUser>
    • Type of IWepinUser is defined in @wepin/types (Support from version 0.0.7)
      • status <'success'|'fail'>
      • userInfo <object> optional
        • userId <string>
        • email <string>
        • provider <'external_token'>
    • Example
      {
      	status: 'success',
      	userInfo: {
      		userID: '123455',
      		email: 'abc@test.com',
      		provider: 'external_token'
              }
      }

Exception message

  • Admin Error Message
    • require/wepin-register : If this error occurs, you have to perform the wepin.register(pin) method.

send(Support from version 0.0.20-alpha)

await wepin.send(account, options?)

It returns the sent transaction id information. It can be only usable after widget login.

Parameters

  • account \<IAccount> - Object specifying the account details.

    • The structure and specifications for IAccount are available in the@wepin/typespackage. It typically includes necessary account details such as the address and network.
  • options \<ISendOptions> - (optional) Additional transaction options.

    • The ISendOptions type, detailed in the@wepin/typesfrom version 0.0.12 onwards, encompasses various transaction modifiers such as the amount to send and the recipient address.

Example

// without options
const result = wepin.send({
  address: '0x0000001111112222223333334444445555556666',
  network: 'Ethereum',
})

// with options
const result = wepin.send(
  {
    address: '0x0000001111112222223333334444445555556666',
    network: 'Ethereum',
  },
  { amount: '0.1', toAddress: '0x777777888888999999000000111111222222333333' }
)

Return value

  • Promise \<string>

    • Returns tx id if the send transaction is successful.

    • Example

      '0x0000001111112222223333334444445555556666.............aaaaaabbbbbbccccccddddddeeeeeeffffff'

Exception message

Admin Error Message

The error message types of the admin method are as follows.

Error MessageDescription
invalid/email-formatinvalid email format
invalid/password-formatinvalid password format (A minimum of 8 characters consisting of letters, numbers and special characters. )
invalid/pin-formatinvalid PIN format (6-8 digit number) (*Do not use the same number more than four times when registering)
invalid/firebase-tokeninvalid firebase token
invalid/wepin-api-keyinvalid wepin api key
invalid/accountinvalid account
invalid/email-domaininvalid email domain
invalid/to-addressinvalid to address
auth/existed-emailexisted email
auth/too-many-requeststoo mandy firebase requests
auth/wrong-passwordwrong password
auth/expired-tokenexpired login session
auth/unknown/${string}unknown auth error
fail/send-emailfailed to sent validation email
fail/reset-passwordfailed to set password
fail/email-verifiedfailed to verify email
fail/wepin-loginlogin wepin failed
fail/wepin-registerfailed to register with wepin
fail/get-balancefailed to get balance
fail/check-emailfailed to check email
fail/requireFeeInsufficient fee
fail/requireNetworkFeeInsufficient network fee(only token transaction request)
require/email-verifiedemail verification required
require/signupwepin sign-up required
require/wepin-registerwepin registration required
require/loginwepin login required
unknown/${string}unknown error

⏩ Provider(Support from version 0.0.7-alpha)

Wepin supports providers that return JSON-RPC request responses to connect with blockchain networks in webs. With Wepin Provider, you can easily connect to various networks supported by Wepin.

The providers supported by Wepin are as follows.

  • EVM compatible Networks
  • Klaytn Network

EVM compatible Networks

ethers.js or web3.js can be used with Wepin Provider to interoperate with EVM compatible blockchains.

Support Networks

Chain IDNetwork NameNetwork Variable
1Ethereum Mainnetethereum
5Ethereum Goerli Testnetevmeth-goerli
19Songbird Canary Networkevmsongbird
137Polygon Mainnetevmpolygon
80001Polygon Mumbaievmpolygon-testnet
Time(Coming soon)evmtime
2731Time Testnetevmtime-elizabeth
8217Klaytnklaytn
1001Klaytn Testnetklaytn-testnet
11155111Ethereum Sepoliaevmeth-sepolia
80002Polygon Amoyevmpolygon-amoy

getProvider

It returns a Provider by given network.

wepin.getProvider({ network })

Parameters

  • networt \ - Available chains Wepin helps provide.(Network Variable)

Return value

  • EIP-1193 provider.

Example

const provider = wepin.getProvider({ network: 'ethereum' })

initializeWeb3

  • web3.js

    import Web3 from 'web3'
    const provider = wepin.getProvider({ network: 'ethereum' })
    const web3 = new Web3(provider)
  • ethers.js (Document: ethers.js for React native)

    import 'react-native-get-random-values'
    // Import the the ethers shims (**BEFORE** ethers)
    import '@ethersproject/shims'
    // Import the ethers library
    import { ethers } from 'ethers'
    
    const provider = wepin.getProvider({ network: 'ethereum' })
    const web3 = new ethers.providers.Web3Provider(provider)

Method

  • Get Accounts You can receive account information through the initialized web3.

    • web3.js
    const accounts = await web3.eth.getAccounts()
    • ethers.js
    const signer = web3.getSigner()
    const address = await signer.getAddress()
  • Get Balance You can check the account balance using the account information.

    • web3.js

      const balance = await web3.eth.getBalance(accounts[0])
    • ethers.js

      const balance = await web3.getBalance(address)

Please refer to the document below for instructions on how to check the balance, fee details, block numbers, etc.

  • Send Transaction Transaction can be sent.

    • web3.js

      const accounts = await web3.eth.getAccounts()
      const tx = {
        from: accounts[0],
        gasPrice: '2000000000',
        gas: '21000',
        to: '0x11f4d0A3c1......13F7E19D048276DAe',
        value: '10000000000000000',
      }
      const response = await web3.eth.sendTransaction(tx)
    • ethers.js

      const signer = web3.getSigner()
      const address = await signer.getAddress()
      const tx = {
        from: address,
        gasPrice: '2000000000',
        gasLimit: '21000',
        to: '0x11f4d0A3c1......13F7E19D048276DAe',
        value: '10000000000000000',
      }
      const response = await signer.sendTransaction(tx)
  • Contract Call A contract call can be performed.

    • web3.js

      const callObject = {
        to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', //contract address
        data: '0xc6888fa10000000000000000000000000000000000000000000000000000000000000003',
      }
      const response = await web3.eth.call(callObject)
    • ethers.js

      const callObject = {
        to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe', //contract address
        data: '0xc6888fa10000000000000000000000000000000000000000000000000000000000000003',
      }
      const response = await web3.call(callObject)

For details of Ethereum compatible network providers, please refer to the link below.

EIP-1193: Ethereum Provider Javascript API