Javascript
是否可以使用 web3 和 ethereumjs-tx 在 Binance Smart Chain 中發送交易?
我想在幣安智能鏈中發送交易,但出現錯誤:new Error(“Chain with name " + chain + " not supported”);
const Tx = require('ethereumjs-tx').Transaction; const Web3 = require('web3'); const web3 = new Web3("https://mainnet.infura.io/v3/xxx"); const privKey = Buffer.from('xxx', 'hex'); const addressFrom = '0xXXX'; const addressTo = '0xXXX'; web3.eth.getTransactionCount(addressFrom, (err, txCount) => { const txObject = { nonce: web3.utils.toHex(txCount), to: addressTo, value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')), gasLimit: web3.utils.toHex(100000), gasPrice: web3.utils.toHex(web3.utils.toWei('100', 'gwei')) }; const tx = new Tx(txObject, {'chain':'smart chain'}); //const tx = new Tx(txObject, {'chain':'56'}); //const tx = new Tx(txObject, {'chain':'binance'}); tx.sign(privKey); const serializedTrans = tx.serialize(); const raw = '0x' + serializedTrans.toString('hex'); web3.eth.sendSignedTransaction(raw, (err, txHash) => { console.log('txHash:', txHash) }); } );
如果使用這些庫無法發送交易,那麼在 Smart Chain 中發送交易對我來說更好嗎?我找到了幾個網站https://docs.binance.org/smart-chain/wallet/wallet_api.html>和<https://github.com/drunken005/binance-utils但在我看來它們是針對正常幣安的網路(正如我在範例中看到的錢包以 bnb 開頭……)還是我錯了?
Infura 不支持 BSC,請嘗試使用此處顯示的其他提供商
// mainnet const web3 = new Web3('https://bsc-dataseed1.binance.org:443'); // testnet const web3 = new Web3('https://data-seed-prebsc-1-s1.binance.org:8545');
或者使用像 quikNode 這樣的提供者
試試這個:
import Common from 'ethereumjs-common'; import transaction from 'ethereumjs-tx'; const common = Common.default.forCustomChain('mainnet', { name: 'bnb', networkId: 56, chainId: 56 }, 'petersburg'); const tx = new transaction.Transaction(data, { common });