Solidity

批准從使用者錢包中提取資金的合約

  • May 19, 2021

我想實現以下流程:

  • 使用者點擊一個按鈕,允許我的合約代表使用者花費資金
  • 使用者點擊第二個按鈕,資金從使用者的錢包轉移到合約。

據我了解,這需要分成兩個交易。

所以我認為這樣的事情會起作用:

合約程式碼:

function approve(uint amount) public {
 // Calling this function first from remix
 ERC20(Token_address).approve(address(this), amount)
}

function transferFrom(uint amount) public {
 // Then calling this function from remix
 ERC20(Token_address).transferFrom(msg.sender, address(this), amount)
}

但它讓我在混音中的氣體估計失敗。我懷疑這是因為我不能讓合約呼叫該approve()函式。需要從批准契約的使用者那裡呼叫以提取其資金。如果使用者不是另一個智能合約而只是一個擁有元遮罩錢包的人,我怎麼能做到這一點?

你是對的,你的合約不應該呼叫該approve方法本身,因為它會msg.sender在代幣智能合約的上下文中成為,這會導致你的合約自我批准。

您希望使用者批准您的契約,您可以編寫一個腳本來實現這一點。web3js 1.2 的一個例子可能是:

var erc20Instance = new web3.eth.Contract(abi,Token_address);

erc20Instance.methods.approve(contractAddress, amount).send({from: userAddress}, 
function(err, transactionHash) {
//some code
});

和 :

  • abi : 代幣合約的 abi。您可以將https://ethereumdev.io/abi-for-erc20-contract-on-ethereum/用於 ERC20。
  • contractAddress :要批准的合約地址。
  • 金額:要批准的金額。請注意,您可以通過發送金額為 0 的新交易來“拒絕”契約,因為它將覆蓋之前的值。
  • userAddress :發件人的地址。

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