Interacting with Ethereum in Swift for a Blockchain Wallet Creation

Posted By : Ravi

Oct 31, 2020

Ethereum Blockchain is one of the fastest-growing blockchain technology and many web applications, mobile applications already working with this technology. Although Ethereum Official has provided its implementation for the web application on their Github pages, for Native application (Android and iOS), it is very difficult to implement as there is no official library for the implementation of Native mobile applications. 

 

We can solve this issue by two methods.

 

  • By implementing web application library with webView or WebKit

 

The implementation of any web application library can be done if we don't have an SDK for mobile apps by using webView or WebKit but the problem with this is it will not give a pure native look for mobile application, this solution is only recommended when there is no way to implement the SDK or other solution.

 

  • By searching third party library 

 

The implementation of connecting applications with Ethereum can be done by the third-party library which is giving the exact same feature as a web app. We have found an excellent library name Web3Swift.

 

 
 

Implementation:

Prerequisites

Install CocoaPods using Homebrew by entering the following in a terminal:

brew install CocoaPods

To install the dependency in your project, to your project directory with terminal and write 

 Pod init

Now  open podfile from your project and write

pod 'web3swift', git: 'https://github.com/BANKEX/web3swift.git' 

Now, go to your terminal and write the below command 

pod install

Now, you have successfully installed the dependency in your project, now it's to make some Action. Go to your project folder and open your project with xcworkspace

 
 

 

To Generate mnemonics :

 

let mnemonic = try! BIP39.generateMnemonics(bitsOfEntropy: 256)!
let keystore = try! BIP32Keystore(mnemonics: mnemonic, password: password, mnemonicsPassword: “”))

This will generate 24 words mnemonics if you want to create 12-word mnemonics replace 256 with 128. Here 256 and 128 are bits. You can read more about mnemonics on Wikipedia.


To create a complete wallet below is the source code:

 

fileprivate func createWallet() {

        var web3KeyStore: BIP32Keystore?

        let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

        let web3KeystoreManager = KeystoreManager.managerForPath(userDir + "/keystore")

        do {

            if (web3KeystoreManager?.addresses.count ?? 0 >= 0) {

                let web3Mnemonics = Mnemonics(entropySize: EntropySize.b128, language: .english)

                print(web3Mnemonics.description)

                web3KeyStore = try BIP32Keystore(mnemonics: web3Mnemonics)

                print("keystore", web3KeyStore as Any)

                guard let kStore = web3KeyStore else {

                    return
                }

                let address = kStore.addresses.first

                let param = kStore.keystoreParams

                #if DEBUG

                print("Mnemonics :-> ", web3Mnemonics.description)

                print("Address :::>>>>> ", address as Any)

                print("Address :::>>>>> ", kStore.addresses as Any)

                #endif

                let keyData = try? JSONEncoder().encode(param)

                self.moveToAccountSucessViewController()

            } else {

                web3KeyStore = web3KeystoreManager?.walletForAddress((web3KeystoreManager?.addresses[0])!) as? BIP32Keystore

            }

        } catch {

            print(error, "\(#line)")

        }

    }
 
 

The above function will create a wallet address for ethereum. Now we will store the above-created Mnemonics and wallet address so that we can use it later. and this can be done using different-2 way.


for saving the create wallet data we can save it by creating a JSON file and store it in a file manager with the below code.

let keyData = try? JSONEncoder().encode(param)

FileManager.default.createFile(atPath: userDir + "/keystore"+"/key.json", contents: keyData, attributes: nil)
 

To extract data from file 

let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

 let path = userDir+"/keystore/

wethioKeystoreManager = KeystoreManager.managerForPath(path, scanForHDwallets: true, suffix: "json")

 

Now we can use this wallet detail for the transaction on ethereum.


In the next blog, we will understand how we can do the transaction with this wallet address.

 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

April 4, 2024 at 10:03 pm

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text