Skip to content

Commit

Permalink
fix: fix bug
Browse files Browse the repository at this point in the history
  • Loading branch information
TiyoSheng committed Nov 8, 2023
1 parent 875ab24 commit 4a83813
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 50 deletions.
24 changes: 12 additions & 12 deletions packages/client/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ setup().then(async (result) => {
<App />
</MUDProvider>
);
// const { mount: mountDevTools } = await import("@latticexyz/dev-tools");
// mountDevTools({
// config: mudConfig,
// publicClient: network.publicClient,
// walletClient: network.walletClient,
// latestBlock$: network.latestBlock$,
// blockStorageOperations$: network.blockStorageOperations$,
// worldAddress: network.worldContract.address,
// worldAbi: network.worldContract.abi,
// write$: network.write$,
// recsWorld: network.world,
// });
const { mount: mountDevTools } = await import("@latticexyz/dev-tools");
mountDevTools({
config: mudConfig,
publicClient: network.publicClient,
walletClient: network.walletClient,
latestBlock$: network.latestBlock$,
blockStorageOperations$: network.blockStorageOperations$,
worldAddress: network.worldContract.address,
worldAbi: network.worldContract.abi,
write$: network.write$,
recsWorld: network.world,
});
});
38 changes: 38 additions & 0 deletions packages/client/src/mud/createSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { SetupNetworkResult } from "./setupNetwork";
import { singletonEntity, encodeEntity } from "@latticexyz/store-sync/recs";
import { message } from 'antd';

let wait = false;

export type SystemCalls = ReturnType<typeof createSystemCalls>;

