Skip to content

Commit

Permalink
wip: test missing in rust
Browse files Browse the repository at this point in the history
  • Loading branch information
matiasbenary committed May 11, 2024
1 parent 126f0eb commit a90fa4b
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 9 deletions.
18 changes: 16 additions & 2 deletions contract-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,23 @@ pub struct Bid {
pub struct Contract {
highest_bid: Bid,
auction_end_time: U64,
auctioneer: AccountId,
auction_was_claimed: bool,
}

#[near]
impl Contract {
#[init]
#[private] // only callable by the contract's account
pub fn init(end_time: U64) -> Self {
pub fn init(end_time: U64,auctioneer: AccountId) -> Self {
Self {
highest_bid: Bid {
bidder: env::current_account_id(),
bid: NearToken::from_yoctonear(1),
},
auction_end_time: end_time,
auctioneer: auctioneer,
auction_was_claimed: false,
}
}

Expand Down Expand Up @@ -65,6 +69,15 @@ impl Contract {
pub fn get_auction_end_time(&self) -> U64 {
self.auction_end_time
}

pub fn auction_end(&mut self) -> Promise {
assert!(env::predecessor_account_id() == self.auctioneer, "You must place a higher bid");
assert!(env::block_timestamp() < self.auction_end_time.into(), "Auction has not ended yet");
assert!(!self.auction_was_claimed, "Auction has been claimed");
self.auction_was_claimed = true;
let auctioneer = self.auctioneer.clone();
Promise::new(auctioneer).transfer(self.highest_bid.bid)
}
}

/*
Expand All @@ -77,7 +90,8 @@ mod tests {

#[test]
fn init_contract() {
let contract = Contract::init(U64::from(1000));
let auctioneer: AccountId = "auctioneer.testnet".parse().unwrap();
let contract = Contract::init(U64::from(1000), auctioneer);

let default_bid = contract.get_highest_bid();
assert_eq!(default_bid.bidder, env::current_account_id());
Expand Down
9 changes: 8 additions & 1 deletion contract-rs/tests/test_basics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ async fn test_contract_is_operational() -> Result<(), Box<dyn std::error::Error>
.await?
.unwrap();

let auctioneer = root
.create_subaccount("auctioneer")
.initial_balance(FIVE_NEAR)
.transact()
.await?
.unwrap();

let contract_account = root
.create_subaccount("contract")
.initial_balance(FIVE_NEAR)
Expand All @@ -34,7 +41,7 @@ async fn test_contract_is_operational() -> Result<(), Box<dyn std::error::Error>

let init = contract
.call("init")
.args_json(json!({"end_time": a_minute_from_now.to_string()}))
.args_json(json!({"end_time": a_minute_from_now.to_string(),"auctioneer": auctioneer.id() }))
.transact()
.await?;

Expand Down
45 changes: 44 additions & 1 deletion contract-ts/sandbox-ts/main.ava.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,20 @@ test.beforeEach(async (t) => {
const alice = await root.createSubAccount("alice");
const bob = await root.createSubAccount("bob");
const contract = await root.createSubAccount("contract");
const auctioneer = await root.createSubAccount("auctioneer");

// Deploy contract (input from package.json)
await contract.deploy(process.argv[2]);

// Initialize contract, finishes in 1 minute
await contract.call(contract, "init", {
end_time: String((Date.now() + 60000) * 10 ** 6),
auctioneer: auctioneer.accountId,
});

// Save state for test runs, it is unique for each test
t.context.worker = worker;
t.context.accounts = { alice, bob, contract };
t.context.accounts = { alice, bob, contract, auctioneer };
});

test.afterEach.always(async (t) => {
Expand Down Expand Up @@ -79,4 +81,45 @@ test("Auction closes", async (t) => {

// alice cannot bid anymore
await t.throwsAsync(alice.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("1 N").toString() }))
});

test("Claim auction", async (t) => {
const { alice, bob, contract, auctioneer} = t.context.accounts;

await alice.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("1 N").toString() });
await bob.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("2 N").toString() });
const auctioneerBalance = await auctioneer.balance();
const available = parseFloat(auctioneerBalance.available.toHuman());

// fast forward approx a minute
await t.context.worker.provider.fastForward(60)

await auctioneer.call(contract, "auction_end",{});

const contractNewBalance = await auctioneer.balance();
const new_available = parseFloat(contractNewBalance.available.toHuman());

t.is(new_available.toFixed(2), (available + 2).toFixed(2));
});

test("Auction open", async (t) => {
const { alice, bob, contract, auctioneer} = t.context.accounts;

await alice.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("1 N").toString() });
await bob.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("2 N").toString() });

await t.throwsAsync(auctioneer.call(contract, "auction_end",{}))
});

test("Auction has been claimed", async (t) => {
const { alice, bob, contract, auctioneer} = t.context.accounts;

await alice.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("1 N").toString() });
await bob.call(contract, "bid", {}, { attachedDeposit: NEAR.parse("2 N").toString() });
// fast forward approx a minute
await t.context.worker.provider.fastForward(60)

await auctioneer.call(contract, "auction_end",{});

await t.throwsAsync(auctioneer.call(contract, "auction_end",{}))
});
22 changes: 17 additions & 5 deletions contract-ts/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,21 @@ class Bid {
@NearBindgen({ requireInit: true })
class AuctionContract {
highest_bid: Bid = { bidder: '', bid: BigInt(1) };
auctionEndTime: bigint = BigInt(0);
auction_end_time: bigint = BigInt(0);
auctioneer: string = "";
auction_was_claimed: boolean = false;

@initialize({ privateFunction: true })
init({ end_time }: { end_time: bigint }) {
this.auctionEndTime = end_time;
init({ end_time, auctioneer }: { end_time: bigint, auctioneer: string }) {
this.auction_end_time = end_time;
this.highest_bid = { bidder: near.currentAccountId(), bid: BigInt(1) };
this.auctioneer = auctioneer;
}

@call({ payableFunction: true })
bid(): NearPromise {
// Assert the auction is still ongoing
assert(this.auctionEndTime > near.blockTimestamp(), "Auction has ended");
assert(this.auction_end_time > near.blockTimestamp(), "Auction has ended");

// Current bid
const bid = near.attachedDeposit();
Expand All @@ -46,6 +49,15 @@ class AuctionContract {

@view({})
get_auction_end_time(): BigInt {
return this.auctionEndTime;
return this.auction_end_time;
}
@call({})
auction_end() {
assert(near.predecessorAccountId() == this.auctioneer, "Only auctioneer can end the auction");
assert(this.auction_end_time <= near.blockTimestamp(), "Auction has not ended yet");
assert(!this.auction_was_claimed, "Auction has been claimed");

this.auction_was_claimed = true;
return NearPromise.new(this.auctioneer).transfer(this.highest_bid.bid);
}
}
1 change: 1 addition & 0 deletions contract-ts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"target": "ES5",
"noEmit": true,
"noImplicitAny": false,
"lib": ["esnext", "esnext.asynciterable"]
},
"files": [
"sandbox-ts/main.ava.ts",
Expand Down

0 comments on commit a90fa4b

Please sign in to comment.