gpt4 book ai didi

javascript - 我如何通过 JavascriptCore 注入(inject)和使用这个 javascript 库 (web3)

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:01 24 4
gpt4 key购买 nike

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

var web3 = new Web3(new Web3.providers.HttpProvider("[我正在使用的提供商]"))

这是我尝试在 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

有什么想法吗?

最佳答案

web3.js 库依赖于 bignumber.jscrypto-js.js (参见 dependencies here)。您需要将这两个 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")
}

关于javascript - 我如何通过 JavascriptCore 注入(inject)和使用这个 javascript 库 (web3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com