1

我一直在尝试在 Swift 中使用带有 JavascriptCore 的web3库。通过运行创建一个 web3 实例

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

这是我试图在 Swift 中执行此操作的代码:

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)
}

我尝试打印出 latestBlockNumber、web3、fn 和 fn1,它们都返回 undefined

有任何想法吗?

4

1 回答 1

4

web3.js库依赖于bignumber.jscrypto-js.js(请参阅此处的依赖项)。您需要将这两个 JS 库添加到包中并以类似的方式加载它们,例如

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")
}
于 2017-11-01T21:51:09.540 回答