Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ethereum 在Web3.js中使用本地私钥_Ethereum_Web3js_Binance Smart Chain - Fatal编程技术网

Ethereum 在Web3.js中使用本地私钥

Ethereum 在Web3.js中使用本地私钥,ethereum,web3js,binance-smart-chain,Ethereum,Web3js,Binance Smart Chain,如何通过使用本地私钥与智能合约进行交互并使用Web3.js发送交易?私钥是硬编码的还是来自环境(.env)文件 这是Node.js和服务器端交互或以太坊/Polygon/Binance智能链智能合约批处理作业所需的 例如,您可能会遇到错误 Error: The method eth_sendTransaction does not exist/is not available Infura、Quikonde等以太坊节点提供商要求您在本地签署传出事务,然后再通过其节点进行广播 Web3.js没有

如何通过使用本地私钥与智能合约进行交互并使用Web3.js发送交易?私钥是硬编码的还是来自环境(
.env
)文件

这是Node.js和服务器端交互或以太坊/Polygon/Binance智能链智能合约批处理作业所需的

例如,您可能会遇到错误

Error: The method eth_sendTransaction does not exist/is not available

Infura、Quikonde等以太坊节点提供商要求您在本地签署传出事务,然后再通过其节点进行广播

Web3.js没有内置此功能。您需要将其用作以太坊提供商的中间件

TypeScript中的示例:


const Web3=require('Web3');
const HDWalletProvider=require(“@truffle/hdwallet provider”);
从“../../build/contracts/AnythingTruffleCompiled.json”导入{abi}”;
//
//项目机密在此硬编码
//-不要在现实生活中这样做
//
//没有0x前缀
const myPrivateKeyHex=“123123”;
const infuraProjectId=“123123”;
const provider=new Web3.providers.HttpProvider(`https://mainnet.infura.io/v3/${infurad}`);
//创建在本地签名事务的web3.js中间件
const localKeyProvider=新的HDWalletProvider({
私钥:[myPrivateKeyHex],
providerOrUrl:提供程序,
});
const web3=新的web3(localKeyProvider);
const myAccount=web3.eth.accounts.privateKeyToAccount(myPrivateKeyHex);
//与以太坊mainnet上现有的、已部署的智能合约交互
常量地址='0x123123';
const myContract=新的web3.eth.合同(abi如有,地址);
//一些示例调用如何从智能合约读取数据
const currentDuration=await myContract.methods.lockingtime().call();
const currentAmount=wait myContract.methods.lockingAmount().call();
console.log('Transaction signer account is',myAccount.address',智能合约is',address);
log('startingtransaction now');
//批准此余额用于代币交换
const receive=wait myContract.methods.myMethod(1,2).send({from:myAccount.address});
控制台日志(“发送接收”,接收);
您还需要避免将私钥提交到任何Github存储库。是一种用于机密管理的低入口解决方案