Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logger hotfix and network deprecation #693

Merged
merged 2 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions client/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,26 @@ export const NETWORKS_INGAME = {
},
};

// Deprectated networks
// status: {deprecated | deprecation-planned}
export const NETWORKS_DEPRECATION = {
GOERLI: {
id: "5",
status: "deprecation-planned",
date: "jan-2024"
},
OPTIMISM_GOERLI: {
id: "420",
status: "deprecation-planned",
date: "jan-2024"
},
ARBITRUM_GOERLI: {
id: "421613",
status: "deprecation-planned",
date: "jan-2024"
}
};

// Web3
export const Web3 = pkgWeb3;

Expand Down
141 changes: 100 additions & 41 deletions client/src/containers/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,26 @@ import parse from "html-react-parser";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { withRouter } from "../hoc/withRouter";
import { randGoodIcon } from "../utils/^^";
import { deployAdminContracts } from '../utils/deploycontract';
import { randGoodIcon, randBadIcon } from "../utils/^^";
import { deployAdminContracts } from "../utils/deploycontract";
import {
networkOnDeprecationOrDeprecated,
isDeprecatedNetwork,
deprecationStatus,
deprecationDate
} from "../utils/networkDeprecation";

class App extends React.Component {
constructor() {
super();
this.state = {
chainId: 0,
};
if (window.ethereum) {
window.ethereum.request({ method: "eth_chainId" }).then((id) => {
this.setState({ chainId: Number(id) });
});
}

// Analytics
ReactGA.initialize(constants.GOOGLE_ANALYTICS_ID);
Expand All @@ -31,7 +45,7 @@ class App extends React.Component {
let target = this.props.levels[0].deployedAddress;
for (let i = 0; i < this.props.levels.length; i++) {
const level = this.props.levels[i];
if (!level.deployedAddress) {
if (!level.deployedAddress) {
return this.props.navigate(`${constants.PATH_LEVEL_ROOT}${i}`);
}
const completed = this.props.completedLevels[level.deployedAddress];
Expand All @@ -54,41 +68,58 @@ class App extends React.Component {

// change the network to Sepolia network
async function switchToSepolia() {
let elements = document.querySelectorAll('.progress-bar-wrapper');
const deployWindow = document.querySelectorAll('.deploy-window-bg');
let elements = document.querySelectorAll(".progress-bar-wrapper");
const deployWindow = document.querySelectorAll(".deploy-window-bg");
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${Number(constants.NETWORKS.SEPOLIA.id).toString(16)}` }],//if on wrong network giving option to switch to sepolia network.
method: "wallet_switchEthereumChain",
params: [
{
chainId: `0x${Number(constants.NETWORKS.SEPOLIA.id).toString(
16
)}`,
},
], //if on wrong network giving option to switch to sepolia network.
});
deployWindow[0].style.display = 'none';
deployWindow[0].style.display = "none";
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
if (switchError.code === 4902) {
try {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
method: "wallet_addEthereumChain",
params: [
{
chainId: [{ chainId: `0x${Number(constants.NETWORKS.SEPOLIA.id).toString(16)}` }]
chainId: [
{
chainId: `0x${Number(
constants.NETWORKS.SEPOLIA.id
).toString(16)}`,
},
],
},
],
});
deployWindow[0].style.display = 'none';
deployWindow[0].style.display = "none";
} catch (addError) {
if (addError.code === 4001) {
//User has rejected changing the request
elements[0].style.display = 'none';
elements[0].style.display = "none";
}
console.error("Can't add nor switch to the selected network")
console.error("Can't add nor switch to the selected network");
}
} else if (switchError.code === 4001) {
//User has rejected changing the request
if (elements[0]) elements[0].style.display = 'none';
if (elements[0]) elements[0].style.display = "none";
}
}
}

async function continueAnyway() {
const deployWindow = document.querySelectorAll(".deploy-window-bg");
deployWindow[0].style.display = "none";
}

return (
<div className="appcontainer">
{/* Parent container */}
Expand Down Expand Up @@ -118,35 +149,49 @@ class App extends React.Component {
</button>
</ul>
</section>
{/* Deploy Window */}
{/*not Deployed window*/}
<div className="deploy-window-bg">
<div className="deploy-window">
<h1>{randGoodIcon()}</h1>
<h1>{strings.deployMessageTitle}</h1>
<br />
{strings.deployMessage}
<ul>
{supportedNetworks.map((network, idx) =>
<li key={idx}>{network}</li>
)}
</ul>
<p className="deploy-note">{strings.deployConfirmation}</p>
<div className="choice-buttons">
<button
className="buttons"
onClick={deployAdminContracts}
>
{strings.deployGame}
</button>
<button
className="buttons"
onClick={switchToSepolia}
>
{strings.switchToSepolia}
</button>
{!networkOnDeprecationOrDeprecated(this.state.chainId) ? (
<div className="deploy-window">
{/*deploy window*/}
<h1>{randGoodIcon()}</h1>
<h1>{strings.deployMessageTitle}</h1>
<br />
{strings.deployMessage}
{supportedNetworksList(supportedNetworks)}
<p className="deploy-note">{strings.deployConfirmation}</p>
<div className="choice-buttons">
<button className="buttons" onClick={deployAdminContracts}>
{strings.deployGame}
</button>
<button className="buttons" onClick={switchToSepolia}>
{strings.switchToSepolia}
</button>
</div>
<p className="deploy-note">{strings.deployNote}</p>
</div>
<p className="deploy-note">{strings.deployNote}</p>
</div>
) : (
<div className="deploy-window">
{/*deprecation window*/}
<h1>{randBadIcon()}</h1>
<h1>
{isDeprecatedNetwork(this.state.chainId)? strings.deprecatedNetwork : strings.networkBeingDeprecated}
</h1>
<br />
{strings.deployMessage}
{supportedNetworksList(supportedNetworks)}
<div className="choice-buttons">
<button className="buttons" onClick={switchToSepolia}>
{strings.switchToSepolia}
</button>
{!isDeprecatedNetwork(this.state.chainId) &&
<button className="buttons" onClick={continueAnyway}>
{strings.continueAnyway}
</button>
}
</div>
</div>
)}
</div>
{/* Levels */}
<Mosaic></Mosaic>
Expand Down Expand Up @@ -176,4 +221,18 @@ function mapDispatchToProps(dispatch) {
return bindActionCreators({}, dispatch);
}

function supportedNetworksList(_supportedNetworks) {
return (
<ul>
{_supportedNetworks.map((network, idx) => (
<li key={idx}>
{network}
{networkOnDeprecationOrDeprecated(constants.NETWORKS[network].id)
&& " (" + deprecationStatus(constants.NETWORKS[network].id) +
" on " + deprecationDate(constants.NETWORKS[network].id) + ")"}
</li>
))}
</ul>)
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
3 changes: 3 additions & 0 deletions client/src/gamedata/ar/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@
"getNewInstance": "احصل على نسخة جديدة",
"deployMessageTitle": "لم يتم نشر اللعبة",
"deployMessage": "تدُعم اللُعبة حاليًا هذه الشبكات فقط:",
"deprecatedNetwork": "شبكة عفا عليها الزمن",
"networkBeingDeprecated":"يتم إهمال الشبكة",
"deployConfirmation": "هل تريد نشر العقود على هذه الشبكة أم التبديل إلى شبكة Sepolia",
"deployNote": "ملاحظة: إذا قمت بنشر جميع المستويات ، فسنرشدك إلى إرسال اللعبة المنشورة بالكامل على هذه الشبكة.",
"deployGame": "نشر اللعبة",
"switchToSepolia": "قم بالتبديل إلى Sepolia",
"deployLevel": "نشر المستوى",
"continueAnyway" : "استمر على أي حال",
"helperDeployAllContracts": "نشر جميع العقود المتبقية على الشبكة الحالية.",
"confirmMainnetDeploy": "أنت على الشبكة الرئيسية ، اللعبة ليس لها قيمة نقدية ، يجب ألا تنشر في هذه الشبكة.",
"submitLevelFooter": "انشر جميع المستويات (publishAllContracts () في الكونسول) لإضافة الشبكة الحالية إلى <a href='https://github.com/OpenZeppelin/ethernaut'> مستودع Github </a> كشبكة جديدة مدعومة.",
Expand Down
3 changes: 3 additions & 0 deletions client/src/gamedata/en/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@
"submitInstance": "Submit instance",
"getNewInstance": "Get new instance",
"deployMessageTitle": "Game not deployed",
"deprecatedNetwork": "Network deprecated",
"networkBeingDeprecated": "Network being deprecated",
"deployMessage": "Currently the game supports only these networks:",
"deployConfirmation": "Do you want to deploy the contracts on this network or switch to the Sepolia network?",
"deployNote": "Note: If you deploy all levels, we'll guide you to submit the whole deployed game on this network.",
"deployGame": "Deploy game",
"switchToSepolia": "Switch to Sepolia",
"continueAnyway" : "Continue anyway",
"deployLevel": "Deploy Level",
"helperDeployAllContracts": "Deploy all the remaining contracts on the current network.",
"confirmMainnetDeploy": "You are on a mainnet, the game has no monetary value, you should not deploy in this network.",
Expand Down
3 changes: 3 additions & 0 deletions client/src/gamedata/es/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@
"submitInstance": "Comprueba instancia",
"getNewInstance": "Nueva instancia",
"deployMessageTitle": "Juego no desplegado",
"deprecatedNetwork": "Red obsoleta",
"networkBeingDeprecated": "Red en desuso",
"deployMessage": "Actualmente, el juego solo es compatible con estas redes.:",
"deployConfirmation": "¿Quieres implementar los contratos en esta red o cambiar a la red Sepolia?",
"deployNote": "Nota: si implementa todos los niveles, lo guiaremos para que envíe todo el juego implementado en esta red.",
"deployGame": "Desplegar juego",
"switchToSepolia": "Cambiar a Sepolia",
"continueAnyway" : "Continuar en esta red",
"deployLevel": "Desplegar implementación",
"helperDeployAllContracts": "Implemente todos los contratos restantes en la red actual.",
"confirmMainnetDeploy": "Estás en una red principal, el juego no tiene valor monetario, no debes implementarlo en esta red.",
Expand Down
3 changes: 3 additions & 0 deletions client/src/gamedata/fr/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@
"submitInstance": "Soumettre une instance",
"getNewInstance": "Créer une nouvelle instance",
"deployMessageTitle": "Jeu non déployé",
"deprecatedNetwork": "Réseau obsolète",
"networkBeingDeprecated": "Réseau désaffecté",
"deployMessage": "Actuellement, le jeu ne prend en charge que ces réseaux:",
"deployConfirmation": "Voulez-vous déployer les contrats sur ce réseau ou passer au réseau Sepolia?",
"deployNote": "Remarque: Si vous déployez tous les niveaux, nous vous guiderons pour soumettre l'ensemble du jeu déployé sur ce réseau.",
"deployGame": "Déploier le jeu",
"switchToSepolia": "Passer à Sepolia",
"continueAnyway" : "Continuer quand même",
"deployLevel": "Déploier le niveau",
"helperDeployAllContracts": "Déployez tous les contrats restants sur le réseau actuel.",
"confirmMainnetDeploy": "Vous êtes sur un MainNet, le jeu n'a pas de valeur monétaire, vous ne devez pas déployer dans ce réseau.",
Expand Down
3 changes: 3 additions & 0 deletions client/src/gamedata/ja/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@
"getNewInstance": "インスタンスの生成",
"deployMessageTitle": "ゲームが展開されていません",
"deployMessage": "現在、ゲームはこれらのネットワークのみをサポートしています:",
"deprecatedNetwork": "ネットワークは放棄されています",
"networkBeingDeprecated": "将来的には、ネットワークは使用できなくなります。",
"deployConfirmation": "コントラクトをこのネットワークに展開しますか、それとも Sepolia ネットワークに切り替えますか?",
"deployNote": "注: すべてのレベルを展開する場合は、展開されたゲーム全体をこのネットワークに送信するように案内されます。",
"deployGame": "ゲームを展開する",
"switchToSepolia": "Sepolia 切り替える",
"deployLevel": "配備レベル",
"continueAnyway" : "とにかく続けます",
"helperDeployAllContracts": "残りのすべてのコントラクトを現在のネットワークにデプロイします。",
"confirmMainnetDeploy": "あなたはメインネット上にいます。ゲームには金銭的価値がありません。このネットワークに展開するべきではありません",
"submitLevelFooter": "すべてのレベルをデプロイ (コンソールで deployAllContracts()) して、現在のネットワークを新しいサポート対象ネットワークとして <a href='https://github.com/OpenZeppelin/ethernaut'>Github リポジトリ</a> に追加します。",
Expand Down
20 changes: 20 additions & 0 deletions client/src/gamedata/pt_br/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@
"sources": "Código",
"submitInstance": "Enviar instância",
"getNewInstance": "Obter nova instância",
"deployMessageTitle": "Jogo não implantado",
"deprecatedNetwork": "Rede obsoleta",
"networkBeingDeprecated": "Rede sendo obsoleta",
"deployMessage": "Atualmente o jogo suporta apenas estas redes:",
"deployConfirmation": "Deseja implantar os contratos nesta rede ou mudar para a rede Sepolia?",
"deployNote": "Observação: se você implantar todos os níveis, orientaremos você a enviar todo o jogo implantado nesta rede.",
"deployGame": "Implantar jogo",
"switchToSepolia": "Mudar para Sepolia",
"continueAnyway" : "Continue de qualquer maneira",
"deployLevel": "Implantar nível",
"helperDeployAllContracts": "Implante todos os contratos restantes na rede atual.",
"confirmMainnetDeploy": "Você está em uma rede principal, o jogo não tem valor monetário, você não deve implantar nesta rede.",
"submitLevelFooter": "Implante todos os níveis (deployAllContracts() no console) para adicionar a rede atual ao nosso <a href='https://github.com/OpenZeppelin/ethernaut'>repositório GitHub</a> como uma nova rede suportada.",
"submitGameFooter": "Incrível! O jogo inteiro está implantado nesta rede. Clique aqui para levantar um problema no GitHub e enviá-lo para nós :)",
"nextLevel": "Vá para o próximo nível",
"uLevels": "Níveis",
"lLevels": "níveis",
Expand All @@ -39,6 +53,8 @@
"lCreated": "criado",
"instance": "Instância",
"numberOf": "Número de ",
"warning": "Aviso",
"warningMessage": "Não há provedor web3 e o jogo está no modo somente leitura",
"levelAuthor": "Autor(es) do nível:",
"pleaseWait": "POR FAVOR, AGUARDE",
"donate": "Esse nível te ensinou algo útil? Doe para o autor do nível (na mainnet):",
Expand Down Expand Up @@ -88,6 +104,10 @@
"troubleshooting": "Às vezes \n\n(a) o estado do aplicativo ou (b) o estado do plugin do MetaMask \n\npode ficar um pouco confuso, especialmente depois de trocar de rede, desbloquear, etc. Se o que você está vendo não faz muito sentido, tente atualizar o aplicativo, desabilitar e habilitar seu plugin metamask ou até mesmo reiniciar seu navegador. \n\nSe você encontrar problemas, por favor nos informe em [email protected]",
"poweredBy": "powered by ",
"setupMetamask": "Se você ainda não tem, instale o [MetaMask browser extension](https://metamask.io/) (no Chrome, Firefox, Brave ou Opera em seu computador). \n\nConfigure a carteira da extensão e use o seletor de rede para apontar para a rede preferida no canto superior esquerdo da interface da extensão. Alternativamente, você pode usar o botão para alternar entre as redes. Se você selecionar uma rede não suportada, o jogo irá notificá-lo e levá-lo para o Sepolia testnet padrão. \n\nUma vez feito, volte aqui e recarregue a página",
"FifthyPercentMessage": "Otimo trabalho! Você está na metade do Ethernaut e está ficando muito bom em quebrar coisas. Trabalhar como pesquisador de segurança Blockchain na OpenZeppelin pode ser divertido... https://grnh.se/fdbf1c043us",
"SeventyFivePercentMessage": "75%: Bom trabalho, já... você está bem fundo na toca do coelho agora... quem sabe aonde isso o levará... https://grnh.se/d4a786e43us",
"NinetyPercentMessage": "90%: Você está quase lá! Faltam apenas mais alguns desafios até você completar o Ethernaut! Você já considerou uma carreira em Segurança Blockchain?https://grnh.se/cfcca8c83us",
"HundredPercentMessage": "100%: Parabéns! Sua jornada pela toca do coelho web3 é impressionante e deve ser comemorada! Agora você tem as habilidades necessárias para quebrar contratos inteligentes! O que vem a seguir daqui em diante? Inscreva-se para ser um pesquisador de segurança Blockchain na OpenZeppelin e contribua para proteger os principais protocolos da web3! https://grnh.se/26c05aac3us",
"Menu": "Menu",
"Networks": "Redes",
"Languages": "línguas",
Expand Down
3 changes: 3 additions & 0 deletions client/src/gamedata/ru/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@
"submitInstance": "Отправить инстанс на проверку",
"getNewInstance": "Создать новый инстанс",
"deployMessageTitle": "Игра не развернута",
"deprecatedNetwork": "заброшенная сеть",
"networkBeingDeprecated": "сеть в процессе закрытия",
"deployMessage": "На данный момент игра поддерживает только эти сети:",
"deployConfirmation": "Вы хотите развернуть контракты в этой сети или переключиться на сеть Sepolia??",
"deployNote": "Примечание. Если вы развернете все уровни, мы посоветуем вам отправить всю развернутую игру в эту сеть.",
"deployGame": "Развернуть игру",
"switchToSepolia": "Переключиться на Sepolia",
"continueAnyway" : "Продолжай в любом случае",
"deployLevel": "Уровень развертывания",
"helperDeployAllContracts": "Разверните все оставшиеся контракты в текущей сети.",
"confirmMainnetDeploy": "Вы находитесь в основной сети, игра не имеет денежной стоимости, вам не следует развертывать ее в этой сети.",
Expand Down
Loading