首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Web3.js中使用本地私钥

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

Stack Overflow用户
提问于 2021-05-28 09:58:18
回答 3查看 5K关注 0票数 5

如何通过拥有本地私钥与智能契约交互并发送与Web3.js的事务?私钥要么是硬编码的,要么来自环境(.env)文件?

这是需要Node.js和服务器端的交互或批处理作业与Ethereum/Polygon/Binance智能链智能合同。

你可能会遇到错误

代码语言:javascript
运行
复制
Error: The method eth_sendTransaction does not exist/is not available
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-05-28 09:58:18

Ethereum节点提供程序(如Infura、QuikNode和其他提供程序)要求您在通过其节点广播事务之前在本地对它们进行签名。

in没有内置的函数。您需要使用@块菌/hd钱包-供应商包作为您的Ethereum提供程序的中间件。

TypeScript中的示例:

代码语言:javascript
运行
复制
 const Web3 = require('web3');
 const HDWalletProvider = require("@truffle/hdwallet-provider");
 import { abi } from "../../build/contracts/AnythingTruffleCompiled.json";
 
 //
 // Project secrets are hardcoded here
 // - do not do this in real life
 //

 // No 0x prefix
const myPrivateKeyHex = "123123123";
const infuraProjectId = "123123123";
 
const provider = new Web3.providers.HttpProvider(`https://mainnet.infura.io/v3/${infuraProjectId}`);

// Create web3.js middleware that signs transactions locally
const localKeyProvider = new HDWalletProvider({
  privateKeys: [myPrivateKeyHex],
  providerOrUrl: provider,
});
const web3 = new Web3(localKeyProvider);

const myAccount = web3.eth.accounts.privateKeyToAccount(myPrivateKeyHex);

// Interact with existing, already deployed, smart contract on Ethereum mainnet
const address = '0x123123123123123123';
const myContract = new web3.eth.Contract(abi as any, address);

// Some example calls how to read data from the smart contract
const currentDuration = await myContract.methods.stakingTime().call();
const currentAmount = await myContract.methods.stakingAmount().call();

console.log('Transaction signer account is', myAccount.address, ', smart contract is', address);

console.log('Starting transaction now');
// Approve this balance to be used for the token swap
const receipt = await myContract.methods.myMethod(1, 2).send({ from: myAccount.address });
console.log('TX receipt', receipt);

您还需要避免将您的私钥提交到任何Github存储库。dotenv封装是一种用于机密管理的低入口解决方案。

票数 8
EN

Stack Overflow用户

发布于 2022-06-20 16:41:16

您可以通过使用ethers.js而不是不需要其他包的web3来实现您想要的结果。首先导入库:

Node.js:

代码语言:javascript
运行
复制
npm install --save ethers
const { ethers } = require("ethers");

网页浏览器:

代码语言:javascript
运行
复制
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
        type="application/javascript"></script>

定义提供者。一种方法是使用提供者URL,如下所示:

代码语言:javascript
运行
复制
const provider = new ethers.providers.JsonRpcProvider(rpcProvider);

然后,为了在不需要授权的情况下与合同进行交互,我们将使用私钥和提供者创建一个钱包,如下所示:

代码语言:javascript
运行
复制
    const signer = new ethers.Wallet(privateKey,provider)

现在,您可以使用前面一步中创建的address、ABI和签名者创建契约:

代码语言:javascript
运行
复制
const contract = new ethers.Contract(contractAddress,ABI, signer);

现在,您可以直接与契约交互。例如,获取令牌的余额:

代码语言:javascript
运行
复制
const tokenBalance = await nftContractReadonly.balanceOf(signer.getAddress(),tokenId);

不要忘记将私钥存储在安全的地方,千万不要在网页中硬编码。

进一步阅读:提供程序 签字人

票数 0
EN

Stack Overflow用户

发布于 2022-06-22 05:15:06

有一种更好、更简单的方式来签署和执行智能契约功能。这里您的函数是addBonus。

首先,我们将创建智能契约实例:

代码语言:javascript
运行
复制
 const createInstance = () => {
  const bscProvider = new Web3(
    new Web3.providers.HttpProvider(config.get('bscRpcURL')),
  );
  const web3BSC = new Web3(bscProvider);
  const transactionContractInstance = new web3BSC.eth.Contract(
    transactionSmartContractABI,
    transactionSmartContractAddress,
  );
  return { web3BSC, transactionContractInstance };
};

现在我们将创建一个新的函数来签署和执行addBonus函数

代码语言:javascript
运行
复制
const updateSmartContract = async (//parameters you need) => {
     try {
    const contractInstance = createInstance();
// need to calculate gas fees for the addBonus
    const gasFees =
      await contractInstance.transactionContractInstance.methods
        .addBonus(
         // all the parameters
        )
        .estimateGas({ from: publicAddress_of_your_desired_wallet });
   const tx = {
      // this is the address responsible for this transaction
      from: chainpalsPlatformAddress,
      // target address, this could be a smart contract address
      to: transactionSmartContractAddress,
      // gas fees for the transaction
      gas: gasFees,
      // this encodes the ABI of the method and the arguments
      data: await contractInstance.transactionContractInstance.methods
        .addBonus(
       // all the parameters
        )
        .encodeABI(),
    };
  // sign the transaction with a private key. It'll return messageHash, v, r, s, rawTransaction, transactionHash
    const signPromise =
       await contractInstance.web3BSC.eth.accounts.signTransaction(
        tx,
        config.get('WALLET_PRIVATE_KEY'),
      );
    // the rawTransaction here is already serialized so you don't need to serialize it again
    // Send the signed txn
    const sendTxn =
      await contractInstance.web3BSC.eth.sendSignedTransaction(
        signPromise.rawTransaction,
      );
    return Promise.resolve(sendTxn);
} catch(error) {
  throw error;
}
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67736753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档