You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用Nethereum Web3的slot0函数?解码异常求助

解决Nethereum调用Uniswap V3 slot0函数的解码异常问题

你的代码触发System.NotSupportedException的核心原因有两个:

  • 误用FunctionMessage类:这个类用于构建需发送交易的函数调用消息(写操作),不适合解析只读函数的返回值。
  • 错误定义返回结构:Uniswap V3的slot0函数返回的是包含7个字段的元组,而非单一uint160类型,导致解码时类型不匹配。

修正方案一:使用自定义返回DTO类解析

定义对应slot0返回结构的类,通过ReturnParameter标记每个字段的类型和索引:

public class Slot0Response
{
    [ReturnParameter("uint160", 0)]
    public BigInteger SqrtPriceX96 { get; set; }

    [ReturnParameter("int24", 1)]
    public int Tick { get; set; }

    [ReturnParameter("uint16", 2)]
    public ushort ObservationIndex { get; set; }

    [ReturnParameter("uint16", 3)]
    public ushort ObservationCardinality { get; set; }

    [ReturnParameter("uint16", 4)]
    public ushort ObservationCardinalityNext { get; set; }

    [ReturnParameter("uint8", 5)]
    public byte FeeProtocol { get; set; }

    [ReturnParameter("bool", 6)]
    public bool Unlocked { get; set; }
}

修改调用代码:

var web3 = new Web3("https://mainnet.infura.io/v3/SECRET_KEY");
var abi = GetAbi("Abi.json");
var pool = web3.Eth.GetContract(abi, "0x4e68Ccd3E89f51C3074ca5072bbAC773960dFa36");
var slot0Function = pool.GetFunction("slot0");
var slot0Result = await slot0Function.CallAsync<Slot0Response>();

修正方案二:直接解析返回的对象列表

如果不想定义DTO类,可直接获取返回的对象列表并逐个转换类型:

var web3 = new Web3("https://mainnet.infura.io/v3/SECRET_KEY");
var abi = GetAbi("Abi.json");
var pool = web3.Eth.GetContract(abi, "0x4e68Ccd3E89f51C3074ca5072bbAC773960dFa36");
var slot0Function = pool.GetFunction("slot0");
var result = await slot0Function.CallAsync<List<object>>();

var sqrtPriceX96 = (BigInteger)result[0];
var tick = (int)result[1];
var observationIndex = (ushort)result[2];
var observationCardinality = (ushort)result[3];
var observationCardinalityNext = (ushort)result[4];
var feeProtocol = (byte)result[5];
var unlocked = (bool)result[6];

注意事项

确保你的Abi.json文件中包含slot0函数的正确定义,其outputs部分需对应7个返回字段的类型和名称,否则解码仍会失败。

内容的提问来源于stack exchange,提问作者speed258

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:22:36