From af787e2ae61f39b4c49edd21d6488da36662849e Mon Sep 17 00:00:00 2001 From: Rigidity Date: Wed, 18 Nov 2026 12:32:00 -0500 Subject: [PATCH 1/2] Add buy it now price to auctions --- README.md | 18 ++ puzzles/actions/bid_action.rue | 12 +- puzzles/actions/bid_action.rue.hash | 2 +- puzzles/actions/bid_action.rue.hex | 29 +-- puzzles/actions/end_action.rue | 26 ++- puzzles/actions/end_action.rue.hash | 2 +- puzzles/actions/end_action.rue.hex | 25 +-- src/actions/bid.rs | 4 + src/actions/end.rs | 4 + src/auction.rs | 76 ++++++- src/error.rs | 9 + src/info.rs | 12 ++ src/parser.rs | 17 ++ src/types.rs | 10 + tests/buy_now.rs | 324 ++++++++++++++++++++++++++++ tests/common/mod.rs | 181 ++++++++++++---- tests/fee_math.rs | 1 + 17 files changed, 670 insertions(+), 82 deletions(-) create mode 100644 tests/buy_now.rs diff --git a/README.md b/README.md index 3a5b121..f30ed84 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ The life cycle of an auction is as follows: 2. Until the auction is ended, anyone can place a bid as long as their bid is strictly higher than the current winning bid and meets certain requirements which can be specified by the auctioneer. The bidder locks up their bid plus the buyer's premium and NFT royalty, and the previous bidder is refunded everything they locked up. Multiple bids can be placed in a single spend. 3. When the auction is ended, the NFT is sent to the highest bidder, the auctioneer receives the final bid amount minus the commission, and the buyer's premium, commission, and NFT royalty are paid out. If there were no bids, the NFT is sent back to the auctioneer. An auction can only be ended once, and no bids can be placed after it's ended. +If the auction has a buy now price, a bid at exactly that price wins outright, and the auction can be ended right away instead of at the end time (see [Buy Now](#buy-now)). + Until the first bid is placed, the auctioneer can also cancel the auction at any time, which sends the NFT back to them just like ending it with no bids. Once there's a bid, the auctioneer is committed and the auction can only be ended. A cancelled auction is ended, so it can't be bid on, ended, or cancelled again. ## Customization @@ -22,6 +24,7 @@ The following parameters can be customized by the auctioneer: - The minimum bid increment (flat or percentage) - The minimum amount of time before the auction is ended - The grace period after a bid is placed before the auction is ended +- An optional buy now price These can also be customized, but they may be enforced to be certain values by the auction house and/or wallet, to ensure that they get a cut: @@ -32,6 +35,20 @@ The auctioneer can cancel the auction before the first bid, regardless of these Both the buyer's premium and commission are percentages, and are sent to a single address. If these need to be split between multiple addresses, you should use something external to do so such as the [royalty split](https://splitxch.com/) primitive. +## Buy Now + +An auction can have a buy now price (`AuctionSettings::buy_now_price`). It's curried into the bid and end actions, where 0 means there isn't one, so it can't be changed once the auction is launched. With a buy now price: + +- No bid can exceed it. +- A bid at exactly the buy now price skips the bid verifier, so the increment can't make it unreachable once there's a bid close to it. It must still be strictly higher than the winning bid, and placed before the end time (or within the grace period). So the auction can be bought until it's ended, and while the winning bid is below the buy now price. +- If the winning bid is at the buy now price, the end action skips the end time and grace period checks, since it can never be outbid. Otherwise the auction ends as usual. + +To buy now, a wallet places a bid at the buy now price and ends the auction in the same spend. `AuctionExt::spend_buy_now_actions` builds both actions and unlocks the NFT to the buyer. The buyer funds and asserts the bid like any other bid, and the previous winning bid is refunded in the same spend. `AuctionInfo::available_buy_now_price` returns the price while the auction can still be bought. If a bid at the buy now price is placed on its own instead, anyone can end the auction right after it. + +Buying is a bid, so it competes with pending bids in the same way (see [Competing Bids](#competing-bids)). A buyer can add their buy now after a pending bid in the same spend, which refunds the pending bidder. A pending buy now can't be outbid like this, since no bid can come after it, so the first buy now to reach the mempool wins unless a conflicting spend confirms first. + +The auctioneer can still cancel an auction with a buy now price before the first bid. + ## Cancelling The cancel action asserts that the auction hasn't ended and has no bids, and has no timing restrictions. It must be authorized by a coin at the payout address, which sends the message `c` to the current auction coin with the `SENDER_PUZZLE | RECEIVER_COIN` mode (`0x17`). Since the message is sent to a specific auction coin, it can't be reused once the auction has been spent. `AuctionExt::cancel_authorization` returns the condition that coin must output, and `AuctionExt::spend_cancel_action` builds the action, which must be spent along with `AuctionExt::unlock_nft` in the same spend bundle. Like the end action, the cancel action creates the coin announcement `$`, and leaves the auction in the same state as ending it with no bids. The spend itself still reveals that it was cancelled. @@ -67,6 +84,7 @@ The reserve finalizer takes the reserve coin's parent from the singleton's solut The puzzles can't prevent every misconfiguration on their own, so `AuctionLaunch::into_auction` rejects invalid auctions. `launch_auction` runs the same checks, but not the ones that are left to wallets below, so sellers are responsible for locking the NFT and reserve correctly: - The minimum bid and bid increment must be greater than 0. +- The buy now price, if there is one, must be greater than 0 and at least the minimum bid. Since a bid at the buy now price skips the bid verifier, a lower price would undercut the minimum bid. - The buyer's premium, commission, and NFT royalty can't exceed 10,000 basis points. - Addresses that receive a payment must be unique, and can't be the settlement payments puzzle or the auction's own lock address. Addresses that aren't paid (with 0 basis points) are ignored. diff --git a/puzzles/actions/bid_action.rue b/puzzles/actions/bid_action.rue index b7e60b0..5dedc3f 100644 --- a/puzzles/actions/bid_action.rue +++ b/puzzles/actions/bid_action.rue @@ -11,6 +11,8 @@ fn main( TIMINGS: Timings, BUYERS_PREMIUM_BPS: Int, ROYALTY_BPS: Int, + // The price at which a bid wins the auction outright, or 0 if there's no buy now price + BUY_NOW_PRICE: Int, Truth: AuctionStateTruth, ...{ bid, grace }: Solution, ) -> Output { @@ -30,10 +32,18 @@ fn main( // // Bids must strictly increase regardless of the verifier. Since the initial winning bid amount // is 0, this also ensures that every bid is positive. + // + // Bids can't exceed the buy now price, so a bid at the buy now price can never be outbid, and + // the end action lets it end the auction right away. It skips the bid verifier, since the + // increment could otherwise make the buy now price unreachable once there's a bid close to it. + // Every bid is positive, so this never applies if there's no buy now price. + let is_buy_now = bid.amount == BUY_NOW_PRICE; + assert !Truth.state.ended & (bid.puzzle_hash.length == 32) & (bid.amount > Truth.state.winning_bid.amount) - & BID_VERIFIER(old_bid, bid); + & ((BUY_NOW_PRICE == 0) | !(bid.amount > BUY_NOW_PRICE)) + & (is_buy_now | BID_VERIFIER(old_bid, bid)); // The premium and royalty are rounded separately so that the reserve holds exactly what the end // action pays out. This matters for CAT reserves, since the CAT ring must balance exactly. diff --git a/puzzles/actions/bid_action.rue.hash b/puzzles/actions/bid_action.rue.hash index ea112c0..e0a5cb0 100644 --- a/puzzles/actions/bid_action.rue.hash +++ b/puzzles/actions/bid_action.rue.hash @@ -1 +1 @@ -3357138553b6efb673f36202c78967ade33bbb80cc8e3683f9fe0de97e36a357 +d94e4389be5a2d7f9fd692c792a78f184c8e1f70ec633873b22744f2d0233e9c diff --git a/puzzles/actions/bid_action.rue.hex b/puzzles/actions/bid_action.rue.hex index d5fd468..a1c5f7e 100644 --- a/puzzles/actions/bid_action.rue.hex +++ b/puzzles/actions/bid_action.rue.hex @@ -1,14 +1,15 @@ -ff02ffff01ff02ffff01ff02ffff03ffff22ffff22ffff22ffff20ff8205bf80 -ffff09ffff0dff0680ffff01208080ffff15ff04ff820bbf8080ffff02ff0bff -ff04ffff03ff820bbfff8207bfff8080ffff04ff02ff8080808080ffff01ff04 -ffff04ff82013fffff04ffff10ff04ffff13ffff12ff04ff2f80ffff01822710 -80ffff13ffff12ff04ff5f80ffff018227108080ffff04ff80ff02808080ffff -04ffff03ffff22ff8202ffffff15ff37ff808080ffff04ffff0154ffff04ff37 -ff808080ffff04ffff0155ffff04ff27ff80808080ffff04ffff04ffff013cff -ff04ffff02ff05ffff04ff05ff028080ff808080ffff03ff820bbfffff04ffff -04ffff0181d6ffff04ffff0133ffff04ff820fbfffff04ff8202bfffff04ffff -04ff820fbfff8080ff808080808080ff8080ff8080808080ffff01ff088080ff -0180ffff04ffff04ffff10ff82013f80ff8201bf80ff018080ffff04ffff01ff -02ffff03ffff07ff0380ffff01ff0bffff0102ffff02ff02ffff04ff02ff0580 -80ffff02ff02ffff04ff02ff07808080ffff01ff0bffff0101ff038080ff0180 -ff018080 +ff02ffff01ff02ffff01ff02ffff03ffff22ffff22ffff22ffff22ffff20ff82 +0b7f80ffff09ffff0dff0680ffff01208080ffff15ff04ff82177f8080ffff21 +ffff20ff81bf80ffff20ffff15ff04ff81bf80808080ffff21ffff09ff04ff81 +bf80ffff02ff0bffff04ffff03ff82177fff820f7fff8080ffff04ff02ff8080 +80808080ffff01ff04ffff04ff82027fffff04ffff10ff04ffff13ffff12ff04 +ff2f80ffff0182271080ffff13ffff12ff04ff5f80ffff018227108080ffff04 +ff80ff02808080ffff04ffff03ffff22ff8205ffffff15ff37ff808080ffff04 +ffff0154ffff04ff37ff808080ffff04ffff0155ffff04ff27ff80808080ffff +04ffff04ffff013cffff04ffff02ff05ffff04ff05ff028080ff808080ffff03 +ff82177fffff04ffff04ffff0181d6ffff04ffff0133ffff04ff821f7fffff04 +ff82057fffff04ffff04ff821f7fff8080ff808080808080ff8080ff80808080 +80ffff01ff088080ff0180ffff04ffff04ffff10ff82027f80ff82037f80ff01 +8080ffff04ffff01ff02ffff03ffff07ff0380ffff01ff0bffff0102ffff02ff +02ffff04ff02ff058080ffff02ff02ffff04ff02ff07808080ffff01ff0bffff +0101ff038080ff0180ff018080 diff --git a/puzzles/actions/end_action.rue b/puzzles/actions/end_action.rue index f896621..8b64c90 100644 --- a/puzzles/actions/end_action.rue +++ b/puzzles/actions/end_action.rue @@ -15,6 +15,8 @@ fn main( TIMINGS: Timings, PAYMENTS: Payments, ROYALTY_BPS: Int, + // The price at which a bid wins the auction outright, or 0 if there's no buy now price + BUY_NOW_PRICE: Int, // The inner puzzle hash of the settlement coin, which is wrapped by the CAT layer for CAT reserves SETTLEMENT_PAYMENT_HASH: Bytes32, NFT_COIN_ID: Bytes32, @@ -31,6 +33,11 @@ fn main( let payout = bid_amount - commission; let unlock_conditions = UNLOCKER(Truth.state.winning_bid, ...unlocker_solution); + // The bid action never allows a bid above the buy now price, so a winning bid at the buy now + // price can't be outbid, and the auction can be ended without waiting for it to be over. With no + // buy now price, the winning bid amount is 0 if there are no bids, so it must be checked first. + let bought_now = (BUY_NOW_PRICE > 0) & (bid_amount == BUY_NOW_PRICE); + Output { new_truth: AuctionStateTruth { state: AuctionState { @@ -101,17 +108,22 @@ fn main( message: tree_hash((1, unlock_conditions)), }, - // We always need to make sure the auction is over - AssertSecondsAbsolute { seconds: TIMINGS.end_time }, - // Announce the end of the auction CreateCoinAnnouncement { message: "$" }, - // If there is a grace period, we need to make sure it's over too - ...inline if TIMINGS.grace_period > 0 { - [AssertSecondsRelative { seconds: TIMINGS.grace_period }] - } else { + // Unless the auction was bought now, we need to make sure it's over, including the grace + // period if there is one + ...inline if bought_now { nil + } else { + [ + AssertSecondsAbsolute { seconds: TIMINGS.end_time }, + ...inline if TIMINGS.grace_period > 0 { + [AssertSecondsRelative { seconds: TIMINGS.grace_period }] + } else { + nil + }, + ] }, ], } diff --git a/puzzles/actions/end_action.rue.hash b/puzzles/actions/end_action.rue.hash index 7b243c9..bf816b2 100644 --- a/puzzles/actions/end_action.rue.hash +++ b/puzzles/actions/end_action.rue.hash @@ -1 +1 @@ -4cdb31b702e6f9e363035aab9e431352a901e6e2c31a76b0552d6434a6741344 +5d9df3e170a0ee659f54372537dd49fd11973aaca297eb9b855b048e79b7f21b diff --git a/puzzles/actions/end_action.rue.hex b/puzzles/actions/end_action.rue.hex index f59ad01..5997826 100644 --- a/puzzles/actions/end_action.rue.hex +++ b/puzzles/actions/end_action.rue.hex @@ -1,20 +1,21 @@ -ff02ffff01ff02ffff03ff820b7fffff01ff0880ffff01ff02ffff01ff02ffff -01ff02ffff01ff04ffff04ff8213ffffff04ff80ffff04ffff0101ff827bff80 +ff02ffff01ff02ffff03ff8216ffffff01ff0880ffff01ff02ffff01ff02ffff +01ff02ffff01ff04ffff04ff8227ffffff04ff80ffff04ffff0101ff82f7ff80 8080ffff04ffff03ff15ffff04ffff0181d6ffff04ffff0133ffff04ff82033f ffff04ff15ffff04ffff04ff82033fff8080ff808080808080ffff01ff018080 ffff04ffff03ff09ffff04ffff0181d6ffff04ffff0133ffff04ff8206bfffff 04ff09ffff04ffff04ff8206bfff8080ff808080808080ffff01ff018080ffff 04ffff03ffff15ff02ff8080ffff04ffff0181d6ffff04ffff0133ffff04ff82 03bfffff04ff02ffff04ffff04ff8203bfff8080ff808080808080ffff01ff01 -8080ffff04ffff03ff1dffff04ffff0181d6ffff04ffff0133ffff04ff8202ff +8080ffff04ffff03ff1dffff04ffff0181d6ffff04ffff0133ffff04ff8205ff ffff04ff1dff8080808080ffff01ff018080ffff04ffff04ffff0142ffff04ff ff0117ffff04ffff02ff17ffff04ff17ffff04ffff0101ffff02ff2fffff04ff -827bffff820fff8080808080ffff04ff8205ffff8080808080ffff04ffff04ff -ff0151ffff04ff819fff808080ffff04ffff01ff3cff2480ffff03ffff15ff81 -dfff8080ffff04ffff04ffff0150ffff04ff81dfff808080ff8080ff80808080 -808080808080ffff04ffff11ff05ff0480ff018080ffff04ffff04ffff13ffff -12ff02ff82012f80ffff0182271080ffff04ffff13ffff12ff02ff818f80ffff -0182271080ffff13ffff12ff02ff5f80ffff01822710808080ff018080ffff04 -ff82177fff01808080ff0180ffff04ffff01ff02ffff03ffff07ff0380ffff01 -ff0bffff0102ffff02ff02ffff04ff02ff058080ffff02ff02ffff04ff02ff07 -808080ffff01ff0bffff0101ff038080ff0180ff018080 +82f7ffff821fff8080808080ffff04ff820bffff8080808080ffff04ffff01ff +3cff2480ffff03ffff22ffff15ff8202ffff8080ffff09ff0bff8202ff8080ff +80ffff04ffff04ffff0151ffff04ff819fff808080ffff03ffff15ff81dfff80 +80ffff04ffff04ffff0150ffff04ff81dfff808080ff8080ff80808080808080 +80808080ffff04ffff11ff05ff0480ff018080ffff04ffff04ffff13ffff12ff +02ff82012f80ffff0182271080ffff04ffff13ffff12ff02ff818f80ffff0182 +271080ffff13ffff12ff02ff5f80ffff01822710808080ff018080ffff04ff82 +2effff01808080ff0180ffff04ffff01ff02ffff03ffff07ff0380ffff01ff0b +ffff0102ffff02ff02ffff04ff02ff058080ffff02ff02ffff04ff02ff078080 +80ffff01ff0bffff0101ff038080ff0180ff018080 diff --git a/src/actions/bid.rs b/src/actions/bid.rs index a9e6d95..33df1f7 100644 --- a/src/actions/bid.rs +++ b/src/actions/bid.rs @@ -9,6 +9,8 @@ pub struct BidActionArgs { pub timings: Timings, pub buyers_premium_bps: u64, pub royalty_bps: u64, + /// The price at which a bid wins the auction outright, or 0 if there's no buy now price. + pub buy_now_price: u64, } impl BidActionArgs { @@ -17,12 +19,14 @@ impl BidActionArgs { timings: Timings, buyers_premium_bps: u64, royalty_bps: u64, + buy_now_price: u64, ) -> Self { Self { bid_verifier, timings, buyers_premium_bps, royalty_bps, + buy_now_price, } } } diff --git a/src/actions/end.rs b/src/actions/end.rs index c86a679..26b7738 100644 --- a/src/actions/end.rs +++ b/src/actions/end.rs @@ -9,6 +9,8 @@ pub struct EndActionArgs { pub timings: Timings, pub payments: Payments, pub royalty_bps: u64, + /// The price at which a bid wins the auction outright, or 0 if there's no buy now price. + pub buy_now_price: u64, /// The inner puzzle hash of the settlement coin created by the reserve, which is wrapped by the /// CAT layer for CAT reserves. pub settlement_payment_hash: Bytes32, @@ -21,6 +23,7 @@ impl EndActionArgs { timings: Timings, payments: Payments, royalty_bps: u64, + buy_now_price: u64, settlement_payment_hash: Bytes32, nft_coin_id: Bytes32, ) -> Self { @@ -29,6 +32,7 @@ impl EndActionArgs { timings, payments, royalty_bps, + buy_now_price, settlement_payment_hash, nft_coin_id, } diff --git a/src/auction.rs b/src/auction.rs index cb47e07..1ae8e2f 100644 --- a/src/auction.rs +++ b/src/auction.rs @@ -31,6 +31,20 @@ pub struct AuctionChildState { pub royalty_amount: Option, } +/// The spends needed to buy an auction at its buy now price. See +/// [`AuctionExt::spend_buy_now_actions`]. +#[derive(Debug, Clone)] +pub struct BuyNowSpends { + /// The winning bid at the buy now price. The buyer must fund the reserve with + /// [`reserve_amount_for_bid`](AuctionInfo::reserve_amount_for_bid) of its amount, and assert its + /// announcement, the same as for any other bid. + pub bid: Bid, + /// The bid and end actions, which must be spent in this order, after any other actions. + pub action_spends: Vec, + /// The NFT sent to the buyer. + pub nft: Nft, +} + pub trait AuctionExt: Sized { fn spend_bid_action( &self, @@ -43,6 +57,19 @@ pub trait AuctionExt: Sized { /// [`unlock_nft`](AuctionExt::unlock_nft) in the same spend bundle. fn spend_end_action(&self, ctx: &mut SpendContext, nft: &Nft) -> Result; + /// Buys the auction at its buy now price for `puzzle_hash`, by placing a bid at that price and + /// ending the auction in the same spend. `nft` is the locked NFT, which is unlocked to the buyer + /// in the same spend bundle, so [`unlock_nft`](AuctionExt::unlock_nft) must not be called. Like + /// any other bid, it must be placed before the end time, or within the grace period if `grace` + /// is set. Returns an error if the auction can't be bought now. + fn spend_buy_now_actions( + &self, + ctx: &mut SpendContext, + puzzle_hash: Bytes32, + grace: bool, + nft: &Nft, + ) -> Result; + /// Cancels the auction before the first bid, sending the NFT back to the payout address. `nft` is /// the locked NFT, which must be unlocked with [`unlock_nft`](AuctionExt::unlock_nft) in the same /// spend bundle. A coin at the payout address must also output the conditions from @@ -56,9 +83,18 @@ pub trait AuctionExt: Sized { /// Spends the locked NFT to the winning bidder, or back to the payout address if there are no /// bids. This must be included in the same spend bundle as the end or cancel action, and `self` - /// must be the auction before it's ended or cancelled. + /// must be the auction before it's ended or cancelled, with no bids placed in the same spend. fn unlock_nft(&self, ctx: &mut SpendContext, nft: &Nft) -> Result; + /// Like [`unlock_nft`](AuctionExt::unlock_nft), but for the given winning bid, which must be the + /// winning bid when the end action is run. + fn unlock_nft_for_bid( + &self, + ctx: &mut SpendContext, + nft: &Nft, + winning_bid: Bid, + ) -> Result; + /// Runs the action puzzles to determine the next state and the reserve coin's conditions, exactly /// as the action layer and reserve finalizer will on chain. fn child_state( @@ -99,6 +135,29 @@ impl AuctionExt for Auction { Ok(Spend::new(puzzle, solution)) } + fn spend_buy_now_actions( + &self, + ctx: &mut SpendContext, + puzzle_hash: Bytes32, + grace: bool, + nft: &Nft, + ) -> Result { + let price = self.info.available_buy_now_price().ok_or_else(|| { + DriverError::Custom("the auction can't be bought at a buy now price".to_string()) + })?; + + let bid = Bid::new(price, puzzle_hash); + let bid_action = self.spend_bid_action(ctx, bid, grace)?; + let end_action = self.spend_end_action(ctx, nft)?; + let nft = self.unlock_nft_for_bid(ctx, nft, bid)?; + + Ok(BuyNowSpends { + bid, + action_spends: vec![bid_action, end_action], + nft, + }) + } + fn spend_cancel_action(&self, ctx: &mut SpendContext, nft: &Nft) -> Result { let puzzle = self.info.cancel_action(ctx)?; // Like the end action, the cancel action passes its solution to the unlocker @@ -116,11 +175,18 @@ impl AuctionExt for Auction { } fn unlock_nft(&self, ctx: &mut SpendContext, nft: &Nft) -> Result { + self.unlock_nft_for_bid(ctx, nft, self.info.state.winning_bid) + } + + fn unlock_nft_for_bid( + &self, + ctx: &mut SpendContext, + nft: &Nft, + winning_bid: Bid, + ) -> Result { let unlocker = self.info.nft_unlocker(ctx)?; - let unlocker_solution = ctx.alloc(&NftUnlockerSolution::new( - self.info.state.winning_bid, - nft.coin.amount, - ))?; + let unlocker_solution = + ctx.alloc(&NftUnlockerSolution::new(winning_bid, nft.coin.amount))?; let conditions = ctx.run(unlocker, unlocker_solution)?; let delegated_puzzle = ctx.alloc(&clvm_quote!(conditions))?; diff --git a/src/error.rs b/src/error.rs index ec2e0b7..192bd31 100644 --- a/src/error.rs +++ b/src/error.rs @@ -15,6 +15,15 @@ pub enum AuctionError { #[error("the {name} of {bps} bps exceeds 10,000 bps")] BpsTooHigh { name: &'static str, bps: u64 }, + #[error("the buy now price must be greater than 0")] + ZeroBuyNowPrice, + + #[error("the buy now price of {buy_now_price} is below the minimum bid of {minimum_bid}")] + BuyNowPriceBelowMinimumBid { + buy_now_price: u64, + minimum_bid: u64, + }, + #[error("puzzle hash {0} receives more than one payment when the auction ends")] DuplicatePaymentPuzzleHash(Bytes32), diff --git a/src/info.rs b/src/info.rs index a37130a..44ba92a 100644 --- a/src/info.rs +++ b/src/info.rs @@ -106,6 +106,14 @@ impl AuctionInfo { bid_amount.checked_add(premium)?.checked_add(royalty) } + /// The buy now price, if the auction can still be bought at it. That's only possible until it's + /// ended, and while the winning bid is below the buy now price. + pub fn available_buy_now_price(&self) -> Option { + self.settings + .buy_now_price + .filter(|&price| !self.state.ended && self.state.winning_bid.amount < price) + } + pub fn bid_action(&self, ctx: &mut SpendContext) -> Result { let bid_verifier = match self.settings.bid_verifier { BidVerifier::Flat { @@ -123,6 +131,7 @@ impl AuctionInfo { self.settings.timings, self.settings.payments.buyers_premium.bps, self.royalty_bps(), + self.settings.buy_now_price_arg(), )) } @@ -143,6 +152,7 @@ impl AuctionInfo { self.settings.timings, self.settings.payments.buyers_premium.bps, self.royalty_bps(), + self.settings.buy_now_price_arg(), ) .curry_tree_hash() .into() @@ -164,6 +174,7 @@ impl AuctionInfo { self.settings.timings, self.settings.payments, self.royalty_bps(), + self.settings.buy_now_price_arg(), SETTLEMENT_PAYMENT_HASH.into(), self.nft_coin_id, )) @@ -175,6 +186,7 @@ impl AuctionInfo { self.settings.timings, self.settings.payments, self.royalty_bps(), + self.settings.buy_now_price_arg(), SETTLEMENT_PAYMENT_HASH.into(), self.nft_coin_id, ) diff --git a/src/parser.rs b/src/parser.rs index d3b1ba5..87aed44 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -110,6 +110,23 @@ pub(crate) fn validate_auction(info: &AuctionInfo) -> Result<(), AuctionError> { return Err(AuctionError::ZeroBidIncrement); } + if let Some(buy_now_price) = info.settings.buy_now_price { + // The buy now price is curried in as 0 when there isn't one, and the memo can't tell + // `Some(0)` apart from `None` + if buy_now_price == 0 { + return Err(AuctionError::ZeroBuyNowPrice); + } + + // A bid at the buy now price skips the bid verifier, so a lower price would undercut the + // minimum bid. It would also be the only bid that could ever be placed. + if buy_now_price < minimum_bid { + return Err(AuctionError::BuyNowPriceBelowMinimumBid { + buy_now_price, + minimum_bid, + }); + } + } + let payments = info.settings.payments; for (name, bps) in [ diff --git a/src/types.rs b/src/types.rs index 7ea5232..bcbb73e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -63,6 +63,16 @@ pub struct AuctionSettings { pub bid_verifier: BidVerifier, pub timings: Timings, pub payments: Payments, + /// The price at which a bid wins the auction outright and ends it right away, if any. No bid can + /// exceed it. It must be at least the minimum bid, and can't be `Some(0)`. + pub buy_now_price: Option, +} + +impl AuctionSettings { + /// The buy now price as it's curried into the bid and end actions, where 0 means there isn't one. + pub fn buy_now_price_arg(&self) -> u64 { + self.buy_now_price.unwrap_or(0) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ToClvm, FromClvm)] diff --git a/tests/buy_now.rs b/tests/buy_now.rs new file mode 100644 index 0000000..8d288b2 --- /dev/null +++ b/tests/buy_now.rs @@ -0,0 +1,324 @@ +mod common; + +use anyhow::{Result, anyhow}; +use auction::*; +use chia_wallet_sdk::prelude::*; +use common::*; + +const BUY_NOW_PRICE: u64 = 1_000; + +/// The error for a spend bundle where the auction's puzzle raises during consensus validation. +const PUZZLE_RAISED: &str = "GeneratorRuntimeError"; + +fn with_buy_now(buy_now_price: u64) -> Config { + Config { + buy_now_price: Some(buy_now_price), + ..Config::default() + } +} + +/// Places a bid without running it in the driver first, so that it's only checked on chain. The +/// bidder funds the reserve amount for the bid. +fn unchecked_bid(h: &mut Harness, amount: u64) -> Result<()> { + let reserve_amount = h + .auction + .info + .reserve_amount_for_bid(amount) + .ok_or(anyhow!("reserve amount overflow"))?; + let key = h.sim.bls(reserve_amount); + StandardLayer::new(key.pk).spend(&mut h.ctx, key.coin, Conditions::new())?; + let bid = h + .auction + .spend_bid_action(&mut h.ctx, Bid::new(amount, key.puzzle_hash), false)?; + h.spend_unchecked(vec![bid], reserve_amount, &[key.sk]) +} + +#[test] +fn buy_now_ends_the_auction_right_away() -> Result<()> { + for reserve in [ + ReserveKind::Xch, + ReserveKind::Cat, + ReserveKind::RevocableCat, + ] { + let mut h = Harness::new(Config { + reserve, + ..with_buy_now(BUY_NOW_PRICE) + })?; + + assert_eq!( + h.auction.info.available_buy_now_price(), + Some(BUY_NOW_PRICE) + ); + + // Well before the end time + h.set_time(10)?; + let reserve_before = h.auction.info.reserve; + let (buyer, nft) = h.buy_now(false)?; + + assert_eq!(buyer.bid.amount, BUY_NOW_PRICE); + assert_eq!( + buyer.reserve_amount, + BUY_NOW_PRICE + fee(BUY_NOW_PRICE, 300) + fee(BUY_NOW_PRICE, 500) + ); + + h.assert_unspent(nft.coin); + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + assert_eq!(nft.info.current_owner, None); + + assert!(h.auction.info.state.ended); + assert_eq!(h.auction.info.state.winning_bid, buyer.bid); + assert_eq!(h.auction.info.available_buy_now_price(), None); + + // The bid and end are in the same spend, so the reserve pays out the buyer's funds directly + h.assert_paid_out(reserve_before, BUY_NOW_PRICE); + + // A bought auction can't be bid on, ended, cancelled, or bought again + assert_fails_with(h.bid(BUY_NOW_PRICE), "raise"); + assert_fails_with(h.end(), "raise"); + assert_fails_with(h.cancel(), "raise"); + assert_fails_with(h.buy_now(false), "can't be bought now"); + } + + Ok(()) +} + +#[test] +fn buy_now_refunds_the_winning_bid() -> Result<()> { + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + + let bidder = h.bid(500)?; + assert_eq!( + h.auction.info.available_buy_now_price(), + Some(BUY_NOW_PRICE) + ); + + let outbid_reserve = h.auction.info.reserve; + let (buyer, nft) = h.buy_now(false)?; + + h.assert_unspent(h.reserve_output( + outbid_reserve, + bidder.bid.puzzle_hash, + bidder.reserve_amount, + )); + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + h.assert_paid_out(outbid_reserve, BUY_NOW_PRICE); + + Ok(()) +} + +#[test] +fn buy_now_after_a_pending_bid_in_the_same_spend() -> Result<()> { + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + + let reserve_before = h.auction.info.reserve; + let (bidders, nft) = h.bids_then_buy_now(&[(100, false), (200, false)], false)?; + let buyer = bidders[2]; + + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + assert!(h.auction.info.state.ended); + assert_eq!(h.auction.info.state.winning_bid, buyer.bid); + + // Every action in the spend is paid out by the same reserve coin, including the refunds of the + // bids that were placed before the buy now + for bidder in &bidders[..2] { + h.assert_unspent(h.reserve_output( + reserve_before, + bidder.bid.puzzle_hash, + bidder.reserve_amount, + )); + } + h.assert_paid_out(reserve_before, BUY_NOW_PRICE); + + Ok(()) +} + +#[test] +fn bid_at_buy_now_price_skips_the_bid_verifier() -> Result<()> { + // The next bid after 1,000 must be at least 1,100, so the buy now price is only reachable + // because it skips the verifier + for buy_now_price in [1_050, 100] { + let mut h = Harness::new(with_buy_now(buy_now_price))?; + + if buy_now_price > 1_000 { + h.bid(1_000)?; + assert_fails_with(h.bid(1_050 - 1), "raise"); + } + + let (buyer, _) = h.buy_now(false)?; + assert_eq!(buyer.bid.amount, buy_now_price); + } + + Ok(()) +} + +#[test] +fn bids_cannot_exceed_buy_now_price() -> Result<()> { + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + + assert_fails_with(h.bid(BUY_NOW_PRICE + 1), "raise"); + assert_fails_with(h.bid(BUY_NOW_PRICE * 10), "raise"); + + // The checks are also enforced on chain, not just by the driver + let result = unchecked_bid(&mut h, BUY_NOW_PRICE + 1); + assert_fails_with(result, PUZZLE_RAISED); + unchecked_bid(&mut h, BUY_NOW_PRICE)?; + + // A bid at the buy now price can never be outbid + assert_fails_with(h.bid(BUY_NOW_PRICE), "raise"); + assert_fails_with(h.bid(BUY_NOW_PRICE + 100), "raise"); + + Ok(()) +} + +#[test] +fn bid_at_buy_now_price_can_be_ended_by_anyone() -> Result<()> { + // A wallet should always buy with the bid and end in the same spend, but if a bid at the buy now + // price is placed on its own, the auction can still be ended right away + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + + h.set_time(10)?; + let winner = h.bid(BUY_NOW_PRICE)?; + assert_eq!(h.auction.info.available_buy_now_price(), None); + + let settled_reserve = h.auction.info.reserve; + let nft = h.end()?; + + assert_eq!(nft.info.p2_puzzle_hash, winner.bid.puzzle_hash); + h.assert_settled(settled_reserve, BUY_NOW_PRICE); + + Ok(()) +} + +#[test] +fn end_waits_for_the_end_time_below_the_buy_now_price() -> Result<()> { + for bid in [None, Some(BUY_NOW_PRICE - 1)] { + let mut h = Harness::new(Config { + timings: Timings::new(END_TIME, 100), + ..with_buy_now(BUY_NOW_PRICE) + })?; + + if let Some(amount) = bid { + h.set_time(END_TIME - 50)?; + h.bid(amount)?; + } + + h.set_time(END_TIME - 1)?; + assert_fails_with(h.end(), "AssertSecondsAbsoluteFailed"); + + // The grace period still applies after a bid below the buy now price + if bid.is_some() { + h.set_time(END_TIME)?; + assert_fails_with(h.end(), "AssertSecondsRelativeFailed"); + } + + h.set_time(END_TIME + 100)?; + let _ = h.end()?; + } + + Ok(()) +} + +#[test] +fn end_waits_for_the_end_time_without_a_buy_now_price() -> Result<()> { + // With no buy now price, the price is curried in as 0, which must not match an auction with no + // bids + let mut h = Harness::new(Config::default())?; + assert_eq!(h.auction.info.available_buy_now_price(), None); + + h.set_time(END_TIME - 1)?; + assert_fails_with(h.end(), "AssertSecondsAbsoluteFailed"); + + let nft = h.nft; + let result = h + .auction + .spend_buy_now_actions(&mut h.ctx, h.seller.puzzle_hash, false, &nft); + assert!(result.is_err()); + h.ctx.take(); + + h.set_time(END_TIME)?; + let _ = h.end()?; + + Ok(()) +} + +#[test] +fn buy_now_follows_bid_timing() -> Result<()> { + // Without a grace period, the auction can't be bought after the end time + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + h.set_time(END_TIME)?; + assert_fails_with(h.buy_now(false), "AssertBeforeSecondsAbsoluteFailed"); + assert_fails_with(h.buy_now(true), "AssertBeforeSecondsAbsoluteFailed"); + + // With a grace period, it can be bought within the grace period of the last bid + let mut h = Harness::new(Config { + timings: Timings::new(END_TIME, 100), + ..with_buy_now(BUY_NOW_PRICE) + })?; + h.set_time(950)?; + h.bid(100)?; + + h.set_time(1_020)?; + assert_fails_with(h.buy_now(false), "AssertBeforeSecondsAbsoluteFailed"); + let (buyer, nft) = h.buy_now(true)?; + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + assert!(h.auction.info.state.ended); + + Ok(()) +} + +#[test] +fn seller_can_cancel_before_a_buy_now() -> Result<()> { + let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + + let nft = h.cancel()?; + assert_eq!(nft.info.p2_puzzle_hash, h.seller.puzzle_hash); + assert_eq!(h.auction.info.available_buy_now_price(), None); + assert_fails_with(h.buy_now(false), "can't be bought now"); + + Ok(()) +} + +#[test] +fn rejects_invalid_buy_now_prices() { + for (buy_now_price, expected) in [(0, "greater than 0"), (99, "below the minimum bid")] { + match Harness::new(with_buy_now(buy_now_price)) { + Ok(_) => panic!("expected a buy now price of {buy_now_price} to be rejected"), + Err(error) => { + let error = error + .downcast::() + .expect("expected an auction error"); + assert!( + matches!( + error, + AuctionError::ZeroBuyNowPrice + | AuctionError::BuyNowPriceBelowMinimumBid { .. } + ), + "{error}" + ); + assert!(error.to_string().contains(expected), "{error}"); + } + } + } +} + +#[test] +fn buy_now_price_round_trips_through_the_memo() -> Result<()> { + // The harness parses the launcher spend and compares it to the launched auction + let h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + assert_eq!( + h.auction.info.memo().settings.buy_now_price, + Some(BUY_NOW_PRICE) + ); + + // The buy now price is curried into the auction, so the same settings without it are a + // different auction + let mut settings = h.auction.info.settings; + settings.buy_now_price = None; + let info = AuctionInfo { + settings, + ..h.auction.info + }; + assert_ne!(info.inner_puzzle_hash(), h.auction.info.inner_puzzle_hash()); + + Ok(()) +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 5ad316d..114773d 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -51,6 +51,7 @@ pub struct Config { pub royalty_bps: u16, pub reserve: ReserveKind, pub did_owner: bool, + pub buy_now_price: Option, } impl Default for Config { @@ -66,6 +67,7 @@ impl Default for Config { royalty_bps: 500, reserve: ReserveKind::Xch, did_owner: false, + buy_now_price: None, } } } @@ -80,6 +82,7 @@ impl Config { commission: BpsPayment::new(self.commission_bps, COMMISSION_PUZZLE_HASH), payout_puzzle_hash, }, + buy_now_price: self.buy_now_price, } } } @@ -90,6 +93,15 @@ pub struct Bidder { pub reserve_amount: u64, } +/// The spends of the bidders in a single spend of the auction. +#[derive(Default)] +struct BidSpend { + actions: Vec, + cat_spends: Vec, + keys: Vec, + bidders: Vec, +} + /// An auction for a freshly minted NFT, launched and confirmed in a simulator. pub struct Harness { pub sim: Simulator, @@ -292,54 +304,133 @@ impl Harness { } fn try_bids(&mut self, bids: &[(u64, bool)]) -> Result> { - let mut bidders = Vec::new(); - let mut actions = Vec::new(); - let mut cat_spends = Vec::new(); - let mut keys = Vec::new(); + let mut spend = BidSpend::default(); for &(amount, grace) in bids { - let reserve_amount = self - .auction - .info - .reserve_amount_for_bid(amount) - .ok_or(anyhow!("reserve amount overflow"))?; - - let key = if self.bank.is_some() { - self.sim.bls(0) - } else { - self.sim.bls(reserve_amount) - }; + let key = self.bidder_key(amount)?; + let bid = Bid::new(amount, key.puzzle_hash); + spend + .actions + .push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); + self.fund_bid(&mut spend, key, bid)?; + } + + self.finish_bids(spend) + } + + /// Buys the auction at its buy now price, returning the buyer and the NFT sent to them. + pub fn buy_now(&mut self, grace: bool) -> Result<(Bidder, Nft)> { + let (bidders, nft) = self.bids_then_buy_now(&[], grace)?; + Ok((bidders[0], nft)) + } + + /// Like [`Harness::buy_now`], but first places `bids` in the same spend of the auction, which is + /// how a buyer would buy an auction with a pending bid. The buyer is the last bidder returned. + pub fn bids_then_buy_now( + &mut self, + bids: &[(u64, bool)], + grace: bool, + ) -> Result<(Vec, Nft)> { + let result = self.try_bids_then_buy_now(bids, grace); + if result.is_err() { + self.ctx.take(); + } + result + } + fn try_bids_then_buy_now( + &mut self, + bids: &[(u64, bool)], + grace: bool, + ) -> Result<(Vec, Nft)> { + let mut spend = BidSpend::default(); + + for &(amount, grace) in bids { + let key = self.bidder_key(amount)?; let bid = Bid::new(amount, key.puzzle_hash); - actions.push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); - - let conditions = Conditions::new().assert_coin_announcement(announcement_id( - self.auction.coin.coin_id(), - bid.tree_hash(), - )); - let p2 = StandardLayer::new(key.pk); - - if self.bank.is_some() { - let cat = self.fund_cat(key.puzzle_hash, reserve_amount)?; - let spend = p2.spend_with_conditions(&mut self.ctx, conditions)?; - cat_spends.push(CatSpend::new(cat, spend)); - } else { - p2.spend(&mut self.ctx, key.coin, conditions)?; - } + spend + .actions + .push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); + self.fund_bid(&mut spend, key, bid)?; + } + + let price = self + .auction + .info + .available_buy_now_price() + .ok_or(anyhow!("the auction can't be bought now"))?; + let key = self.bidder_key(price)?; + let puzzle_hash = key.puzzle_hash; + + // Funding a CAT bid confirms a spend of the bank, which would also confirm any spends + // already in the context, so the buyer must be funded before the NFT is unlocked + self.fund_bid(&mut spend, key, Bid::new(price, puzzle_hash))?; + + let buy_now = + self.auction + .spend_buy_now_actions(&mut self.ctx, puzzle_hash, grace, &self.nft)?; + assert_eq!(buy_now.bid, Bid::new(price, puzzle_hash)); + spend.actions.extend(buy_now.action_spends); + + let bidders = self.finish_bids(spend)?; + self.nft = buy_now.nft; + Ok((bidders, buy_now.nft)) + } - keys.push(key.sk.clone()); - bidders.push(Bidder { - bid, - reserve_amount, - }); + /// A new key for a bidder, with a coin that holds the reserve amount for a bid of `amount` if the + /// reserve is XCH. CAT bidders are funded from the bank instead. + fn bidder_key(&mut self, amount: u64) -> Result { + if self.bank.is_some() { + return Ok(self.sim.bls(0)); } - let auction = self.auction.spend(&mut self.ctx, actions, cat_spends)?; + let reserve_amount = self + .auction + .info + .reserve_amount_for_bid(amount) + .ok_or(anyhow!("reserve amount overflow"))?; + Ok(self.sim.bls(reserve_amount)) + } + + /// Funds exactly the reserve amount for `bid` from `key`, asserting the bid's announcement so the + /// funds can't be reused. + fn fund_bid(&mut self, spend: &mut BidSpend, key: BlsPairWithCoin, bid: Bid) -> Result<()> { + let reserve_amount = self + .auction + .info + .reserve_amount_for_bid(bid.amount) + .ok_or(anyhow!("reserve amount overflow"))?; + + let conditions = Conditions::new().assert_coin_announcement(announcement_id( + self.auction.coin.coin_id(), + bid.tree_hash(), + )); + let p2 = StandardLayer::new(key.pk); + + if self.bank.is_some() { + let cat = self.fund_cat(key.puzzle_hash, reserve_amount)?; + let cat_spend = p2.spend_with_conditions(&mut self.ctx, conditions)?; + spend.cat_spends.push(CatSpend::new(cat, cat_spend)); + } else { + p2.spend(&mut self.ctx, key.coin, conditions)?; + } + + spend.keys.push(key.sk); + spend.bidders.push(Bidder { + bid, + reserve_amount, + }); + Ok(()) + } + + fn finish_bids(&mut self, spend: BidSpend) -> Result> { + let auction = self + .auction + .spend(&mut self.ctx, spend.actions, spend.cat_spends)?; let coin_spends = self.ctx.take(); - self.sim.spend_coins(coin_spends.clone(), &keys)?; + self.sim.spend_coins(coin_spends.clone(), &spend.keys)?; self.confirmed(&coin_spends, auction)?; - - Ok(bidders) + Ok(spend.bidders) } /// Ends the auction and unlocks the NFT, returning the NFT sent to the winning bidder. @@ -612,13 +703,21 @@ impl Harness { /// Asserts that the reserve coin `reserve` paid out a winning bid of `amount` to the seller and /// every fee recipient, and created an empty reserve for the ended auction. pub fn assert_settled(&self, reserve: AuctionReserve, amount: u64) { + let premium = fee(amount, self.config.buyers_premium_bps); + let royalty = fee(amount, self.config.royalty_bps.into()); + assert_eq!(reserve.coin().amount, amount + premium + royalty); + self.assert_paid_out(reserve, amount); + } + + /// Like [`Harness::assert_settled`], but doesn't check the reserve's amount. When the winning bid + /// is placed in the same spend as the end, the reserve pays out funds that the bidder added to + /// the spend bundle, rather than funds it already held. + pub fn assert_paid_out(&self, reserve: AuctionReserve, amount: u64) { let premium = fee(amount, self.config.buyers_premium_bps); let commission = fee(amount, self.config.commission_bps); let royalty = fee(amount, self.config.royalty_bps.into()); let payout = amount - commission; - assert_eq!(reserve.coin().amount, amount + premium + royalty); - for (puzzle_hash, payment) in [ (PREMIUM_PUZZLE_HASH, premium), (COMMISSION_PUZZLE_HASH, commission), diff --git a/tests/fee_math.rs b/tests/fee_math.rs index 732bc7f..7bf0b1b 100644 --- a/tests/fee_math.rs +++ b/tests/fee_math.rs @@ -28,6 +28,7 @@ fn auction(premium_bps: u64, commission_bps: u64, royalty_bps: u16) -> Auction { commission: BpsPayment::new(commission_bps, COMMISSION_PUZZLE_HASH), payout_puzzle_hash: PAYOUT_PUZZLE_HASH, }, + buy_now_price: None, }; let reserve = Coin::new( Bytes32::new([6; 32]), From a5ae0649a793687a2485a45d5759310aa7d41f43 Mon Sep 17 00:00:00 2001 From: Rigidity Date: Wed, 18 Nov 2026 12:46:37 -0500 Subject: [PATCH 2/2] Address review findings in buy now - Return AuctionError::BuyNowUnavailable from spend_buy_now_actions instead of a custom driver error - Make the NFT unlock for a same-spend winning bid private - Build the bid and end action curry args in one place each - Cover CAT reserves for refunds in a buy now spend, both bid verifiers, and the minimum bid boundary - Move buy now validation tests to tests/validation.rs and add a parsing case - Share the harness's bid loop --- src/auction.rs | 79 ++++++++++---------- src/error.rs | 5 ++ src/info.rs | 39 ++++------ src/types.rs | 2 +- tests/buy_now.rs | 174 ++++++++++++++++++++++++-------------------- tests/common/mod.rs | 36 ++++----- tests/parsing.rs | 8 ++ tests/validation.rs | 40 ++++++++++ 8 files changed, 221 insertions(+), 162 deletions(-) diff --git a/src/auction.rs b/src/auction.rs index 1ae8e2f..5575b32 100644 --- a/src/auction.rs +++ b/src/auction.rs @@ -14,8 +14,9 @@ use chia_wallet_sdk::{ }; use crate::{ - AUCTION_SINGLETON_AMOUNT, AuctionInfo, AuctionReserve, AuctionState, Bid, BidActionSolution, - CANCEL_MESSAGE, CANCEL_MESSAGE_MODE, NftUnlockerSolution, spend_auction_lock, + AUCTION_SINGLETON_AMOUNT, AuctionError, AuctionInfo, AuctionReserve, AuctionState, Bid, + BidActionSolution, CANCEL_MESSAGE, CANCEL_MESSAGE_MODE, NftUnlockerSolution, + spend_auction_lock, }; pub type Auction = Singleton; @@ -61,14 +62,15 @@ pub trait AuctionExt: Sized { /// ending the auction in the same spend. `nft` is the locked NFT, which is unlocked to the buyer /// in the same spend bundle, so [`unlock_nft`](AuctionExt::unlock_nft) must not be called. Like /// any other bid, it must be placed before the end time, or within the grace period if `grace` - /// is set. Returns an error if the auction can't be bought now. + /// is set. Returns [`AuctionError::BuyNowUnavailable`] if the auction can't be bought now (see + /// [`available_buy_now_price`](AuctionInfo::available_buy_now_price)). fn spend_buy_now_actions( &self, ctx: &mut SpendContext, puzzle_hash: Bytes32, grace: bool, nft: &Nft, - ) -> Result; + ) -> Result; /// Cancels the auction before the first bid, sending the NFT back to the payout address. `nft` is /// the locked NFT, which must be unlocked with [`unlock_nft`](AuctionExt::unlock_nft) in the same @@ -86,15 +88,6 @@ pub trait AuctionExt: Sized { /// must be the auction before it's ended or cancelled, with no bids placed in the same spend. fn unlock_nft(&self, ctx: &mut SpendContext, nft: &Nft) -> Result; - /// Like [`unlock_nft`](AuctionExt::unlock_nft), but for the given winning bid, which must be the - /// winning bid when the end action is run. - fn unlock_nft_for_bid( - &self, - ctx: &mut SpendContext, - nft: &Nft, - winning_bid: Bid, - ) -> Result; - /// Runs the action puzzles to determine the next state and the reserve coin's conditions, exactly /// as the action layer and reserve finalizer will on chain. fn child_state( @@ -141,15 +134,18 @@ impl AuctionExt for Auction { puzzle_hash: Bytes32, grace: bool, nft: &Nft, - ) -> Result { - let price = self.info.available_buy_now_price().ok_or_else(|| { - DriverError::Custom("the auction can't be bought at a buy now price".to_string()) - })?; + ) -> Result { + let price = self + .info + .available_buy_now_price() + .ok_or(AuctionError::BuyNowUnavailable)?; let bid = Bid::new(price, puzzle_hash); let bid_action = self.spend_bid_action(ctx, bid, grace)?; let end_action = self.spend_end_action(ctx, nft)?; - let nft = self.unlock_nft_for_bid(ctx, nft, bid)?; + // The end action runs after the bid, so the NFT is unlocked to the buyer rather than to the + // auction's current winning bid + let nft = unlock_nft_to(self, ctx, nft, bid)?; Ok(BuyNowSpends { bid, @@ -175,29 +171,7 @@ impl AuctionExt for Auction { } fn unlock_nft(&self, ctx: &mut SpendContext, nft: &Nft) -> Result { - self.unlock_nft_for_bid(ctx, nft, self.info.state.winning_bid) - } - - fn unlock_nft_for_bid( - &self, - ctx: &mut SpendContext, - nft: &Nft, - winning_bid: Bid, - ) -> Result { - let unlocker = self.info.nft_unlocker(ctx)?; - let unlocker_solution = - ctx.alloc(&NftUnlockerSolution::new(winning_bid, nft.coin.amount))?; - let conditions = ctx.run(unlocker, unlocker_solution)?; - let delegated_puzzle = ctx.alloc(&clvm_quote!(conditions))?; - - let spend = spend_auction_lock( - ctx, - self.info.launcher_id, - self.info.inner_puzzle_hash(), - Spend::new(delegated_puzzle, NodePtr::NIL), - )?; - - nft.spend(ctx, spend) + unlock_nft_to(self, ctx, nft, self.info.state.winning_bid) } fn child_state( @@ -403,6 +377,29 @@ impl AuctionExt for Auction { } } +/// Spends the locked NFT to `winning_bid`, which must be the winning bid when the end or cancel +/// action is run. +fn unlock_nft_to( + auction: &Auction, + ctx: &mut SpendContext, + nft: &Nft, + winning_bid: Bid, +) -> Result { + let unlocker = auction.info.nft_unlocker(ctx)?; + let unlocker_solution = ctx.alloc(&NftUnlockerSolution::new(winning_bid, nft.coin.amount))?; + let conditions = ctx.run(unlocker, unlocker_solution)?; + let delegated_puzzle = ctx.alloc(&clvm_quote!(conditions))?; + + let spend = spend_auction_lock( + ctx, + auction.info.launcher_id, + auction.info.inner_puzzle_hash(), + Spend::new(delegated_puzzle, NodePtr::NIL), + )?; + + nft.spend(ctx, spend) +} + fn child_auction(auction: &Auction, spent_reserve: AuctionReserve, state: AuctionState) -> Auction { auction.child_with( AuctionInfo { diff --git a/src/error.rs b/src/error.rs index 192bd31..cac14c7 100644 --- a/src/error.rs +++ b/src/error.rs @@ -24,6 +24,11 @@ pub enum AuctionError { minimum_bid: u64, }, + #[error( + "the auction can't be bought now, since it has no buy now price, has ended, or has a bid at it" + )] + BuyNowUnavailable, + #[error("puzzle hash {0} receives more than one payment when the auction ends")] DuplicatePaymentPuzzleHash(Bytes32), diff --git a/src/info.rs b/src/info.rs index 44ba92a..b328776 100644 --- a/src/info.rs +++ b/src/info.rs @@ -126,13 +126,7 @@ impl AuctionInfo { } => ctx.curry(PercentBidVerifierArgs::new(minimum_bid, bid_increment_bps))?, }; - ctx.curry(BidActionArgs::new( - bid_verifier, - self.settings.timings, - self.settings.payments.buyers_premium.bps, - self.royalty_bps(), - self.settings.buy_now_price_arg(), - )) + ctx.curry(self.bid_action_args(bid_verifier)) } pub fn bid_action_hash(&self) -> Bytes32 { @@ -147,15 +141,19 @@ impl AuctionInfo { } => PercentBidVerifierArgs::new(minimum_bid, bid_increment_bps).curry_tree_hash(), }; + self.bid_action_args(bid_verifier_hash) + .curry_tree_hash() + .into() + } + + fn bid_action_args(&self, bid_verifier: V) -> BidActionArgs { BidActionArgs::new( - bid_verifier_hash, + bid_verifier, self.settings.timings, self.settings.payments.buyers_premium.bps, self.royalty_bps(), self.settings.buy_now_price_arg(), ) - .curry_tree_hash() - .into() } fn nft_unlocker_args(&self) -> NftUnlockerArgs { @@ -168,21 +166,18 @@ impl AuctionInfo { pub fn end_action(&self, ctx: &mut SpendContext) -> Result { let unlocker = self.nft_unlocker(ctx)?; - - ctx.curry(EndActionArgs::new( - unlocker, - self.settings.timings, - self.settings.payments, - self.royalty_bps(), - self.settings.buy_now_price_arg(), - SETTLEMENT_PAYMENT_HASH.into(), - self.nft_coin_id, - )) + ctx.curry(self.end_action_args(unlocker)) } pub fn end_action_hash(&self) -> Bytes32 { + self.end_action_args(self.nft_unlocker_args().curry_tree_hash()) + .curry_tree_hash() + .into() + } + + fn end_action_args(&self, unlocker: U) -> EndActionArgs { EndActionArgs::new( - self.nft_unlocker_args().curry_tree_hash(), + unlocker, self.settings.timings, self.settings.payments, self.royalty_bps(), @@ -190,8 +185,6 @@ impl AuctionInfo { SETTLEMENT_PAYMENT_HASH.into(), self.nft_coin_id, ) - .curry_tree_hash() - .into() } /// Cancels the auction before the first bid, which must be authorized by the payout puzzle. See diff --git a/src/types.rs b/src/types.rs index bcbb73e..1f472c9 100644 --- a/src/types.rs +++ b/src/types.rs @@ -70,7 +70,7 @@ pub struct AuctionSettings { impl AuctionSettings { /// The buy now price as it's curried into the bid and end actions, where 0 means there isn't one. - pub fn buy_now_price_arg(&self) -> u64 { + pub(crate) fn buy_now_price_arg(&self) -> u64 { self.buy_now_price.unwrap_or(0) } } diff --git a/tests/buy_now.rs b/tests/buy_now.rs index 8d288b2..1ab0077 100644 --- a/tests/buy_now.rs +++ b/tests/buy_now.rs @@ -7,6 +7,12 @@ use common::*; const BUY_NOW_PRICE: u64 = 1_000; +const ALL_RESERVES: [ReserveKind; 3] = [ + ReserveKind::Xch, + ReserveKind::Cat, + ReserveKind::RevocableCat, +]; + /// The error for a spend bundle where the auction's puzzle raises during consensus validation. const PUZZLE_RAISED: &str = "GeneratorRuntimeError"; @@ -33,13 +39,22 @@ fn unchecked_bid(h: &mut Harness, amount: u64) -> Result<()> { h.spend_unchecked(vec![bid], reserve_amount, &[key.sk]) } +/// Asserts that the driver refuses to buy the auction now. +fn assert_buy_now_unavailable(h: &mut Harness) { + let nft = h.nft; + let result = h + .auction + .spend_buy_now_actions(&mut h.ctx, h.seller.puzzle_hash, false, &nft); + assert!( + matches!(result, Err(AuctionError::BuyNowUnavailable)), + "{result:?}" + ); + h.ctx.take(); +} + #[test] fn buy_now_ends_the_auction_right_away() -> Result<()> { - for reserve in [ - ReserveKind::Xch, - ReserveKind::Cat, - ReserveKind::RevocableCat, - ] { + for reserve in ALL_RESERVES { let mut h = Harness::new(Config { reserve, ..with_buy_now(BUY_NOW_PRICE) @@ -76,7 +91,7 @@ fn buy_now_ends_the_auction_right_away() -> Result<()> { assert_fails_with(h.bid(BUY_NOW_PRICE), "raise"); assert_fails_with(h.end(), "raise"); assert_fails_with(h.cancel(), "raise"); - assert_fails_with(h.buy_now(false), "can't be bought now"); + assert_buy_now_unavailable(&mut h); } Ok(()) @@ -84,73 +99,105 @@ fn buy_now_ends_the_auction_right_away() -> Result<()> { #[test] fn buy_now_refunds_the_winning_bid() -> Result<()> { - let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + for reserve in ALL_RESERVES { + let mut h = Harness::new(Config { + reserve, + ..with_buy_now(BUY_NOW_PRICE) + })?; - let bidder = h.bid(500)?; - assert_eq!( - h.auction.info.available_buy_now_price(), - Some(BUY_NOW_PRICE) - ); + let bidder = h.bid(500)?; + assert_eq!( + h.auction.info.available_buy_now_price(), + Some(BUY_NOW_PRICE) + ); - let outbid_reserve = h.auction.info.reserve; - let (buyer, nft) = h.buy_now(false)?; + let outbid_reserve = h.auction.info.reserve; + let (buyer, nft) = h.buy_now(false)?; - h.assert_unspent(h.reserve_output( - outbid_reserve, - bidder.bid.puzzle_hash, - bidder.reserve_amount, - )); - assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); - h.assert_paid_out(outbid_reserve, BUY_NOW_PRICE); + h.assert_unspent(h.reserve_output( + outbid_reserve, + bidder.bid.puzzle_hash, + bidder.reserve_amount, + )); + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + h.assert_paid_out(outbid_reserve, BUY_NOW_PRICE); + } Ok(()) } #[test] fn buy_now_after_a_pending_bid_in_the_same_spend() -> Result<()> { - let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; + for reserve in ALL_RESERVES { + let mut h = Harness::new(Config { + reserve, + ..with_buy_now(BUY_NOW_PRICE) + })?; - let reserve_before = h.auction.info.reserve; - let (bidders, nft) = h.bids_then_buy_now(&[(100, false), (200, false)], false)?; - let buyer = bidders[2]; + let reserve_before = h.auction.info.reserve; + let (bidders, nft) = h.bids_then_buy_now(&[(100, false), (200, false)], false)?; + let buyer = bidders[2]; - assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); - assert!(h.auction.info.state.ended); - assert_eq!(h.auction.info.state.winning_bid, buyer.bid); + assert_eq!(nft.info.p2_puzzle_hash, buyer.bid.puzzle_hash); + assert!(h.auction.info.state.ended); + assert_eq!(h.auction.info.state.winning_bid, buyer.bid); - // Every action in the spend is paid out by the same reserve coin, including the refunds of the - // bids that were placed before the buy now - for bidder in &bidders[..2] { - h.assert_unspent(h.reserve_output( - reserve_before, - bidder.bid.puzzle_hash, - bidder.reserve_amount, - )); + // Every action in the spend is paid out by the same reserve coin, including the refunds of + // the bids that were placed before the buy now + for bidder in &bidders[..2] { + h.assert_unspent(h.reserve_output( + reserve_before, + bidder.bid.puzzle_hash, + bidder.reserve_amount, + )); + } + h.assert_paid_out(reserve_before, BUY_NOW_PRICE); } - h.assert_paid_out(reserve_before, BUY_NOW_PRICE); Ok(()) } #[test] fn bid_at_buy_now_price_skips_the_bid_verifier() -> Result<()> { - // The next bid after 1,000 must be at least 1,100, so the buy now price is only reachable - // because it skips the verifier - for buy_now_price in [1_050, 100] { - let mut h = Harness::new(with_buy_now(buy_now_price))?; - - if buy_now_price > 1_000 { - h.bid(1_000)?; - assert_fails_with(h.bid(1_050 - 1), "raise"); - } + // With either verifier, the next bid after 1,000 must be at least 1,100, so the buy now price of + // 1,050 is only reachable because it skips the verifier + for bid_verifier in [ + BidVerifier::Flat { + minimum_bid: 100, + bid_increment: 100, + }, + BidVerifier::Percent { + minimum_bid: 100, + bid_increment_bps: 1_000, + }, + ] { + let mut h = Harness::new(Config { + bid_verifier, + ..with_buy_now(1_050) + })?; + + h.bid(1_000)?; + assert_fails_with(h.bid(1_049), "raise"); let (buyer, _) = h.buy_now(false)?; - assert_eq!(buyer.bid.amount, buy_now_price); + assert_eq!(buyer.bid.amount, 1_050); } Ok(()) } +#[test] +fn buy_now_price_can_equal_the_minimum_bid() -> Result<()> { + let mut h = Harness::new(with_buy_now(100))?; + + // The only bid that can be placed is the buy now + assert_fails_with(h.bid(101), "raise"); + let (buyer, _) = h.buy_now(false)?; + assert_eq!(buyer.bid.amount, 100); + + Ok(()) +} + #[test] fn bids_cannot_exceed_buy_now_price() -> Result<()> { let mut h = Harness::new(with_buy_now(BUY_NOW_PRICE))?; @@ -179,6 +226,7 @@ fn bid_at_buy_now_price_can_be_ended_by_anyone() -> Result<()> { h.set_time(10)?; let winner = h.bid(BUY_NOW_PRICE)?; assert_eq!(h.auction.info.available_buy_now_price(), None); + assert_buy_now_unavailable(&mut h); let settled_reserve = h.auction.info.reserve; let nft = h.end()?; @@ -228,12 +276,7 @@ fn end_waits_for_the_end_time_without_a_buy_now_price() -> Result<()> { h.set_time(END_TIME - 1)?; assert_fails_with(h.end(), "AssertSecondsAbsoluteFailed"); - let nft = h.nft; - let result = h - .auction - .spend_buy_now_actions(&mut h.ctx, h.seller.puzzle_hash, false, &nft); - assert!(result.is_err()); - h.ctx.take(); + assert_buy_now_unavailable(&mut h); h.set_time(END_TIME)?; let _ = h.end()?; @@ -273,34 +316,11 @@ fn seller_can_cancel_before_a_buy_now() -> Result<()> { let nft = h.cancel()?; assert_eq!(nft.info.p2_puzzle_hash, h.seller.puzzle_hash); assert_eq!(h.auction.info.available_buy_now_price(), None); - assert_fails_with(h.buy_now(false), "can't be bought now"); + assert_buy_now_unavailable(&mut h); Ok(()) } -#[test] -fn rejects_invalid_buy_now_prices() { - for (buy_now_price, expected) in [(0, "greater than 0"), (99, "below the minimum bid")] { - match Harness::new(with_buy_now(buy_now_price)) { - Ok(_) => panic!("expected a buy now price of {buy_now_price} to be rejected"), - Err(error) => { - let error = error - .downcast::() - .expect("expected an auction error"); - assert!( - matches!( - error, - AuctionError::ZeroBuyNowPrice - | AuctionError::BuyNowPriceBelowMinimumBid { .. } - ), - "{error}" - ); - assert!(error.to_string().contains(expected), "{error}"); - } - } - } -} - #[test] fn buy_now_price_round_trips_through_the_memo() -> Result<()> { // The harness parses the launcher spend and compares it to the launched auction diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 114773d..b24bb1b 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -305,16 +305,7 @@ impl Harness { fn try_bids(&mut self, bids: &[(u64, bool)]) -> Result> { let mut spend = BidSpend::default(); - - for &(amount, grace) in bids { - let key = self.bidder_key(amount)?; - let bid = Bid::new(amount, key.puzzle_hash); - spend - .actions - .push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); - self.fund_bid(&mut spend, key, bid)?; - } - + self.add_bids(&mut spend, bids)?; self.finish_bids(spend) } @@ -344,21 +335,13 @@ impl Harness { grace: bool, ) -> Result<(Vec, Nft)> { let mut spend = BidSpend::default(); - - for &(amount, grace) in bids { - let key = self.bidder_key(amount)?; - let bid = Bid::new(amount, key.puzzle_hash); - spend - .actions - .push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); - self.fund_bid(&mut spend, key, bid)?; - } + self.add_bids(&mut spend, bids)?; let price = self .auction .info .available_buy_now_price() - .ok_or(anyhow!("the auction can't be bought now"))?; + .ok_or(AuctionError::BuyNowUnavailable)?; let key = self.bidder_key(price)?; let puzzle_hash = key.puzzle_hash; @@ -377,6 +360,19 @@ impl Harness { Ok((bidders, buy_now.nft)) } + /// Adds a bid action for each of `bids` to `spend`, funded by a new bidder. + fn add_bids(&mut self, spend: &mut BidSpend, bids: &[(u64, bool)]) -> Result<()> { + for &(amount, grace) in bids { + let key = self.bidder_key(amount)?; + let bid = Bid::new(amount, key.puzzle_hash); + spend + .actions + .push(self.auction.spend_bid_action(&mut self.ctx, bid, grace)?); + self.fund_bid(spend, key, bid)?; + } + Ok(()) + } + /// A new key for a bidder, with a coin that holds the reserve amount for a bid of `amount` if the /// reserve is XCH. CAT bidders are funded from the bank instead. fn bidder_key(&mut self, amount: u64) -> Result { diff --git a/tests/parsing.rs b/tests/parsing.rs index 3d7fa6e..97fc411 100644 --- a/tests/parsing.rs +++ b/tests/parsing.rs @@ -185,5 +185,13 @@ fn rejects_invalid_auctions() -> Result<()> { Err(AuctionError::DuplicatePaymentPuzzleHash(_)) )); + let result = parse_modified(&mut h, |solution| { + solution.key_value_list.settings.buy_now_price = Some(99); + }); + assert!(matches!( + result, + Err(AuctionError::BuyNowPriceBelowMinimumBid { .. }) + )); + Ok(()) } diff --git a/tests/validation.rs b/tests/validation.rs index d56a4a9..62ebe8a 100644 --- a/tests/validation.rs +++ b/tests/validation.rs @@ -114,6 +114,46 @@ fn allows_fees_of_100_percent() -> Result<()> { Ok(()) } +#[test] +fn rejects_invalid_buy_now_prices() { + let with_buy_now = |buy_now_price| Config { + buy_now_price: Some(buy_now_price), + ..Config::default() + }; + + // `Some(0)` would be curried in the same way as `None` + let error = launch_error(with_buy_now(0), default_settings); + assert!(matches!(error, AuctionError::ZeroBuyNowPrice), "{error}"); + + // A bid at the buy now price skips the bid verifier, so it can't be below the minimum bid + for bid_verifier in [ + BidVerifier::Flat { + minimum_bid: 100, + bid_increment: 100, + }, + BidVerifier::Percent { + minimum_bid: 100, + bid_increment_bps: 100, + }, + ] { + let config = Config { + bid_verifier, + ..with_buy_now(99) + }; + let error = launch_error(config, default_settings); + assert!( + matches!( + error, + AuctionError::BuyNowPriceBelowMinimumBid { + buy_now_price: 99, + minimum_bid: 100, + } + ), + "{error}" + ); + } +} + #[test] fn rejects_duplicate_payment_puzzle_hashes() { let settings: [fn(&Config, Bytes32, Bytes32) -> AuctionSettings; 3] = [