由于web3swift库并不完善,单元测试中缺少“addr”方法,而本人开发过程中又需要用到,即:将ENS域名转成16进制地址;于是特地写了篇文章作为记录,希望有同样需求的同鞋能用上。
首先要引入web3swift库,地址:https://github.com/BANKEX/web3swift
//MARK:将ENS域名转成16进制地址字符串
func keccakHexStringFromENSString (inputName: String) -> String {
var node = ""
for _ in 0..<32 {
node += "00"
}
let name = normalize(name: inputName)
if name.count > 0 {
//将字符串用“.”分割成数组并将数组倒序
var labels = name.split(separator: ".")
labels.reverse()
//递归
for subLabels in labels {
let str = String(subLabels)
var labbelSha = str.sha3(.keccak256)
labbelSha = "0x" + node + labbelSha
let data = convertToData(labbelSha as AnyObject)
node = (data?.sha3(.keccak256).toHexString())!
print("0x" + node)
}
}
return infuratestResolver(encodeStr: "0x" + node)
}
//将某类型转成Data
func convertToData(_ value: AnyObject) -> Data? {
switch value {
case let d as Data:
return d
case let d as String:
if d.hasHexPrefix() {
let hex = Data.fromHex(d)
if hex != nil {
return hex
}
}
let str = d.data(using: .utf8)
if str != nil {
return str
}
case let d as [UInt8]:
return Data(d)
case let d as EthereumAddress:
return d.addressData
case let d as [IntegerLiteralType]:
var bytesArray = [UInt8]()
for el in d {
guard el >= 0, el <= 255 els