export async function simulateBuy({
target,
requestedOrderSize,
publicClient,
}: {
target: Address;
requestedOrderSize: bigint;
publicClient: GenericPublicClient;
}): Promise<{ orderSize: bigint; amountOut: bigint }> {
const numberResult = await publicClient.simulateContract({
address: target,
abi: coinABI,
functionName: "buy",
args: [
zeroAddress,
requestedOrderSize,
0n, // minAmountOut
0n, // sqrtPriceLimitX96
zeroAddress, // tradeReferrer
],
// We want to ensure that the multicall3 contract has enough ETH to buy in the simulation
stateOverride: [
{
address: baseSepolia.contracts.multicall3.address,
balance: parseEther("10000000"),
},
],
});
const orderSize = numberResult.result[0];
const amountOut = numberResult.result[1];
return { orderSize, amountOut };
}
function buy(
address recipient,
uint256 orderSize,
uint256 minAmountOut,
uint160 sqrtPriceLimitX96,
address tradeReferrer
) public payable nonReentrant returns (uint256, uint256) {
// Ensure the recipient is not the zero address
if (recipient == address(0)) {
revert AddressZero();
}
// Calculate the trade reward
uint256 tradeReward = _calculateReward(orderSize, TOTAL_FEE_BPS);
// Calculate the remaining size
uint256 trueOrderSize = orderSize - tradeReward;
// Handle incoming currency
_handleIncomingCurrency(orderSize, trueOrderSize);
// Set up the swap parameters
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: currency,
tokenOut: address(this),
fee: LP_FEE,
recipient: recipient,
amountIn: trueOrderSize,
amountOutMinimum: minAmountOut,
sqrtPriceLimitX96: sqrtPriceLimitX96
});
// Execute the swap
uint256 amountOut = ISwapRouter(swapRouter).exactInputSingle(params);
_handleTradeRewards(tradeReward, tradeReferrer);
_handleMarketRewards();
emit CoinBuy(msg.sender, recipient, tradeReferrer, amountOut, currency, tradeReward, trueOrderSize);
return (orderSize, amountOut);
}
3070 💯
Explore the intricacies of buying and selling using smart contracts in the latest blog post by @3070.eth. Delve into important functions like `simulateBuy` and the implications of retaining correct recipient addresses in Transaction-Knowledge Adoption for secure contracts execution.