如何通过 smatcontract 正确签署代币转移?
How to correctly sign the transfer of tokens through the smatcontract?
我有 smartcontract 方法转移:
function transfer(address to, uint256 amount) external {
require(balances[msg.sender] >= amount, "Not enough tokens");
balances[msg.sender] -= amount;
balances[to] += amount;
}
通过 HardHat 使用帐户炼金术部署后:“https://eth-ropsten.alchemyapi.io/v2/iwxxx”
我得到:
使用账户部署合约:0x5Cххх
账户余额:299502973995526766
代币地址:0xC1ххх
和运行这段代码:
const acc_addr = "0x5Cxxx";
const address = "0xC1xxx"
const receiverAddress = "0x39xxx"
var Web3 = require('web3')
var provider = "https://eth-ropsten.alchemyapi.io/v2/iwxxx";
var web3 = new Web3(new Web3.providers.HttpProvider(provider));
const token = new web3.eth.Contract(abi, address);
token.setProvider(web3.currentProvider)
token.methods.balanceOf(acc_addr).call((err, res) => {
log("balanse => ", res);
});
token.methods.transfer(receiverAddress, "1").send({ "from": acc_addr }, (err, res) => {
if (err) {
console.log(err);
return
}
console.log("Hash transaction: " + res);
});
所以我得到了错误:
Error: Returned error: Unsupported method: eth_sendTransaction.
Alchemy does not hold users' private keys. See available methods at
https://docs.alchemy.com/alchemy/documentation/apis
at Object.ErrorResponse (D:\node_modules\web3-core-helpers\lib\errors.js:28:19)
我知道我必须以某种方式签署此交易。但问题是,我怎么看不懂?
将ETH从一个地址转移到另一个地址的正常交易非常简单明了。
您需要使用 wallet.add() 方法将交易发送方的私钥(在您的情况下为 acc_addr
)传递到本地 web3 实例。
web3.eth.accounts.wallet.add('0x<private_key>');
注意:Web3 不与节点提供商共享私钥 - 仅使用它在本地签署交易。
我有 smartcontract 方法转移:
function transfer(address to, uint256 amount) external {
require(balances[msg.sender] >= amount, "Not enough tokens");
balances[msg.sender] -= amount;
balances[to] += amount;
}
通过 HardHat 使用帐户炼金术部署后:“https://eth-ropsten.alchemyapi.io/v2/iwxxx”
我得到: 使用账户部署合约:0x5Cххх 账户余额:299502973995526766 代币地址:0xC1ххх
和运行这段代码:
const acc_addr = "0x5Cxxx";
const address = "0xC1xxx"
const receiverAddress = "0x39xxx"
var Web3 = require('web3')
var provider = "https://eth-ropsten.alchemyapi.io/v2/iwxxx";
var web3 = new Web3(new Web3.providers.HttpProvider(provider));
const token = new web3.eth.Contract(abi, address);
token.setProvider(web3.currentProvider)
token.methods.balanceOf(acc_addr).call((err, res) => {
log("balanse => ", res);
});
token.methods.transfer(receiverAddress, "1").send({ "from": acc_addr }, (err, res) => {
if (err) {
console.log(err);
return
}
console.log("Hash transaction: " + res);
});
所以我得到了错误:
Error: Returned error: Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys. See available methods at https://docs.alchemy.com/alchemy/documentation/apis
at Object.ErrorResponse (D:\node_modules\web3-core-helpers\lib\errors.js:28:19)
我知道我必须以某种方式签署此交易。但问题是,我怎么看不懂?
将ETH从一个地址转移到另一个地址的正常交易非常简单明了。
您需要使用 wallet.add() 方法将交易发送方的私钥(在您的情况下为 acc_addr
)传递到本地 web3 实例。
web3.eth.accounts.wallet.add('0x<private_key>');
注意:Web3 不与节点提供商共享私钥 - 仅使用它在本地签署交易。