我正在开发一个 NestJS 项目,我的服务中有此功能:
async activateCompany(data: CompanyActivateRequest): Promise<void> {
(...)
await this.blockchain.addController(newWallet.address);
await this.blockchain.increaseAllowance(newWallet.address,data.monthlyBalance);
(...)
}
这是我的
addController
功能
async addController(walletAddress: string): Promise<void> {
try {
const wallet = new ethers.Wallet(process.env.OWNER_PRIVATE_KEY,this._provider);
const contract = new ethers.Contract(process.env.CONTRACT_ADDRESS, this._abi, wallet);
await contract.addController(walletAddress);
} catch (error) {
throw new InternalServerErrorException(['blockchain-error']);
}
}
这是我的
increaseAllowance
功能
async increaseAllowance(walletAddress: string, amount: number, increaseNonce: boolean): Promise<void> {
try {
const wallet = new ethers.Wallet(process.env.OWNER_PRIVATE_KEY, this._provider);
const contract = new ethers.Contract(process.env.CONTRACT_ADDRESS, this._abi, wallet);
await contract.increaseAllowance(walletAddress, amount);
} catch (error) {
throw new InternalServerErrorException(['blockchain-error']);
}
}
我遇到了随机数问题,主要是随机数过低。我该如何正确处理?
我正在使用安全帽在本地运行区块链。
我尝试向每个函数传递一个布尔值,当它
true
时将1添加到当前随机数,但这对于同时完成多个交易来说效果不佳。
有几个部分可以使这项工作可靠:
在
ethers
中,类似的方法调用将导致 TransactionResponse
。该交易响应将包含现已提交到链的交易的hash
。
一旦提交,您需要
wait()
才能进行交易挖矿 - 取决于区块链以及精心选择的速度和安全性平衡 [*],您必须等待该交易出现在区块中:
const response: TransactionResponse = await contract.increaseAllowance(walletAddress, amount)
// The NUMBER_OF_BLOCKS is an optional parameter
// and stands for the number of blocks that need to be "built"
// on top of the block with your transaction
//
// The higher the number, the less likely it is that
// your transaction will disappear from the blockchain
// by the mechanism of reorgs
//
// The lower the number, the faster this function will execute
const receipt: TransactionReceipt = await response.wait(NUMBER_OF_BLOCKS)
一般来说,如果您的服务器钱包想要并行服务大量用户,您将需要以某种方式对交易进行排序,否则随机数问题将不可避免。
这里的第一个选项是创建一个处理事务提交的作业队列。有多种选择,根据您的预算和服务复杂性,您可能想尝试类似由
bull
支持的 redis
之类的东西,或者更简单但不太坚固的 fastq
。
第二个选项是拥有一个充当售票机的服务,为 Web 服务器请求处理程序提供随机数。
我的回答越来越长,希望它至少有一点帮助:)