如何通过拥有本地私钥与智能契约交互并发送与Web3.js的事务?私钥要么是硬编码的,要么来自环境(.env
)文件?
这是需要Node.js和服务器端的交互或批处理作业与Ethereum/Polygon/Binance智能链智能合同。
你可能会遇到错误
Error: The method eth_sendTransaction does not exist/is not available
发布于 2021-05-28 09:58:18
Ethereum节点提供程序(如Infura、QuikNode和其他提供程序)要求您在通过其节点广播事务之前在本地对它们进行签名。
in没有内置的函数。您需要使用@块菌/hd钱包-供应商包作为您的Ethereum提供程序的中间件。
TypeScript中的示例:
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封装是一种用于机密管理的低入口解决方案。
发布于 2022-06-20 16:41:16
您可以通过使用ethers.js而不是不需要其他包的web3来实现您想要的结果。首先导入库:
Node.js:
npm install --save ethers
const { ethers } = require("ethers");
网页浏览器:
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="application/javascript"></script>
定义提供者。一种方法是使用提供者URL,如下所示:
const provider = new ethers.providers.JsonRpcProvider(rpcProvider);
然后,为了在不需要授权的情况下与合同进行交互,我们将使用私钥和提供者创建一个钱包,如下所示:
const signer = new ethers.Wallet(privateKey,provider)
现在,您可以使用前面一步中创建的address、ABI和签名者创建契约:
const contract = new ethers.Contract(contractAddress,ABI, signer);
现在,您可以直接与契约交互。例如,获取令牌的余额:
const tokenBalance = await nftContractReadonly.balanceOf(signer.getAddress(),tokenId);
不要忘记将私钥存储在安全的地方,千万不要在网页中硬编码。
发布于 2022-06-22 05:15:06
有一种更好、更简单的方式来签署和执行智能契约功能。这里您的函数是addBonus。
首先,我们将创建智能契约实例:
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函数
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;
}
}
https://stackoverflow.com/questions/67736753
复制相似问题