可以使用以下的库进行与以太坊链的交互:
https://github.com/web3j/web3j
https://github.com/BANKEX/web3swift
Transacting with a smart contract:
Function function = new Function<>( "functionName", // function we're calling Arrays.asList(new Type(value), ...), // Parameters to pass as Solidity Types Arrays.asList(new TypeReference
Querying the state of a smart contract:
Function function = new Function<>( "functionName", Arrays.asList(new Type(value)), // Solidity Types in smart contract functions Arrays.asList(new TypeReference
示例:
fun requestAuth(context:Context?){
//获取该账户交易个数
val nonce =web3j?.ethGetTransactionCount(
mWallet?.address.toString(), DefaultBlockParameterName.LATEST)?.sendAsync()?.get()?.transactionCount
val function = FunctionEncoder.makeFunction("auth", arrayListOf("uint8", "uint256"),
arrayListOf(WalletConfigure.mContractIndex, WalletConfigure.mDeviceId)as List?, emptyList())
val encodedFunction = FunctionEncoder.encode(function)
val rawTransaction = RawTransaction.createTransaction(nonce, WalletConfigure.mGasPrice,
WalletConfigure.mGasLimit, WalletConfigure.mContractAddress, BigInteger.ZERO, encodedFunction)
val signedString = TransactionEncoder.signMessage(rawTransaction, mWallet)
val transactionResponse =web3j?.ethSendRawTransaction(Numeric.toHexString(signedString))?.sendAsync()?.get()
val hash = transactionResponse?.transactionHash
if (!TextUtils.isEmpty(hash)){
if (null != context){
Toast.makeText(context, "交易已发送到链上:$hash", Toast.LENGTH_LONG).show()
}
}else{
Toast.makeText(context, "交易失败:"+transactionResponse?.error?.message, Toast.LENGTH_LONG).show()
}
}