钱包如何执行智能合约

可以使用以下的库进行与以太坊链的交互:

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() {}, ...));String encodedFunction = FunctionEncoder.encode(function)Transaction transaction = Transaction.createFunctionCallTransaction( , , , contractAddress, , encodedFunction);org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();String transactionHash = transactionResponse.getTransactionHash();// wait for response using EthGetTransactionReceipt...

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() {}, ...));String encodedFunction = FunctionEncoder.encode(function)org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall( Transaction.createEthCallTransaction(, contractAddress, encodedFunction), DefaultBlockParameterName.LATEST) .sendAsync().get();List someTypes = FunctionReturnDecoder.decode( response.getValue(), function.getOutputParameters());

示例:

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

}

}

你可能感兴趣的:(钱包如何执行智能合约)