블록체인
[ethereum] privatekey를 이용하여 address 복구, transaction 발생
멍개.
2022. 8. 27. 16:52
privateKeyToAccount()를 이용하면 privatekey를 이용하여 account를 가져올 수 있습니다.
let Web3 = require('web3')
let web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io'));
let PK = "0x1076f9a014620c526eaf424cad97755a8d5c1a492f2637731f56975d30805db6"
let account = web3.eth.accounts.privateKeyToAccount(PK)
console.log(account)
· 실행결과
{ address: '0x31bF95273C33C9042da801580F6d54a6f11b3CfE',
privateKey:
'0x1076f9a014620c526eaf424cad97755a8d5c1a492f2637731f56975d30805db6',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt] }
가져온 account에서 encrypt를 이용하면 keystore를 만들 수 있고, signTransactio을 이용하면 트랜잭션에 서명하여 rawTransaction을 만들 수 있습니다.
· sample
let Web3 = require('web3')
let web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io'));
/*
web3.utils.toWei(1, 'ether') : 1ETH => 1 * 10 ^ 18
web3.utils.fromWei(1, 'ether'): 1 * 10 ^ 18 => 1ETH
*/
(async () => {
let EOA1 = "0x31bF95273C33C9042da801580F6d54a6f11b3CfE"
let PK = "0x1076f9a014620c526eaf424cad97755a8d5c1a492f2637731f56975d30805db6"
let EOA2 = "0x22C353816541d2437dd9Aa673Be0de07d869df6B"
let eoa1_nonce = await web3.eth.getTransactionCount(EOA1, "pending")
let balance = await web3.eth.getBalance(EOA1)
console.log(eoa1_nonce)
console.log(balance)
console.log(web3.utils.toWei("0.1", 'ether'))
console.log(web3.utils.toWei("21", 'Gwei'))
let txParam = {
nonce: eoa1_nonce,
from: EOA1,
to: EOA2,
value: web3.utils.toHex(web3.utils.toWei("0.1", 'ether')), // 0.1 이더
gasPrice: web3.utils.toHex(web3.utils.toWei("21", 'Gwei')), // 가스 가격
gasLimit: web3.utils.toHex(300000), // 가스 최대 사용량
}
let account = web3.eth.accounts.privateKeyToAccount(PK)
let signedTx = await account.signTransaction(txParam)
let txInfo = await web3.eth.sendSignedTransaction(signedTx.rawTransaction, (err, txHash) => {
if (err) {
console.log('========== transaction 발생 중 에러 ===========')
return
}
console.log('========== transaction 발생 ===========')
console.log(txHash)
})
console.log('========== transaction 처리완료 ===========')
console.log(txInfo)
})()