Solidity

Solidity 轉移函式將乙太幣發送到合約地址而不是我指定的接收者

  • March 2, 2022

我正在嘗試開發一個涉及使用智能合約進行餘額轉移的項目。我想將餘額發起人地址轉移一個地址。我正在使用 Remix IDE 來編寫我的契約,並且我正在使用 Ropsten 測試網。

我遇到的問題是我是否使用 Solidity或函式transfer(),發起的餘額轉移是從合約的地址,而不是發起到收件人的地址。不管我在參數中輸入了什麼,結果都是一樣的。send()``call()``msg.sender

這是程式碼片段:

function buy(uint256 tokenId) public payable {
       address payable recipient = payable(ownerOf(tokenId)); // Get the address and cast it to payable
       require(msg.value >= cost, "Insufficient bid.");
       require(msg.sender != address(recipient), "User already owns the NFT");
       require(recipient.send(msg.value)); // Problematic part: Transfer value
       _safeTransfer(recipient, msg.sender, tokenId, ""); // Unrelated: Transferring a NFT
}

當我執行上述程式碼時,Metamask 上會出現以下螢幕:

在此處輸入圖像描述

現在的問題是地址0x6A9...4691是合約的地址而不是recipient的地址。如果我讓它繼續前進,餘額不會顯示在recipient’ 餘額中。

如果您發現問題,請告訴我。或者我是否必須通過參考特定錢包的文件來使用前端來啟動資金轉移?順便說一句,在我的情況下,這並不理想。

實際上我自己找到了解決方案。將餘額轉移到合約地址是預期的行為。首先合約收到餘額,然後將餘額發送到收件人的地址。

我創建的問題是我在 Ganache 上部署了合約並試圖在 Ropsten 上呼叫該函式,反之亦然,這就是為什麼餘額沒有顯示在收件人地址上的原因。當我將合約部署到目前網路時,餘額轉移功能起作用了!

愚蠢的錯誤,但請確保避免它。如果您在多個網路上進行測試,則可能會發生這種情況。

因此,為名為“address _userAddress”的函式創建一個參數。

那應該工作:)

就像是 :

function buy(uint256 tokenId, address _userAddress) public payable {
       address payable recipient = _userAddress; // Get the address and cast it to payable
       require(msg.value >= cost, "Insufficient bid.");
       require(msg.sender != address(recipient), "User already owns the NFT");
       require(recipient.send(msg.value)); // Problematic part: Transfer value
       _safeTransfer(_userAddress, msg.sender, tokenId, ""); // Unrelated: Transferring a NFT
}

也可能存在一些allowanec問題,因此請確保您已授予智能合約批准以在代幣合約中花費資金

引用自:https://ethereum.stackexchange.com/questions/115317