export function createSystemCalls(
Expand All @@ -18,14 +20,18 @@ export function createSystemCalls(
};

const move = async (steps: any) => {
if (wait) return
wait = true
console.log('move', new Date().getTime());
try {
const tx = await worldContract.write.move([steps]);
await waitForTransaction(tx);
console.log('move success', new Date().getTime(), tx);
wait = false
} catch (error) {
console.log('move', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}

// return getComponentValue(Player, singletonEntity);
Expand Down Expand Up @@ -63,31 +69,39 @@ export function createSystemCalls(
}

const battleInvitation = async (addr: any, steps: any) => {
if (wait) return
wait = true
console.log('battleInvitation', new Date().getTime());
try {
const tx = await worldContract.write.battleInvitation([addr, steps]);
await waitForTransaction(tx);
console.log('battleInvitation success', new Date().getTime(), tx);
wait = false
return tx
} catch (error) {
console.log('battleInvitation', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}
}

const confirmBattle = async (buffHash: any, battleId: any) => {
if (wait) return
wait = true
console.log('confirmBattle', new Date().getTime());
try {
const tx = await worldContract.write.confirmBattle([buffHash, battleId]);
await waitForTransaction(tx);
console.log('confirmBattle success', new Date().getTime(), tx);
wait = false
return {
type: 'success',
data: getComponentValue(BattleList, encodeEntity({ battleId: "uint256" }, { battleId: battleId}))
}
} catch (error) {
console.log('confirmBattle', error);
message.error(error.cause.reason || error.cause.details);
wait = false
return {
type: 'error',
msg: error.cause.reason || error.cause.details || error.cause
Expand All @@ -97,18 +111,22 @@ export function createSystemCalls(
}

const revealBattle = async (battleId: any, action: any, arg: any, nonce: any) => {
if (wait) return
wait = true
console.log('revealBattle', new Date().getTime());
try {
const tx = await worldContract.write.revealBattle([battleId, action, arg, nonce]);
await waitForTransaction(tx);
console.log('revealBattle success', new Date().getTime(), tx);
wait = false
return {
type: 'success',
data: getComponentValue(BattleList, encodeEntity({ battleId: "uint256" }, { battleId: battleId}))
}
} catch (error) {
console.log('revealBattle', error);
message.error(error.cause.reason || error.cause.details);
wait = false
return {
type: 'error',
msg: error.cause.reason || error.cause.details || error.cause
Expand Down Expand Up @@ -161,37 +179,49 @@ export function createSystemCalls(
}

const openBox = async (boxId: any) => {
if (wait) return
wait = true
console.log('openBox', new Date().getTime());
try {
const tx = await worldContract.write.openBox([boxId]);
await waitForTransaction(tx);
console.log('openBox success', new Date().getTime(), tx);
wait = false
} catch (error) {
console.log('openBox', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}
}

const revealBox = async (boxId: any) => {
if (wait) return
wait = true
console.log('revealBox', new Date().getTime());
try {
const tx = await worldContract.write.revealBox([boxId]);
await waitForTransaction(tx);
console.log('revealBox success', new Date().getTime(), tx);
wait = false
return getComponentValue(BoxList, encodeEntity({ boxId: "uint256" }, { boxId: boxId}));
} catch (error) {
console.log('revealBox', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}
}

const getCollections = async (boxId: any, oreAmount: any, treasureAmount: any) => {
if (wait) return
wait = true
try {
const tx = await worldContract.write.getCollections([boxId, oreAmount, treasureAmount]);
await waitForTransaction(tx);
wait = false
} catch (error) {
console.log('getCollections', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}
}

Expand Down Expand Up @@ -219,28 +249,36 @@ export function createSystemCalls(
}

const initUserInfo = async () => {
if (wait) return
wait = true
console.log('initUserInfo', new Date().getTime());
try {
const tx = await worldContract.write.initUserInfo();
await waitForTransaction(tx);
console.log('initUserInfo success', new Date().getTime(), tx);
wait = false
return tx
} catch (error) {
console.log('initUserInfo', error);
message.error(error.cause.reason || error.cause.details);
wait = false
}
}

const forceEnd = async (battleId: any) => {
if (wait) return
wait = true
console.log('forceEnd', new Date().getTime());
try {
const tx = await worldContract.write.forceEnd([battleId]);
await waitForTransaction(tx);
console.log('forceEnd success', new Date().getTime(), tx);
wait = false
return getComponentValue(BattleList, encodeEntity({ battleId: "uint256" }, { battleId: battleId}))
} catch (error) {
console.log('forceEnd', error);
// message.error(error.cause.reason || error.cause.details);
wait = false
}
}

Expand Down
6 changes: 2 additions & 4 deletions packages/client/src/pages/game/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ const Game = () => {
timeout = setTimeout(() => {
unlockUserLocation();
timeout = null
}, 5000);
}, 23000);
}
setTargetPlayer(null);
} else {
Expand Down Expand Up @@ -349,9 +349,7 @@ const Game = () => {
}

const showUserInfo = async (player) => {
if (player.addr.toLocaleLowerCase() == account.toLocaleLowerCase()) {
if (curPlayer) player = curPlayer
} else {
if (!player.userUrl || !player.lootUrl) {
let addon = getComponentValue(PlayerAddon, encodeEntity({addr: "address"}, {addr: player.addr}))
console.log(addon)
let userTokenId = addon.userId.toString()
Expand Down
99 changes: 65 additions & 34 deletions packages/client/src/pages/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import { delay } from '@/utils';
import { useMUD } from '@/mud/MUDContext';
import { useEntityQuery } from "@latticexyz/react";
import { Has, getComponentValue } from '@latticexyz/recs';
import { decodeEntity } from "@latticexyz/store-sync/recs";
import { decodeEntity, encodeEntity } from "@latticexyz/store-sync/recs";
import { ethers } from 'ethers';

import indexDuckImg from '@/assets/img/duck_index.png';

import lootAbi from '../../../../contracts/out/Loot.sol/MLoot.abi.json'
import userAbi from '../../../../contracts/out/User.sol/MUser.abi.json'
import pluginAbi from '../../../../contracts/out/Plugin.sol/MPlugin.abi.json'
import { async } from 'rxjs';

let userContract: any
let lootContract: any
Expand All @@ -34,7 +35,7 @@ let transfering = false
const Home = () => {
const [messageApi, contextHolder] = message.useMessage();
const {
components: { GlobalConfig, Player },
components: { GlobalConfig, Player, LootList1, PlayerAddon },
systemCalls: { selectBothNFT, joinBattlefield, setInfo, initUserInfo },
network
} = useMUD();
Expand All @@ -49,29 +50,6 @@ const Home = () => {

const navigate = useNavigate();

useEffect(() => {
getBalance()
let worldContractAddress = localStorage.getItem('worldContractAddress') || ''
if (worldContractAddress && network.worldContract.address.toLocaleLowerCase() == worldContractAddress.toLocaleLowerCase()) {
let playerInfo = localStorage.getItem('playerInfo');
if (playerInfo) playerInfo = JSON.parse(playerInfo);
if (playerInfo.state >= 1 && playerInfo && playerInfo.username) {
setUsername(playerInfo.username);
setClothes(playerInfo.clothes);
setHandheld(playerInfo.handheld);
setHead(playerInfo.head);
setUserUrl(playerInfo.userUrl);
setLootUrl(playerInfo.lootUrl);
setPlayer(playerInfo);
setStep('mint');
}
}
// const address = localStorage.getItem(UserAddressKey);
// if (address) {
// setWalletAddress(address);
// }
}, []);

const [clothes, setClothes] = useState<string>();
const [handheld, setHandheld] = useState<string>();
const [head, setHead] = useState<string>();
Expand All @@ -80,17 +58,36 @@ const Home = () => {
const [lootUrl, setLootUrl] = useState<string>();
const [player, setPlayer] = useState<any>();

const LootList1Data = useEntityQuery([Has(LootList1)]).map((entity) => {
const loot = getComponentValue(LootList1, entity);
const address = decodeEntity({ addr: "address" }, entity)?.addr?.toLocaleLowerCase() || ''
loot.addr = address
return loot;
})

const players = useEntityQuery([Has(Player)]).map((entity) => {
const address = decodeEntity({ addr: "address" }, entity)?.addr?.toLocaleLowerCase() || ''
const player = getComponentValue(Player, entity);
player.addr = address
LootList1Data.forEach((item) => {
if (item.addr.toLocaleLowerCase() === address.toLocaleLowerCase()) {
let clothes = item.chest.replace(/"(.*?)"/, '').split(' of')[0].replace(/^\s+|\s+$/g,"")
let handheld = item.weapon.replace(/"(.*?)"/, '').split(' of')[0].replace(/^\s+|\s+$/g,"")
let head = item.head.replace(/"(.*?)"/, '').split(' of')[0].replace(/^\s+|\s+$/g,"")
player.equip = {
clothes,
handheld,
head,
}
}
})
return player;
})

const curPlayer = players.find(player => player.addr.toLocaleLowerCase() == network?.account.toLocaleLowerCase());

const GlobalConfigData = useEntityQuery([Has(GlobalConfig)]).map((entity) => getComponentValue(GlobalConfig, entity));
console.log(GlobalConfigData, 'GlobalConfigData')
// console.log(GlobalConfigData, 'GlobalConfigData')

if (GlobalConfigData.length && GlobalConfigData[0].userContract) {
let privateKey = network.privateKey
Expand Down Expand Up @@ -125,6 +122,47 @@ const Home = () => {
pluginContract = new ethers.Contract(pluginContractAddress, pluginAbi, wallet)
}

const atobUrl = (url) => {
url = url.replace('data:application/json;base64,', '')
url = atob(url)
url = JSON.parse(url)
return url
}

console.log(curPlayer, 'curPlayer', players)

useEffect(() => {
getBalance()
async function init() {
if (curPlayer?.state >= 1 && curPlayer?.name) {
let addon = getComponentValue(PlayerAddon, encodeEntity({addr: "address"}, {addr: curPlayer.addr}))
let userTokenId = addon.userId.toString()
let lootTokenId = addon.lootId.toString()

let urls = await Promise.all([userContract.tokenURI(userTokenId), lootContract.tokenURI(lootTokenId)])
let url = urls[0]
let lootUrl = urls[1]
url = atobUrl(url)
lootUrl = atobUrl(lootUrl)
curPlayer.userUrl = url.image
curPlayer.lootUrl = lootUrl.image
setUsername(curPlayer.name);
setClothes(curPlayer?.equip?.clothes);
setHandheld(curPlayer?.equip?.handheld);
setHead(curPlayer?.equip?.head);
setUserUrl(curPlayer.userUrl);
setLootUrl(curPlayer.lootUrl);
setPlayer(curPlayer);
setStep('mint');
}
}
init()
// const address = localStorage.getItem(UserAddressKey);
// if (address) {
// setWalletAddress(address);
// }
}, [curPlayer]);

const createWallet = () => {
setModalVisible(true);
}
Expand Down Expand Up @@ -164,13 +202,6 @@ const Home = () => {
})
}

const atobUrl = (url) => {
url = url.replace('data:application/json;base64,', '')
url = atob(url)
url = JSON.parse(url)
return url
}

const toObject = (obj) => {
return JSON.parse(JSON.stringify(obj, (key, value) => typeof value === 'bigint' ? value.toString() : value
))
Expand Down Expand Up @@ -219,7 +250,7 @@ const Home = () => {

let player = Object.assign(playerData, {username, clothes, handheld, head, userUrl: url.image, lootUrl: lootUrl.image})
console.log(player, 'player')
localStorage.setItem('playerInfo', JSON.stringify(toObject(player)));
// localStorage.setItem('playerInfo', JSON.stringify(toObject(player)));

let result = await Promise.all([setInfo(username, ''), joinBattlefield()])
console.log(result, 'result')
Expand Down

0 comments on commit 4a83813

Please sign in to comment.