Skip to content

Commit

Permalink
feat: docs and demos
Browse files Browse the repository at this point in the history
  • Loading branch information
jinglescode committed Apr 29, 2024
1 parent 1fd95ff commit 13c9b3a
Show file tree
Hide file tree
Showing 13 changed files with 928 additions and 50 deletions.
19 changes: 13 additions & 6 deletions packages/contracts/src/vesting/offchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ export class MeshVestingContract extends MeshTxInitiator {
depositFund = async (
amount: Asset[],
lockUntilTimeStampMs: number,
beneficiary: string,
networkId = 0
beneficiary: string
): Promise<string> => {
const { utxos, walletAddress } = await this.getWalletInfoForTx();
const scriptAddr = v2ScriptToBech32(this.scriptCbor, undefined, networkId);
const scriptAddr = v2ScriptToBech32(
this.scriptCbor,
undefined,
this.networkId
);
const { pubKeyHash: ownerPubKeyHash } =
serializeBech32Address(walletAddress);
const { pubKeyHash: beneficiaryPubKeyHash } =
Expand All @@ -49,19 +52,23 @@ export class MeshVestingContract extends MeshTxInitiator {
return this.mesh.txHex;
};

withdrawFund = async (vestingUtxo: UTxO, networkId = 0): Promise<string> => {
withdrawFund = async (vestingUtxo: UTxO): Promise<string> => {
const { utxos, walletAddress, collateral } =
await this.getWalletInfoForTx();
const { input: collateralInput, output: collateralOutput } = collateral;
const scriptAddr = v2ScriptToBech32(this.scriptCbor, undefined, networkId);
const scriptAddr = v2ScriptToBech32(
this.scriptCbor,
undefined,
this.networkId
);
const { pubKeyHash } = serializeBech32Address(walletAddress);

const datum = parseDatumCbor<VestingDatum>(vestingUtxo.output.plutusData!);

const invalidBefore =
unixTimeToEnclosingSlot(
Math.min(datum.fields[0].int, Date.now() - 15000),
networkId === 0
this.networkId === 0
? SLOT_CONFIG_NETWORK.Preprod
: SLOT_CONFIG_NETWORK.Mainnet
) + 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ function Right() {
try {
const contract = getContract();

const tokenName = `Mesh Gift Card${Math.random()}`;
const tokenName = `Mesh_Gift_Card_${parseInt(
(Math.random() * 1000).toString()
)}`;
const giftValue: Asset[] = [
{
unit: 'lovelace',
Expand Down
129 changes: 129 additions & 0 deletions packages/demo/components/pages/contracts/marketplace/buyAsset.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import Codeblock from '../../../ui/codeblock';
import Card from '../../../ui/card';
import SectionTwoCol from '../../../common/sectionTwoCol';
import Button from '../../../ui/button';
import { CardanoWallet, useWallet } from '@meshsdk/react';
import { useEffect, useState } from 'react';
import RunDemoResult from '../../../common/runDemoResult';
import { getMarketplace, asset, price } from './config';
import useLocalStorage from '../../../../hooks/useLocalStorage';
import Input from '../../../ui/input';

export default function MarketplaceBuyAsset() {
return (
<>
<SectionTwoCol
sidebarTo="buyAsset"
header="Buy Asset"
leftFn={Left()}
rightFn={Right()}
/>
</>
);
}

function Left() {
let code = `async marketplace.purchaseAsset(\n`;
code += ` address: string,\n`;
code += ` asset: string,\n`;
code += ` price: number\n`;
code += `)`;
return (
<>
<p>
Purchase a listed asset from the marketplace. The seller will receive
the listed price in ADA and the buyer will receive the asset.
</p>
<Codeblock data={code} isJson={false} />
<p>
<code>address</code> is the seller's address. <code>asset</code> is the
listed asset's <code>unit</code>. <code>price</code> is the listed price
in Lovelace.
</p>
</>
);
}

function Right() {
const { connected, wallet } = useWallet();
const [loading, setLoading] = useState<boolean>(false);
const [response, setResponse] = useState<null | any>(null);
const [responseError, setResponseError] = useState<null | any>(null);
const [userLocalStorage, setUserlocalStorage] = useLocalStorage(
'meshMarketplaceDemo',
{}
);
const [listPrice, updateListPrice] = useState<number>(price);
const [sellerAddress, updateSellerAddress] =
useState<string>('SELLER ADDRESS');

let code1 = ``;
code1 += `const txHash = await marketplace.purchaseAsset(\n`;
code1 += ` '${sellerAddress}',\n`;
code1 += ` '${asset}',\n`;
code1 += ` ${listPrice}\n`;
code1 += `);\n`;

useEffect(() => {
if (userLocalStorage.listPrice) {
updateListPrice(userLocalStorage.listPrice);
}
if (userLocalStorage.sellerAddress) {
updateSellerAddress(userLocalStorage.sellerAddress);
}
}, []);

async function rundemo() {
setLoading(true);
setResponse(null);
setResponseError(null);

try {
const marketplace = getMarketplace(wallet);
const txHash = await marketplace.purchaseAsset(
sellerAddress,
asset,
listPrice
);
setResponse(txHash);
} catch (error) {
setResponseError(`${error}`);
}
setLoading(false);
}

return (
<Card>
<Input
value={sellerAddress}
onChange={(e) => updateSellerAddress(e.target.value)}
placeholder="Seller address"
label="Seller address"
/>
<Input
value={listPrice}
onChange={(e) => updateListPrice(e.target.value)}
placeholder="Listed price in Lovelace"
label="Listed price in Lovelace"
/>
<Codeblock data={code1} isJson={false} />
{connected ? (
<>
<Button
onClick={() => rundemo()}
style={
loading ? 'warning' : response !== null ? 'success' : 'light'
}
disabled={loading}
>
Purchase Listed Mesh Token
</Button>
<RunDemoResult response={response} />
</>
) : (
<CardanoWallet />
)}
<RunDemoResult response={responseError} label="Error" />
</Card>
);
}
131 changes: 131 additions & 0 deletions packages/demo/components/pages/contracts/marketplace/cancelListing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import Codeblock from '../../../ui/codeblock';
import Card from '../../../ui/card';
import SectionTwoCol from '../../../common/sectionTwoCol';
import Button from '../../../ui/button';
import { CardanoWallet, useWallet } from '@meshsdk/react';
import { useEffect, useState } from 'react';
import RunDemoResult from '../../../common/runDemoResult';
import { getMarketplace, asset, price } from './config';
import useLocalStorage from '../../../../hooks/useLocalStorage';
import Input from '../../../ui/input';

export default function MarketplaceCancelAsset() {
return (
<>
<SectionTwoCol
sidebarTo="cancelListing"
header="Cancel Listing"
leftFn={Left()}
rightFn={Right()}
/>
</>
);
}

function Left() {
let code = `async marketplace.delistAsset(\n`;
code += ` address: string,\n`;
code += ` asset: string,\n`;
code += ` price: number\n`;
code += `)`;
return (
<>
<p>
Cancel a listing on the marketplace. The seller can cancel the listing
at any time. The seller will receive the listed asset back.
</p>
<p>
<code>address</code> is the seller's address. <code>asset</code> is the
listed asset's <code>unit</code>. <code>price</code> is the listed price
in Lovelace.
</p>
<Codeblock data={code} isJson={false} />
</>
);
}

function Right() {
const { connected, wallet } = useWallet();
const [loading, setLoading] = useState<boolean>(false);
const [response, setResponse] = useState<null | any>(null);
const [responseError, setResponseError] = useState<null | any>(null);
const [userLocalStorage, setUserlocalStorage] = useLocalStorage(
'meshMarketplaceDemo',
{}
);

const [listPrice, updateListPrice] = useState<number>(price);
const [sellerAddress, updateSellerAddress] =
useState<string>('SELLER ADDRESS');

let code1 = ``;
code1 += `const txHash = await marketplace.delistAsset(\n`;
code1 += ` '${sellerAddress}',\n`;
code1 += ` '${asset}',\n`;
code1 += ` ${listPrice}\n`;
code1 += `);`;

useEffect(() => {
if (userLocalStorage.listPrice) {
updateListPrice(userLocalStorage.listPrice);
}
if (userLocalStorage.sellerAddress) {
updateSellerAddress(userLocalStorage.sellerAddress);
}
}, []);

async function rundemo() {
setLoading(true);
setResponse(null);
setResponseError(null);

try {
const marketplace = getMarketplace(wallet);
const txHash = await marketplace.delistAsset(
sellerAddress,
asset,
listPrice
);
setResponse(txHash);
} catch (error) {
setResponseError(`${error}`);
}
setLoading(false);
}

return (
<Card>
<Input
value={sellerAddress}
onChange={(e) => updateSellerAddress(e.target.value)}
placeholder="Seller address"
label="Seller address"
/>
<Input
value={listPrice}
onChange={(e) => updateListPrice(e.target.value)}
placeholder="Listing price in Lovelace"
label="Listing price in Lovelace"
/>

<Codeblock data={code1} isJson={false} />
{connected ? (
<>
<Button
onClick={() => rundemo()}
style={
loading ? 'warning' : response !== null ? 'success' : 'light'
}
disabled={loading}
>
Cancel listing
</Button>
<RunDemoResult response={response} />
</>
) : (
<CardanoWallet />
)}
<RunDemoResult response={responseError} label="Error" />
</Card>
);
}
52 changes: 52 additions & 0 deletions packages/demo/components/pages/contracts/marketplace/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// import { BasicMarketplace } from '@meshsdk/contracts';
// import { BlockfrostProvider } from '@meshsdk/core';

import { MeshMarketplaceContract } from '@meshsdk/contracts';
import { BlockfrostProvider, MeshTxBuilder } from '@meshsdk/core';

// export function getMarketplace(wallet) {
// const blockchainProvider = new BlockfrostProvider(
// process.env.NEXT_PUBLIC_BLOCKFROST_API_KEY_PREPROD!
// );

// const marketplace = new BasicMarketplace({
// fetcher: blockchainProvider,
// initiator: wallet,
// network: 'preprod',
// signer: wallet,
// submitter: blockchainProvider,
// percentage: 25000, // 2.5%
// owner: 'addr_test1vpvx0sacufuypa2k4sngk7q40zc5c4npl337uusdh64kv0c7e4cxr',
// });

// return marketplace;
// }

const policyId = 'd9312da562da182b02322fd8acb536f37eb9d29fba7c49dc17255527';
const assetId = '4d657368546f6b656e';
export const asset = policyId + assetId;
export const price = 10000000;

export function getContract(wallet) {
const blockchainProvider = new BlockfrostProvider(
process.env.NEXT_PUBLIC_BLOCKFROST_API_KEY_PREPROD!
);

const meshTxBuilder = new MeshTxBuilder({
fetcher: blockchainProvider,
submitter: blockchainProvider,
});

const contract = new MeshMarketplaceContract(
{
mesh: meshTxBuilder,
fetcher: blockchainProvider,
wallet: wallet,
networkId: 0,
},
'addr_test1qpvx0sacufuypa2k4sngk7q40zc5c4npl337uusdh64kv0uafhxhu32dys6pvn6wlw8dav6cmp4pmtv7cc3yel9uu0nq93swx9',
200
);

return contract;
}

0 comments on commit 13c9b3a

Please sign in to comment.