Flutter 1inch api 交换不断恢复

问题描述 投票:0回答:1

我正在使用 flutter 开发一个钱包应用程序。现在我正在集成 1Inch Swap api,但我在指南上遇到了困难。我 遵循招摇中指示的每个步骤,但执行不断恢复,如您所见:https://polygonscan.com/tx/0x278bffd11b38788699beffc9e6f6acada6d4d9f0c368414b360a70cf1d06db22 我什至尝试直接从 1inch swagger 网站签署交易,结果相同。 输入数据和调用的函数看起来很奇怪,我可以获得一些帮助吗? 其他问题:在swagger中,快速启动中没有提到broadCastRawTransaction函数,有必要吗?我尝试向它传递签名的 tx 哈希值,但只得到 500-“内部服务器错误”。

代码在这里:

Future<Map<String, dynamic>> swap({
    required AppUser appUser,
    required LocalWallet fromWallet,
    required WalletNetwork walletNetwork,
    required RemoteToken startToken,
    required TokenValue endToken,
    required double quantity,
  }) async {
    Map<String, dynamic> result = {};
    final queryParameters = {
      'src': startToken.tokenValue.contractAddresses[walletNetwork.chainGeckoName],
      'dst': endToken.contractAddresses[walletNetwork.chainGeckoName],
      'amount': (quantity * pow(10, startToken.tokenValue.decimals)).toInt(),
      'from': fromWallet.address,
      'slippage': 1,
      'includeTokensInfo': true,
      'disableEstimate': true,
    };
    String params = queryParameters
        .toString()
        .replaceAll('{', '')
        .replaceAll('}', '')
        .replaceAll(', ', '&')
        .replaceAll(': ', '=');
    try {
      http.Response response = await http.get(
        Uri.parse('$_endPoint${walletNetwork.chainID}/swap?${params.toString()}'),
        headers: _headers,
      );
      if (response.statusCode == 200) {
        dynamic jsonTx = json.decode(response.body)['tx'];
        String transaction = await signAndSendTransaction(
          appUser: appUser,
          senderLocalWallet: fromWallet,
          transaction: Transaction(
            from: EthereumAddress.fromHex(jsonTx['from']),
            to: EthereumAddress.fromHex(jsonTx['to']),
            value: EtherAmount.fromInt(EtherUnit.wei, int.parse(jsonTx['value'])),
            data: Uint8List.fromList(jsonTx['data'].codeUnits),
            gasPrice: EtherAmount.fromInt(EtherUnit.wei, int.parse(jsonTx['gasPrice'])),
            maxGas: 100000,
          ),
        );
        await broadCastRawTransaction(transaction, walletNetwork);
        result.addAll({'transaction': transaction});
      } else {
        debugPrint('ErrCode: ${response.statusCode} - err: ${response.body}');
        result.addAll({'error': json.decode(response.body).toString()});
        throw Exception('1Inch swap error');
      }
    } on Exception catch (e) {
      debugPrint(e.toString());
      debugPrint('error call 1Inch swap');
    }
    return result;
  }

Future<String> signAndSendTransaction({
    required AppUser appUser,
    required LocalWallet senderLocalWallet,
    required Transaction transaction,
  }) async {
    WalletNetwork network = getWalletNetworkFromName(appUser, senderLocalWallet.network);
    Web3Client web3client = Web3Client('${network.rpc}$ankr', Client());
    EthPrivateKey credentials = EthPrivateKey.fromHex(senderLocalWallet.privateKey);

    String response = await web3client
        .sendTransaction(credentials, transaction, chainId: network.chainID)
        .catchError((e) => (e.message));

    web3client.dispose();
    debugPrint('SignAndSendTransactionRespose: $response');
    return response;
  }

broadCastRawTransaction(
    rawTransaction,
    WalletNetwork walletNetwork,
  ) async {
    http.Response response = await http.post(
      Uri.parse(
          'https://api.1inch.dev/tx-gateway/v1.1/${walletNetwork.chainID}/broadcast'),
      headers: _headers,
      body: json.encode({'rawTransaction': rawTransaction}),
    );
    print(response.statusCode);
    print(response.body);
    if (response.statusCode == 200) {
      print(response.body);
    }
  }
flutter polygon swap
1个回答
0
投票

解决了更改 uint8list 方法的问题。 而不是使用

data: Uint8List.fromList(jsonTx['data'].codeUnits

我把它改成了这个功能:

Uint8List hexToBytes(String hexString) {
  hexString = hexString.substring(2);
  var bytes = <int>[];
  for (var i = 0; i < hexString.length; i += 2) {
    var hexChar = hexString.substring(i, i + 2);
    var byte = int.parse(hexChar, radix: 16);
    bytes.add(byte);
  }
  return Uint8List.fromList(bytes);
}

事实并非如此 而不是使用

data: hexToBytes(jsonTx['data']

© www.soinside.com 2019 - 2024. All rights reserved.