Skip to content

Commit

Permalink
fix: display BatchID correctly, updates contract (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
orpheuslummis committed Jan 14, 2024
1 parent 41279b7 commit 40fce9c
Show file tree
Hide file tree
Showing 6 changed files with 930 additions and 897 deletions.
18 changes: 15 additions & 3 deletions contracts/AstaVerde.sol
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ contract AstaVerde is ERC1155, ERC1155Pausable, Ownable, IERC1155Receiver, Reent
}

struct Batch {
uint256 batchId;
uint256[] tokenIds;
uint256 creationTime;
uint256 startingPrice;
Expand Down Expand Up @@ -181,6 +182,7 @@ contract AstaVerde is ERC1155, ERC1155Pausable, Ownable, IERC1155Receiver, Reent
updateBasePrice();

Batch memory newBatch;
newBatch.batchId = lastBatchID;
newBatch.tokenIds = new uint256[](batchSize);
newBatch.creationTime = block.timestamp;
newBatch.price = basePrice;
Expand All @@ -205,7 +207,7 @@ contract AstaVerde is ERC1155, ERC1155Pausable, Ownable, IERC1155Receiver, Reent
}

batches.push(newBatch);
emit BatchMinted(lastBatchID, block.timestamp);
emit BatchMinted(newBatch.batchId, block.timestamp);
_mintBatch(address(this), newTokenIds, amounts, "");
}

Expand Down Expand Up @@ -264,11 +266,21 @@ contract AstaVerde is ERC1155, ERC1155Pausable, Ownable, IERC1155Receiver, Reent

function getBatchInfo(
uint256 batchID
) public view returns (uint256[] memory tokenIds, uint256 creationTime, uint256 price, uint256 remainingTokens) {
)
public
view
returns (
uint256 batchId,
uint256[] memory tokenIds,
uint256 creationTime,
uint256 price,
uint256 remainingTokens
)
{
require(batchID <= batches.length, "Batch ID is out of bounds");
Batch memory batch = batches[batchID];
price = getBatchPrice(batchID);
return (batch.tokenIds, batch.creationTime, price, batch.remainingTokens);
return (batch.batchId, batch.tokenIds, batch.creationTime, price, batch.remainingTokens);
}

function handleRefund(uint256 usdcAmount, uint256 totalCost) internal {
Expand Down
26 changes: 13 additions & 13 deletions test/AstaVerde.behavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ export function shouldBehaveLikeAstaVerde(): void {
await this.astaVerde.mintBatch(producers, cids);
const batchID = await this.astaVerde.lastBatchID();
const batchInfo = await this.astaVerde.getBatchInfo(batchID);
expect(batchInfo[0]).to.deep.equal([1n, 2n]); // tokenIds
expect(batchInfo[1]).to.be.a("bigint"); // creationTime
expect(batchInfo[2]).to.equal(BASE_PRICE); // price
expect(batchInfo[1]).to.deep.equal([1n, 2n]); // tokenIds
expect(batchInfo[2]).to.be.a("bigint"); // creationTime
expect(batchInfo[3]).to.equal(BASE_PRICE); // price
});

