簡體   English   中英

Web3.js - 如何簽署一個交換的批准交易?

[英]Web3.js - How to sign an approve transaction for a swap?

我想以編程方式交換兩個令牌。 我必須先批准金額。 如何批准使用 web3.js ?

到目前為止,這是我想出的,但我收到錯誤Error: Returned error: nonce too low

const myAddress = "my-wallet-address"
const privateKey = Buffer.from('my-private-key', 'hex');

const test = async () => {
    const allowed = await tokenContract.methods.allowance(myAddress, 'UniswapV2Router02ContractAddress').call()

    const encodedABI = tokenContract.methods.approve('UniswapV2Router02ContractAddress', amountIn).encodeABI();
    const tx = {        
        from: myAddress,
        to: 'UniswapV2Router02ContractAddress',
        gas: 2000000,
        data: encodedABI
    };
    
    const customCommon = Common.default.forCustomChain(
        'mainnet',
        {
          name: 'SAMPLE testnet',
          networkId: custom-testnet-id,
          chainId: custom-testnet-id,
        },
        'petersburg',
      )

    const txTx = new Tx(tx, {common: customCommon});
    txTx.sign(privateKey);

    // below gives true, true
    console.log(txTx.validate(), ethUtil.bufferToHex(txTx.getSenderAddress()) === ethUtil.bufferToHex(ethUtil.privateToAddress(privateKey)))
    
    const serializedTx = txTx.serialize();

    // below line results in error
    await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))

    // await uniswapV2Router02Contract.methods.swapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn, amountOutMin, path, myAddress, deadline).send({from: myAddress})
}

test()

Error: Returned error: nonce too low錯誤: web3.eth.sendSignedTransaction() 總是返回“返回錯誤:nonce too low”但是我已經驗證我的私鑰屬於發件人(我)的交易所以我一無所知

我們先來了解一下以太坊中的 Nonce 是什么。

基於以太坊論文:Nonce 是標量值,等於從地址(錢包)發送的交易數量......

交易包括:轉賬、創建合約...

當您在不同的地方使用您的帳戶時,可能會引發Nonce too low錯誤。 特別是當您使用私鑰簽署交易時。

例子:

  • 一個地址有 5 個事務,從 MM (PC1) 發送。 隨機數為 5。
  • 您使用私鑰 (PC2) 在另一個地方執行交易。 Nonce 是 6。但是,MM 對此一無所知。
  • 回到PC1,在MM上執行另一個事務,Nonce應該是7,但是MM說是6。這導致Nonce太低的問題。

對於修復,我們可以簡單地重置 MM 錢包:

從 MM 菜單中選擇設置 => 高級設置 => 重置。


為什么reset MM可以解決nonce問題?

  • 通過復位,MM 可以同步地址的事務數量。 所以隨機數很好地增加了。

這是代碼:

var Web3 = require('web3');
var web3 = new Web3("rpc-node-link");
var Tx = require('ethereumjs-tx').Transaction;
var Common = require('ethereumjs-common');
var ethUtil = require('ethereumjs-util')

web3.eth.getTransactionCount(myAddress, async (err, txCount) => {
        const encodedABI = contractWhichisApproving.methods.approve(contractThatWantsToSpendContractWhichisApprovingsToken, amountIn).encodeABI();
        const tx = {
            nonce: web3.utils.toHex(txCount),
            from: myAddress,
            to: contractWhichisApprovingAddress,
            gas: 2000000,
            data: encodedABI
        };

        const customCommon = Common.default.forCustomChain(
            'mainnet',
            {
            name: 'Example testnet',
            networkId: custom-testnet-id,
            chainId: custom-testnet-id,
            },
            'petersburg',
        )

        const txTx = new Tx(tx, {common: customCommon});
        txTx.sign(privateKey);

        // following line logs true, true
        console.log(txTx.validate(), ethUtil.bufferToHex(txTx.getSenderAddress()) === ethUtil.bufferToHex(ethUtil.privateToAddress(privateKey)))

        const serializedTx = txTx.serialize();
        console.log('sending')
        await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', console.log);
        console.log('done')
    });

使用自定義鏈的參考: https ://github.com/ethereumjs/ethereumjs-tx/blob/master/examples/custom-chain-tx.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM