1

I have been trying to use the web3 library with JavascriptCore in Swift. A web3 instance is created by running

var web3 = new Web3(new Web3.providers.HttpProvider("[the provider im using]"))

This is the code I am trying to do this in Swift with:

if let url = Bundle.main.url(forResource: "web3", withExtension: "js"){
     let lib = try! String(contentsOfFile: url.path)
     let jsvirtualmachine = JSVirtualMachine()
     let context = JSContext(virtualMachine: jsvirtualmachine)
     context.evaluateScript(lib)

     let web3 = context.evaluateScript("var web3 = new Web3(new Web3.providers.HttpProvider('[myprovider]')")
     let fn = context.objectForKeyedSubscript("web3")
     let fn1 = fn?.construct(withArguments: [])
     let latestBlockNumber = context.evaluateScript("web3.eth.blockNumber")
     print(latestBlockNumber)
}

I have tried printing out latestBlockNumber, web3, fn, and fn1 and all of them return undefined

Any ideas?

1
  • Did you success with this try? Commented Oct 29, 2021 at 6:03

1 Answer 1

4

The web3.js library has dependencies on bignumber.js and crypto-js.js (See dependencies here). You will need to add these two JS libs to the bundle and load them in a similar way, e.g.

do {
    let bigNumberJS = try String(contentsOf: Bundle.main.url(forResource: "bignumber.min", withExtension: "js")!, encoding: .utf8)
    let cryptoJS = try String(contentsOf: Bundle.main.url(forResource: "crypto-js", withExtension: "js")!, encoding: .utf8)
    let web3JS = try String(contentsOf: Bundle.main.url(forResource: "web3-light.min", withExtension: "js")!, encoding: .utf8)
    context.evaluateScript(bigNumberJS)
    context.evaluateScript(cryptoJS)
    context.evaluateScript(web3JS)
    context.evaluateScript("var Web3 = require('web3'); var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));")
    if let version = context.evaluateScript("web3.version.api") {
        print("Web3 version is \(version)")
    }
}
catch {
    print("An error occurred")
}
Sign up to request clarification or add additional context in comments.

2 Comments

hi, so unlike bignumber, crypto-js has multiple files. How to handle that?
Each of their releases contains a crypto-js.js which contains everything in one file. Try downloading the zip file of the latest release. github.com/brix/crypto-js/releases/tag/3.1.9-1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.