it("should pause and unpause the contract by the owner", async function () {
Expand Down Expand Up @@ -518,7 +518,7 @@ export function shouldBehaveLikeAstaVerde(): void {

// Buy the batch of tokens
const batchInfo = await this.astaVerde.getBatchInfo(batchID);
const price = batchInfo[2];
const price = batchInfo[3];
const tokenAmount = BigInt(cids.length);
const usdcAmount = price * tokenAmount;
const user = this.signers.others[0];
Expand All @@ -528,7 +528,7 @@ export function shouldBehaveLikeAstaVerde(): void {
await this.astaVerde.connect(user).buyBatch(batchID, usdcAmount, tokenAmount);

// Redeem the tokens
const tokenIds = batchInfo[0];
const tokenIds = batchInfo[1];
await this.astaVerde.connect(user).redeemTokens([...tokenIds]); // a copy of tokenIDs is needed

// Check that the tokens are marked as redeemed
Expand All @@ -549,7 +549,7 @@ export function shouldBehaveLikeAstaVerde(): void {
// User 1 buys the batch of tokens
const user1 = this.signers.others[0];
const batchInfo = await this.astaVerde.getBatchInfo(batchID);
const price = batchInfo[2];
const price = batchInfo[3];
const tokenAmount = BigInt(cids.length);
const usdcAmount = price * tokenAmount;
await mintUSDC(user1, this.mockUSDC, 1000000n);
Expand All @@ -559,7 +559,7 @@ export function shouldBehaveLikeAstaVerde(): void {

// User 2 attempts to redeem the tokens
const user2 = this.signers.others[1];
const tokenIds = batchInfo[0];
const tokenIds = batchInfo[1];
await expect(this.astaVerde.connect(user2).redeemTokens([...tokenIds])).to.be.revertedWith(
"Only the owner can redeem",
);
Expand All @@ -574,7 +574,7 @@ export function shouldBehaveLikeAstaVerde(): void {

// Buy the batch of tokens
const batchInfo = await this.astaVerde.getBatchInfo(batchID);
const price = batchInfo[2];
const price = batchInfo[3];
const tokenAmount = BigInt(cids.length);
const usdcAmount = price * tokenAmount;
const user = this.signers.others[0];
Expand All @@ -587,7 +587,7 @@ export function shouldBehaveLikeAstaVerde(): void {
await this.astaVerde.pause();

// Redeem the tokens
const tokenIds = batchInfo[0];
const tokenIds = batchInfo[1];
try {
await this.astaVerde.connect(user).redeemTokens([...tokenIds]);
} catch (error) {
Expand All @@ -613,8 +613,8 @@ export function shouldBehaveLikeAstaVerde(): void {
const user2 = this.signers.others[1];
const batchInfo1 = await this.astaVerde.getBatchInfo(batchID1);
const batchInfo2 = await this.astaVerde.getBatchInfo(batchID2);
const price1 = batchInfo1[2];
const price2 = batchInfo2[2];
const price1 = batchInfo1[3];
const price2 = batchInfo2[3];
const tokenAmount1 = BigInt(cids1.length);
const tokenAmount2 = BigInt(cids2.length);
const usdcAmount1 = price1 * tokenAmount1;
Expand Down Expand Up @@ -669,7 +669,7 @@ export function shouldBehaveLikeAstaVerde(): void {
for (let i = 0; i < numBatches; i++) {
console.log("buy batch", i);
let batchInfo = await this.astaVerde.getBatchInfo(i);
let price = batchInfo[2];
let price = batchInfo[3];
const tokenAmount = BigInt(cids.length);
const usdcAmount = price * tokenAmount;
usdcAmounts.push(usdcAmount);
Expand All @@ -679,7 +679,7 @@ export function shouldBehaveLikeAstaVerde(): void {
await this.astaVerde.connect(user).buyBatch(i, usdcAmount, tokenAmount); // here we see the price decrease
const expectedPrice = BASE_PRICE - i * PRICE_DECREASE_RATE;
batchInfo = await this.astaVerde.getBatchInfo(i); // here we see it decrease again
price = batchInfo[2];
price = batchInfo[3];

console.log("expectedPrice", expectedPrice);
console.log("price", price);
Expand Down
17 changes: 9 additions & 8 deletions webapp/src/components/BatchCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ export default function BatchCard({ batch }: { batch: Batch }) {
// const [isModalOpen, setIsModalOpen] = useState(false);
const [tokenAmount, setTokenAmount] = useState(1);

console.log("batch.token_ids", batch.token_ids);
console.log("BatchCard: batch.token_ids", batch.token_ids);

const { data, fetchNextPage, error } = useContractInfiniteReads({
cacheKey: "tokenMetadata",
...paginatedIndexesConfig(
(tokenID: bigint) => {
console.log("fetching tokenCID", tokenID);
console.log("BatchCard: fetching tokenCID", tokenID);
return [
{
...astaverdeContractConfig,
Expand All @@ -57,9 +57,10 @@ export default function BatchCard({ batch }: { batch: Batch }) {
args: [BigInt(batch.id)],
});

console.log("batch", batch);
console.log("batches", batches);
console.log("currentPrice", currentPrice);
console.log("BatchCard: batch", batch);
console.log("BatchCard: batches", batches);
console.log("BatchCard: currentPrice", currentPrice);
console.log("BatchCard: batch.id", batch.id);

// we get metadata for each token,

Expand All @@ -80,7 +81,7 @@ export default function BatchCard({ batch }: { batch: Batch }) {
/>

<div className="col-span-full mt-4">
<p className="text-gray-900 font-bold text-2xl">Batch ID: {batch.id}</p>
<p className="text-gray-900 font-bold text-2xl">Batch {Number(batch.id)}</p>
<p className="text-gray-600">{batch ? `${batch.itemsLeft} items left` : "0 items left"}</p>
<p className="text-gray-600">{currentPrice ? `${currentPrice} USDC` : "0 USDC"}</p>
</div>
Expand Down Expand Up @@ -134,8 +135,8 @@ function BuyBatchButton({
args: [address!, astaverdeContractConfig.address],
});

console.log("🚀 ~ file: BatchCard.tsx:152 ~ allowance:", Number(formatUnits(allowance || BigInt(0), 6)), totalPrice);
console.log("buyBatch enabled", Number(formatUnits(allowance || BigInt(0), 6)) >= totalPrice);
console.log("BatchCard: allowance:", Number(formatUnits(allowance || BigInt(0), 6)), totalPrice);
console.log("BatchCard: buyBatch enabled", Number(formatUnits(allowance || BigInt(0), 6)) >= totalPrice);

const { config: configApprove } = usePrepareContractWrite({
...usdcContractConfig,
Expand Down
53 changes: 31 additions & 22 deletions webapp/src/components/BatchListing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ export function BatchListing() {
});

if (lastBatchIDError || lastBatchID === undefined) {
console.log("lastBatchIDError", lastBatchIDError);
console.log("BatchListing: lastBatchIDError", lastBatchIDError);
}
const lastBatchIDn: number = lastBatchID ? Number(lastBatchID) : 0;

console.log("lastBatchIDn, isError, isLoading", lastBatchID, isError, isLoading);
console.log("BatchListing: lastBatchIDn, isError, isLoading", lastBatchID, isError, isLoading);

const { data, fetchNextPage, error, hasNextPage } = useContractInfiniteReads({
cacheKey: "batchMetadata",
...paginatedIndexesConfig(
(batchID: bigint) => {
console.log("fetching batchID", batchID);
console.log("BatchListing: fetching batchID", batchID);
return [
{
...astaverdeContractConfig,
Expand All @@ -39,7 +39,20 @@ export function BatchListing() {
{ start: lastBatchIDn, perPage: 10, direction: "decrement" },
),
});
console.log("data", data);
console.log("BatchListing: data", data);

if (isLoading) {
return <div>Loading...</div>;
}

if (isError) {
console.log("BatchListing: error", error);
return <div>Could not display, sorry.</div>;
}

if (!data) {
return <div>Could not display, sorry.</div>;
}

const { address } = useAccount();

Expand All @@ -51,21 +64,27 @@ export function BatchListing() {
});

if (error) {
console.log("error", error);
console.log("BatchListing: error", error);
return <div>Could not display, sorry.</div>;
}

if (data?.pages?.[0]?.[0]?.error) {
return <div>Error occurred: No batch has been minted yet.</div>;
}


const batches: Batch[] =
data?.pages?.flatMap(
(page: any[]) =>
page?.map((batch: any) => {
console.log("batch", batch);
const tokenIDs: number[] = batch.result?.[0] || [];
const timestamp: number = batch.result?.[1] || 0;
const price: number = batch.result?.[2] || 0;
const itemsLeft: number = batch.result?.[3] || 0;
const batchProper = new Batch(0, tokenIDs, timestamp, price, itemsLeft); // Assuming batch.id is not available, replace 0 with the correct value
console.log("batchProper", batchProper);
console.log("BatchListing: batch", batch);
const batchID = batch.result?.[0] || 0;
const tokenIDs: number[] = batch.result?.[1] || [];
const timestamp: number = batch.result?.[2] || 0;
const price: number = batch.result?.[3] || 0;
const itemsLeft: number = batch.result?.[4] || 0;
const batchProper = new Batch(batchID, tokenIDs, timestamp, price, itemsLeft);
console.log("BatchListing: batchProper", batchProper);
return batchProper;
}),
) || [];
Expand All @@ -74,16 +93,6 @@ export function BatchListing() {

return (
<>
{/* <div className="w-full flex justify-end p-2 pt-4">
<button
className="px-4 py-2 bg-secondary text-white rounded-full hover:bg-blue-700 disabled:opacity-50"
disabled={!fetchNextPage || isLoading || isError}
onClick={() => refetchAllowance()}
>
Refresh
</button>
</div> */}

<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2 mt-4">
{batches.map((batch) => (
<div key={batch.id} className="w-full px-2 mb-4">
Expand Down
Loading

1 comment on commit 40fce9c

@vercel
Copy link

@vercel vercel bot commented on 40fce9c Jan 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

astaverde-dev – ./webapp

astaverde-dev-git-main-orpheuslummis.vercel.app
astaverde-dev.vercel.app
astaverde-dev-orpheuslummis.vercel.app

Please sign in to comment.