【发布时间】:2018-03-08 06:35:03
【问题描述】:
考虑以下代码在 ropsten 测试网中用于 web3js 和以太坊智能合约之间的通信。
web3.eth.getTransactionCount(contractAddress).then(function(lastCountOfTransaction){
var rawTransaction = {
"from": contractAddress,
"nonce": "0x" + lastCountOfTransaction.toString(16),
"gasPrice": web3.utils.toHex(1 * 1e9), //1 can be changed to n gwei
"gasLimit": web3.utils.toHex(1000000), // 1000000 can be to set to any n number
"to": userAddress,
"value": "0x0",
"data": ContractObject.methods.transfer(userAddress, noOfTokens).encodeABI(),
"chainId": chainId
};
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'),function(err,hash){
if (!err){
console.log(hash);
resolve(hash);
}
else{
console.log(err);
resolve(err);
}
});
});
我有多个代币持有者,比如一个是合约地址,它具有代币的初始值,一个是代币所有者,它具有总供应量。我想从合约地址而不是合约所有者帐户中提供代币。如果我们进行如下更改,则可以从所有者帐户转移令牌
web3.eth.getTransactionCount(myAddress).then(function(lastCountOfTransaction){
var rawTransaction = {
"from": myAddress,
"nonce": "0x" + lastCountOfTransaction.toString(16),
"gasPrice": web3.utils.toHex(1 * 1e9), //1 can be changed to n gwei
"gasLimit": web3.utils.toHex(1000000), // 1000000 can be to set to any n number
"to": contractAddress,
"value": "0x0",
"data": ContractObject.methods.transfer(userAddress, noOfTokens).encodeABI(),
"chainId": chainId
};
但是上面的代码没有按预期工作。它确实为我提供了交易哈希,但没有分发令牌。
【问题讨论】:
-
您是否使用与
from地址对应的私钥进行签名? -
您好,谢谢您的回复。合约地址的私钥在哪里?我的意思是,当我单击创建按钮来创建合同时,它只会返回给我一个合同地址。我在这里使用的私钥是合约所有者的。这可能是一个错误,但我不知道合约地址也有私钥。
-
合约没有私钥。您使用的私钥决定了谁在发送交易。如果您想从两个不同的帐户执行操作,您将使用两个不同的私钥进行签名。
-
这就是我所说的我已经创建了一份合同。在创建时,我已经为合约提供了一些硬币。假设是 1000。此外,如果我的合约需要超过 1000 个,我已经给了所有者 2000 个硬币,我可以通过所有者帐户给它。现在在初始阶段,我想从合约地址发送交易。而且合约地址也没有私钥。比我如何从合约账户发送代币。
-
你不能从合约账户发送代币。你所能做的就是调用合约中的函数。所以在合约中写一个发送代币的函数,然后调用它。
标签: blockchain ethereum solidity smartcontracts web3js