I am trying to send a signed transaction using web3 1.0 and Infura.io through the browser. When I run it I dont get any errors but the transaction never hits the blockchain so I am confused on whats happening.
*See the log below to see the details
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>
<script src="https://cdn.rawgit.com/ethereumjs/browser-builds/2fb69a714afe092b06645286f14b94f41e5c062c/dist/ethereumjs-tx.js"></script>
Here is the script –
var web3 = new Web3();
if(web3.setProvider(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/API KEY'))){
web3.eth.net.isListening();
}
// Get Contract ABI
var abi = JSON.parse('MY ABI')
// Define Variable for Contract ABI
var AK = new web3.eth.Contract(abi);
// Set Contract Address
AK.options.address = "CONTRACT ADDRESS";
// Set amount
var amountToSend = 100;
var weiAmount = amountToSend * 1e18;
// create transaction - to address, amount
var data = AK.methods.transfer("SEND TO ADDRESS", weiAmount).encodeABI();
// object to hold the transaction data From Address
web3.eth.getTransactionCount("SEND FROM ADDRESS").then(count => {
// Set transaction params
let privateKey = new EthJS.Buffer.Buffer("FROM ADDRESS PRIVATE KEY", "hex")
web3.eth.getGasPrice().then(gasPrice => {
let txParams = {
nonce: web3.utils.toHex(count),
gasLimit: web3.utils.toHex(250000),
value: web3.utils.toHex(0),
gas: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(web3.eth.gasPrice),
to: "TO ADDRESS",
from: "FROM ADDRESS",
data: data
}
// Sign Transaction
let tx = new EthJS.Tx(txParams)
tx.sign(privateKey)
let serializedTx = tx.serialize().toString('hex')
var receipt = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
console.log('serializedTx:', serializedTx)
console.log('Receipt:', receipt)
});
});
When i run the script it logs –
Promise {<pending>, _events: undefined, emit: ƒ, on: ƒ, once: ƒ, off: ƒ, …}
addListener: ƒ (t,e,r)
emit: ƒ (t,e,r,i,o,a)
listeners: ƒ (t,e)
off: ƒ (t,e,r,i)
on: ƒ (t,e,r)
once: ƒ (t,e,r)
removeAllListeners: ƒ (t)
removeListener: ƒ (t,e,r,i)
_events: undefined
__proto__: Promise
[[PromiseStatus]]: "pending"
[[PromiseValue]]: undefined
Best Answer
the
sendSignedTransaction(...)
returns a Promise (the same asgetTransactionCount(...)
above it). One way to get its result is to do it like:The transaction won't be mined instantly. It will take anywhere from a few seconds to more than an hour (depending on your gas_price and network congestion) to have it mined and thus the result printed to console.
You can get the transaction hash before broadcasting it with:
And look for the transaction status on etherscan a few seconds/minutes after broadcasting it. If the tx is valid, it should show up as pending/confirmed.