android 如何使用Web3j库调用ERC721中的tokenURI()函数?

cl25kdpy  于 2023-02-06  发布在  Android
关注(0)|答案(1)|浏览(149)

我需要查看包含所有元数据的NFT-image。我决定像这样调用tokenURI()函数,但它不起作用

private fun getNFTMetadata() = viewModelScope.launch(Dispatchers.IO){
    //tokenURI  -- by token ID
    val web3j: Web3j = createWeb3j() ?: return@launch

    var ids = listOf<Uint256>(Uint256.DEFAULT)

    val function: org.web3j.abi.datatypes.Function = org.web3j.abi.datatypes.Function(
        "tokenURI",
        ids,
        listOf()
    )

    val encodedFunction = FunctionEncoder.encode(function)
    val response: EthCall = web3j.ethCall(
        Transaction.createEthCallTransaction(WALLET_ADDRESS, CONTRACT_ADDRESS, encodedFunction),
        LATEST
    ).sendAsync().get()

    if (response.value != null){
        state.value = response.value
    } else {
        state.value = "NAN"
    }
}

private fun createWeb3j(): Web3j? {
    val webSocketService = WebSocketService(WEB_SOCKET_URL, true)
    try {
        webSocketService.connect()
    } catch (e: ConnectException) {
        e.printStackTrace()
    }
    return Web3j.build(webSocketService)
}

我真的不知道如何正确调用那个函数,请帮帮我!)

r6hnlfcb

r6hnlfcb1#

我发现了错误。我更改了接收参数。

private fun getNFTMetadata() = viewModelScope.launch(Dispatchers.IO){
    //tokenURI  -- by token ID
    val web3j: Web3j = createWeb3j() ?: return@launch

    val big: Uint256 = Uint256(1)

    val function: org.web3j.abi.datatypes.Function = org.web3j.abi.datatypes.Function(
        "tokenURI",
        listOf(big),
        listOf(object : TypeReference<Utf8String>() {})
    )

    val encodedFunction = FunctionEncoder.encode(function)
    val response: EthCall = web3j.ethCall(
        Transaction.createEthCallTransaction(WALLET_ADDRESS, CONTRACT_ADDRESS, encodedFunction),
        LATEST
    ).sendAsync().get()

    if (response.value != null){

        state.value = response.value
    } else {
        state.value = "NAN"
    }
}

相关问题