iOS日常积累

iOS区块链钱包之web3swift(四)

2018-11-01  本文已影响0人  小奉不在乎

ETH(ropsten)测试币领取地址:http://faucet.ropsten.be:3001/

ETH(ropsten)测试区块查询地址:https://ropsten.etherscan.io/

ETH(Rinkeby)测试币领取地址:https://faucet.rinkeby.io/

ETH(Rinkeby)测试区块查询地址:https://rinkeby.etherscan.io

  1. 生成助记词
let mmemonics = BIP39.generateMnemonics(bitsOfEntropy: 128)
  1. 转换成种子
// 助记词转换为随机种子
let seed = BIP39.seedFromMmemonics(mnemonic)
  1. 创建账号
let keystore = try! BIP32Keystore(seed: seed!, password: "123456")
kLog(keystore?.addresses?.first?.address)

let keystoreManager = KeystoreManager([keystore!])

let account = keystoreManager.addresses![0]

kLog(account)

let privateKey = try! keystore?.UNSAFE_getPrivateKeyData(password: "123456", account: account)
kLog(privateKey?.hex)
  1. 网络配置
// 申请测试链 https://infura.io/
let url = URL(string: "https://rinkeby.infura.io/v3/xxxxxxxxxxxxxxxxxxx")
let web3 = Web3.new(url!)
web3?.provider.network = nil
web3?.addKeystoreManager(keystoreManager)
  1. 获取余额
// 3. 查询余额
let balanceResult = web3?.eth.getBalance(address: account)
guard case .success(let balance)? = balanceResult else {return}
kLog(Web3.Utils.formatToEthereumUnits(balance) ?? "")
  1. 转账
let sendToAddress = EthereumAddress("0x000000000000000000000000")
let contract = web3?.contract(Web3.Utils.coldWalletABI, at: sendToAddress, abiVersion: 2)

let amount = "0.0001"
var options = Web3Options.defaultOptions()
options.value = Web3.Utils.parseToBigUInt(amount, units: .eth)
options.from = account

let intermediate = contract?.method("fallback", options: options)
guard let result = intermediate?.send(password: "123456") else {return print("result error")}
switch result {
case .success(let res):
    print(res)
    return
case .failure(let error):
    print(error)
}
  1. 绘制收款二维码
var eip67Data = Web3.EIP67Code(address: account)
eip67Data.gasLimit = BigUInt(21000)
eip67Data.amount = BigUInt("1000000000000000000")
let encoding = eip67Data.toImage(scale: 10.0)
//self.imageView.image = UIImage(ciImage: encoding)
//self.imageView.contentMode = .scaleAspectFit

好了,记录到此结束,更多知识请期待后续的整理,另外IMtoken开源了,近期我会整理一份源码解析,当然你们有好的建议或者问题也可以在下方留言,我会一一解答的。

上一篇下一篇

猜你喜欢

热点阅读