Skip to content

Commit

Permalink
Fix small errors and update packages
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastienGllmt committed Apr 26, 2024
1 parent bccb004 commit da5c9b6
Show file tree
Hide file tree
Showing 12 changed files with 114 additions and 33 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ You can find the full docs on this [here](https://docs.paimastudios.com/home/mul

- [Cardano NodeJS](https://www.npmjs.com/package/@paima/cardano-projected-nft-nodejs)
- [Cardano Browser](https://www.npmjs.com/package/@paima/cardano-projected-nft-browser)

Deployment addresses:
- Cardano preprod: `addr_test1wqlvnxfxyyw64l3fr9gmw7x5mfmnd29smg4why3stdg35us2lxacg`
- EVM: `0x963ba25745aEE135EdCFC2d992D5A939d42738B6`
4 changes: 2 additions & 2 deletions dapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"@babel/core": "^7.0.0",
"@babel/plugin-syntax-flow": "^7.14.5",
"@babel/plugin-transform-react-jsx": "^7.14.9",
"@dcspark/cardano-multiplatform-lib-browser": "^3.1.2",
"@dcspark/carp-client": "^2.4.1",
"@dcspark/cardano-multiplatform-lib-browser": "^5.2.0",
"@dcspark/carp-client": "^3.1.0",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.9",
Expand Down
52 changes: 46 additions & 6 deletions dapp/src/components/IsConnectedWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ import { Stack, Typography } from "@mui/material";
import { PropsWithChildren } from "react";
import ConnectWallet from "./ConnectWallet";
import { useGetVmType } from "../hooks/useGetVmType";
import { isChainSupported } from "../utils/evm/chains";
import { isChainSupported as isEvmChainSupported } from "../utils/evm/chains";
import { isChainSupported as isCardanoChainSupported } from "../utils/cardano/chains";
import { useNetwork } from "wagmi";
import ChainSelector from "./ChainSelector";
import { VmTypes } from "../utils/constants";
import { useCardanoNetworkId } from "../hooks/cardano/useCardanoNetworkId";
import { useCardanoWalletApi } from "../hooks/cardano/useCardanoWalletApi";
import { useDappStore } from "../store";

export default function IsConnectedWrapper({ children }: PropsWithChildren) {
const vmType = useGetVmType();
const { chain } = useNetwork();
const supportedChain = isChainSupported(chain?.id);

if (vmType === VmTypes.None) {
return (
Expand All @@ -33,13 +35,51 @@ export default function IsConnectedWrapper({ children }: PropsWithChildren) {
);
}

if (vmType === VmTypes.EVM && !supportedChain) {
if (vmType === VmTypes.EVM) {
const EvmIsConnected = IsConnectedEvmWrapper();
if (EvmIsConnected != null) {
return EvmIsConnected;
}
}
if (vmType === VmTypes.Cardano) {
const CardanoIsConnected = IsConnectedCardanoWrapper();
if (CardanoIsConnected != null) {
return CardanoIsConnected;
}
}

return <>{children}</>;
}

function IsConnectedCardanoWrapper() {
const selectedWallet = useDappStore((state) => state.selectedWallet);
const walletApi = useCardanoWalletApi(selectedWallet);
const networkId = useCardanoNetworkId(walletApi);
const supportedChain = isCardanoChainSupported(networkId);

if (!supportedChain) {
return (
<Stack sx={{ my: 4, gap: 2, alignItems: "center" }}>
<Typography>You are using an account on an unsupported network.</Typography>
</Stack>
);
}

return undefined;
}

function IsConnectedEvmWrapper() {
const { chain } = useNetwork();
const supportedChain = isEvmChainSupported(chain?.id);

if (!supportedChain) {
return (
<Stack sx={{ my: 4, gap: 2, alignItems: "center" }}>
<Typography>You are using an unsupported network.</Typography>
<ChainSelector text="Switch network" />
</Stack>
);
}
return <>{children}</>;
}

return undefined;
}
3 changes: 3 additions & 0 deletions dapp/src/components/cardano/LockNftList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ export default function LockNftList() {
if (showOnlyNfts) {
tokens = tokens.filter((token) => isTokenNft(token));
}
if (tokens.length === 0) {
return <Typography>None.</Typography>;
}

return (
<Stack sx={{ gap: 2, width: "100%", alignItems: "center" }}>
Expand Down
20 changes: 10 additions & 10 deletions dapp/src/components/cardano/UnlockNftList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ function UnlockNftListItem({
const lucid = useDappStore((state) => state.lucid);
const address = useDappStore((state) => state.address);
const paymentKeyHash = useDappStore((state) => state.paymentKeyHash);
const { tokens, actionTxId, actionOutputIndex, plutusDatum } = lockInfo;
const { tokens, actionOutputIndex, txId, plutusDatum } = lockInfo;
let { unlockTime } = lockInfo;
const [now, setNow] = useState<number>(new Date().getTime());
const [isLoading, setIsLoading] = useState(false);
Expand Down Expand Up @@ -129,8 +129,8 @@ function UnlockNftListItem({
throw new Error("Prerequisites missing!");
}

if (!actionTxId) {
console.error("actionTxId missing in lock info", lockInfo);
if (!txId) {
console.error("txId missing in lock info", lockInfo);
return;
}
if (!plutusDatum) {
Expand All @@ -141,7 +141,7 @@ function UnlockNftListItem({
const validatorAddress = lucid.utils.validatorToAddress(validator);
const utxos = await lucid.utxosByOutRef([
{
txHash: actionTxId,
txHash: txId,
outputIndex: actionOutputIndex,
},
]);
Expand All @@ -155,7 +155,7 @@ function UnlockNftListItem({

const datum = getUnlockDatum({
ownerPaymentKeyHash: paymentKeyHash,
txId: actionTxId,
txId,
outputIndex: BigInt(actionOutputIndex),
unlockTime: BigInt(lastBlockTime + ttl) + minimumLockTime,
});
Expand Down Expand Up @@ -219,14 +219,14 @@ function UnlockNftListItem({
throw new Error("Prerequisites missing!");
}

if (!actionTxId) {
console.error("actionTxId missing in lock info", lockInfo);
if (!txId) {
console.error("txId missing in lock info", lockInfo);
return;
}

const utxos = await lucid.utxosByOutRef([
{
txHash: actionTxId,
txHash: txId,
outputIndex: actionOutputIndex,
},
]);
Expand Down Expand Up @@ -327,7 +327,7 @@ function UnlockNftListItem({
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Stack>
<Typography sx={{ overflowWrap: "anywhere" }}>
Tx ID: {actionTxId}
Tx ID: {txId}
<Box component="span" fontWeight={700}>
#{actionOutputIndex}
</Box>
Expand Down Expand Up @@ -449,7 +449,7 @@ export default function UnlockNftList() {
{unclaimedLocks.map((lock) => (
<UnlockNftListItem
lockInfo={lock}
key={`${lock.actionTxId}#${lock.actionOutputIndex}`}
key={`${lock.txId}#${lock.actionOutputIndex}`}
metadata={nftMetadata}
/>
))}
Expand Down
5 changes: 5 additions & 0 deletions dapp/src/hooks/cardano/useCardanoWalletApi.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { WalletApi } from "lucid-cardano";
import { useEffect, useState } from "react";
import { useDappStore } from "../../store";

const useCardanoWalletApi = (walletKey?: string) => {
const [walletApi, setWalletApi] = useState<WalletApi>();
const selectWallet = useDappStore((state) => state.selectWallet);

useEffect(() => {
if (window.cardano && walletKey && window.cardano[walletKey]) {
window.cardano[walletKey].enable().then(setWalletApi);
} else {
// the user may have uninstalled the wallet they previously had
selectWallet(undefined);
}
}, [walletKey]);

Expand Down
10 changes: 7 additions & 3 deletions dapp/src/hooks/cardano/useGetLocksCardano.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ const fetchLocks = async (paymentKeyHash: string) => {
);
const responseData: ProjectedNftRangeResponse = request.data;
const locksMap: Record<string, LockInfoCardano> = {};
responseData.forEach((dat) => {
responseData.forEach(datAndTx => datAndTx.payload.forEach((dat) => {
if (dat.status === ProjectedNftStatus.Invalid) return;
if (dat.ownerAddress !== paymentKeyHash) return;

const token = new Token(new Asset(dat.policyId, dat.assetName), BigInt(dat.amount));
const txKey = `${dat.actionTxId}#${dat.actionOutputIndex}`;
const txKey = `${datAndTx.txId}#${dat.actionOutputIndex}`;
const previousTxKey =
dat.previousTxHash !== "" && dat.previousTxOutputIndex != null
? `${dat.previousTxHash}#${dat.previousTxOutputIndex}`
Expand All @@ -44,6 +44,8 @@ const fetchLocks = async (paymentKeyHash: string) => {
tokens: [token],
status: dat.status,
unlockTime: null,
block: datAndTx.block,
txId: datAndTx.txId,
};
locksMap[txKey] = lock;
} else {
Expand Down Expand Up @@ -71,6 +73,8 @@ const fetchLocks = async (paymentKeyHash: string) => {
tokens: [token],
status: dat.status,
unlockTime: BigInt(dat.forHowLong),
block: datAndTx.block,
txId: datAndTx.txId,
};
delete locksMap[previousTxKey];
locksMap[txKey] = lock;
Expand All @@ -92,7 +96,7 @@ const fetchLocks = async (paymentKeyHash: string) => {
assertNever(dat.status);
break;
}
});
}));
const locks: LockInfoCardano[] = Object.values(locksMap).sort(
(a, b) => a.actionSlot - b.actionSlot,
);
Expand Down
8 changes: 6 additions & 2 deletions dapp/src/hooks/cardano/useLucid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ const useLucid = () => {
: "https://cardano-mainnet.blockfrost.io/api/v0",
env.REACT_APP_BLOCKFROST_PROJECT_ID,
);
const newLucidInstance = await Lucid.new(provider, blockfrostNetwork);

newLucidInstance.selectWallet(walletApi);
try {
const newLucidInstance = await Lucid.new(provider, blockfrostNetwork);
newLucidInstance.selectWallet(walletApi);

return newLucidInstance;
} catch (e) {
throw new Error(`Blockfrost connection error. Check your network panel for more information`);
}
}, [walletApi, networkId]);

useEffect(() => {
Expand Down
19 changes: 19 additions & 0 deletions dapp/src/utils/cardano/chains.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import env from "../configs/env";
import {
NetworkInfo
} from "@dcspark/cardano-multiplatform-lib-browser";

/**
* Define supported chains
*/
export const supportedChains: number[] = env.REACT_APP_TESTNET
? [NetworkInfo.preprod().network_id()]
: [NetworkInfo.mainnet().network_id()];


export const isChainSupported = (chainId: number | undefined) => {
return (
chainId != null && supportedChains.find((chain) => chain === chainId) != null
);
};

4 changes: 3 additions & 1 deletion dapp/src/utils/cardano/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { ProjectedNftRangeResponse, ProjectedNftStatus } from "@dcspark/carp-client/shared/models/ProjectedNftRange";
import { Token } from "./token";

export type LockInfoCardano = ProjectedNftRangeResponse[number] & {
export type LockInfoCardano = ProjectedNftRangeResponse[number]['payload'][number] & {
tokens: Token[];
status: Exclude<ProjectedNftStatus, "Invalid">;
unlockTime: null | bigint;
block: ProjectedNftRangeResponse[number]['block'],
txId: ProjectedNftRangeResponse[number]['txId']
};
2 changes: 1 addition & 1 deletion dapp/src/utils/evm/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,6 @@ export const getChainReserveWaitingTime = (

export const isChainSupported = (chainId: number | undefined) => {
return (
chainId != null && !!supportedChains.find((chain) => chain.id === chainId)
chainId != null && supportedChains.find((chain) => chain.id === chainId) != null
);
};
16 changes: 8 additions & 8 deletions dapp/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1360,15 +1360,15 @@
resolved "https://registry.yarnpkg.com/@csstools/selector-specificity/-/selector-specificity-2.2.0.tgz#2cbcf822bf3764c9658c4d2e568bd0c0cb748016"
integrity sha512-+OJ9konv95ClSTOJCmMZqpd5+YGsB2S+x6w3E1oaM8UuR5j8nTNHYSz8c9BEPGDOCMQYIEEGlVPj/VY64iTbGw==

"@dcspark/cardano-multiplatform-lib-browser@^3.1.2":
version "3.1.2"
resolved "https://registry.yarnpkg.com/@dcspark/cardano-multiplatform-lib-browser/-/cardano-multiplatform-lib-browser-3.1.2.tgz#1495d57b6d129c50a87bc838c11d0b7d7ad6939d"
integrity sha512-BDIF33nqEKAGn72+ESD1fLgnWCZJbPWnVKHr0cy7Al2zhvM30rGsajcJNHLPh2XXZQh1H35fBiHHR2uUyZRRpw==
"@dcspark/cardano-multiplatform-lib-browser@^5.2.0":
version "5.2.0"
resolved "https://registry.yarnpkg.com/@dcspark/cardano-multiplatform-lib-browser/-/cardano-multiplatform-lib-browser-5.2.0.tgz#6d8444c1f5af1afb4d1eb2e6f9342fb4eca51f51"
integrity sha512-zxosWnOZFV+4tHDYOYGR9k2kgMEp87A7PoXjXNdzufzVmT2JqaYAyEXZPQya3GlLfsWl43q/Oaj280b8IJLqcQ==

"@dcspark/carp-client@^2.4.1":
version "2.4.1"
resolved "https://registry.yarnpkg.com/@dcspark/carp-client/-/carp-client-2.4.1.tgz#8e6d88a76cb5410d3cc1536672eab1b238f33fad"
integrity sha512-546kIqq+uMawfMOYtWQeqxfihO/kO00wqmMLRYyl6bpWj6lCaXmlcu2tmGrjbthbqnksVFa79iDn15gGzIG4AA==
"@dcspark/carp-client@^3.1.0":
version "3.1.0"
resolved "https://registry.yarnpkg.com/@dcspark/carp-client/-/carp-client-3.1.0.tgz#983a1bb70dd46b0cba72cb1c75ec9d1377fc1b7b"
integrity sha512-szg0bU7tkOXZpP4i5eXoprTg3921dHAiF9QmY0CXWs101sLNlp+3YHzb1MiZCCFHIkAD1kd6UEx0XmGF566wxw==
dependencies:
axios "^0.27.2"

Expand Down

0 comments on commit da5c9b6

Please sign in to comment.