首先,我得先说明一下,我本身是不是写 Solidity 工程师。我的合约完全是在网路上研究来的。之前对虚拟货币的概念,大约就像我对「股票」、「期货」的认知,就这样而已。但公司突然有需求,就派我来研究,接下来是我这整个专案所遇到的问题:以下是我的合约:
这个合约经过某位热心的网友帮我修改过了,应该是没问题的。
我的目的是
1、使用者只需要授权一次
2、可以自由转移使用者钱包的金额至任何一个钱包,而不需要使用者再次授权
当然以上只是核心的功能,其他的只能等这两个功能实现后,才能再继续用web3 去作互动。
一开始我部署在 Sepolia testnet ,部署没有问题,但在授权合约时,被收了高额的gas ,大约5.x的eth , 但我不知道问题出在哪里。
于是我换部署在 polygan 。 在polygan 一直授权失败,但却找不到问题。我尝试着把gas费提高,但依旧授权失败。
以下是我的合约内容跟程式,我该怎麽修正,还是我该怎麽找资料?
solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.27;
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
}
contract USDTManager {
IERC20 public usdt;
constructor() {
usdt = IERC20(0xc2132D05D31c914a87C6611C10748AEb04B58e8F);
}
function transferUSDTFromUser(address from, address to, uint256 amount) public {
require(usdt.transferFrom(from, to, amount), "Transfer failed");
}
function getUSDTBalance(address account) public view returns (uint256) {
return usdt.balanceOf(account);
}
}
Web3 + html
if (typeof window.ethereum !== 'undefined' || typeof window.trustwallet !== 'undefined') {
web3 = new Web3(window.ethereum || window.trustwallet);
} else {
alert('please install Trust Wallet or MetaMask');
}
document.getElementById('connectWallet').addEventListener('click', async () => {
if (typeof window.ethereum !== 'undefined') {
web3 = new Web3(window.ethereum);
try {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
userAddress = accounts[0];
console.log("connection MetaMask:", userAddress);
const gasPrice = await web3.eth.getGasPrice();
gasPriceAsString = web3.utils.fromWei(gasPrice, 'gwei');
usdtContract = new web3.eth.Contract(usdtABI, usdtAddress);
usdtManagerContract = new web3.eth.Contract(usdtManagerABI, usdtManagerAddress);
$('#approveUSDT').prop('disabled', false);
$('#transferUSDT').prop('disabled', false);
} catch (error) {
console.error("connect MetaMask failed:", error);
}
} else {
alert('please install MetaMask ');
}
});
document.getElementById('approveUSDT').addEventListener('click', async () => {
try {
const balance = await usdtContract.methods.balanceOf(userAddress).call();
console.log("user's balance:", balance);
const gasPrice = await web3.eth.getGasPrice();
const amount = web3.utils.toWei('10', 'mwei');
const gasEstimate = web3.eth.estimateGas({
to: usdtManagerAddress,
data: usdtManagerContract.methods.approve(usdtManagerAddress, balance).encodeABI()
});
console.log("approve gas:", gasEstimate);
return false;
const tx = await usdtManagerContract.methods.approve(usdtManagerAddress, balance).send({
from: userAddress,
gas: 100000000,
gasPrice: 100000000
});
console.log("approve success:", tx.transactionHash);
} catch (error) {
console.error("approve failed:", error);
}
});
感谢各位的热心