diff --git a/.all-contributorsrc b/.all-contributorsrc index 43daaa81953..5f412e70f8a 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -12479,6 +12479,15 @@ "contributions": [ "content" ] + }, + { + "login": "nipunh", + "name": "Nipun Hedaoo", + "avatar_url": "https://avatars.githubusercontent.com/u/26524611?v=4", + "profile": "https://github.com/nipunh", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/.env.example b/.env.example index d1736aa8df1..bc6e44826d9 100644 --- a/.env.example +++ b/.env.example @@ -35,9 +35,5 @@ BUILD_LOCALES= # fixed number of CPUs (e.g. 2) to limit the demand during build time LIMIT_CPUS= -# Sentry auth token required for error tracking -SENTRY_AUTH_TOKEN= -NEXT_PUBLIC_SENTRY_DSN= - # Enables the bundle analyzer ANALYZE=false \ No newline at end of file diff --git a/README.md b/Adding that improves clarity README.md similarity index 99% rename from README.md rename to Adding that improves clarity README.md index 782c6ed0cfe..229775bb059 100644 --- a/README.md +++ b/Adding that improves clarity README.md @@ -119,7 +119,7 @@ git push - In your PR description, reference the issue it resolves (see [linking a pull request to an issue using a keyword](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword)) - ex. `Updates out of date content [Fixes #1234]` - Netlify (our hosting service for build previews) deploys all PRs to a publicly accessible preview URL, e.g.: ![Netlify deploy preview](public/images/preview-deploy.png) -- _Confirm your Netlify preview deploy looks & functions as expected_ +- _Confirm that your Netlify preview deploy looks and functions as expected_ - Why not say hi and draw attention to your PR in [our discord server](https://discord.gg/ethereum-org)? ### 6. Wait for review @@ -1908,6 +1908,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d Mako Shan
Mako Shan

🖋 Christina
Christina

🖋 + Nipun Hedaoo
Nipun Hedaoo

💻 diff --git a/instrumentation.ts b/instrumentation.ts deleted file mode 100644 index 72dc765734d..00000000000 --- a/instrumentation.ts +++ /dev/null @@ -1,28 +0,0 @@ -import * as Sentry from "@sentry/nextjs" - -export async function register() { - const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN - - if (!dsn) { - console.warn("Sentry DSN not found, skipping") - return - } - - const commonSentryOptions = { - dsn, - enabled: process.env.NODE_ENV === "production", - tracesSampleRate: 1.0, - } - - if (process.env.NEXT_RUNTIME === "nodejs") { - Sentry.init({ - ...commonSentryOptions, - }) - } - - if (process.env.NEXT_RUNTIME === "edge") { - Sentry.init({ - ...commonSentryOptions, - }) - } -} diff --git a/next.config.js b/next.config.js index 07130fe114d..886870c1b02 100644 --- a/next.config.js +++ b/next.config.js @@ -1,6 +1,5 @@ /* eslint-disable @typescript-eslint/no-var-requires */ const { PHASE_DEVELOPMENT_SERVER } = require("next/constants") -const { withSentryConfig } = require("@sentry/nextjs") const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true", @@ -27,7 +26,7 @@ module.exports = (phase, { defaultConfig }) => { let nextConfig = { ...defaultConfig, reactStrictMode: true, - webpack: (config, { webpack }) => { + webpack: (config) => { config.module.rules.push({ test: /\.ya?ml$/, use: "yaml-loader", @@ -58,17 +57,6 @@ module.exports = (phase, { defaultConfig }) => { // Modify the file loader rule to ignore *.svg, since we have it handled now. fileLoaderRule.exclude = /\.svg$/i - // Tree shake Sentry debug code - // ref. https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-with-nextjs - config.plugins.push( - new webpack.DefinePlugin({ - __SENTRY_DEBUG__: false, - __RRWEB_EXCLUDE_IFRAME__: true, - __RRWEB_EXCLUDE_SHADOW_DOM__: true, - __SENTRY_EXCLUDE_REPLAY_WORKER__: true, - }) - ) - return config }, i18n, @@ -76,12 +64,6 @@ module.exports = (phase, { defaultConfig }) => { images: { deviceSizes: [640, 750, 828, 1080, 1200, 1504, 1920], }, - env: { - NEXT_PUBLIC_CONTEXT: process.env.CONTEXT, - }, - experimental: { - instrumentationHook: true, - }, } if (phase !== PHASE_DEVELOPMENT_SERVER) { @@ -110,15 +92,5 @@ module.exports = (phase, { defaultConfig }) => { } } - return withBundleAnalyzer( - withSentryConfig(nextConfig, { - // TODO: temp config, update this to the correct org & project - org: "ethereumorg-ow", - project: "javascript-nextjs", - authToken: process.env.SENTRY_AUTH_TOKEN, - release: `${process.env.BUILD_ID}_${process.env.REVIEW_ID}`, - disableLogger: true, - silent: true, - }) - ) + return withBundleAnalyzer(nextConfig) } diff --git a/package.json b/package.json index 0959863ebe9..dba17923e31 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ethereum-org-website", - "version": "8.10.1", + "version": "9.0.0", "license": "MIT", "private": true, "scripts": { @@ -48,7 +48,6 @@ "@radix-ui/react-switch": "^1.1.0", "@radix-ui/react-tooltip": "^1.1.2", "@radix-ui/react-visually-hidden": "^1.1.0", - "@sentry/nextjs": "^8.19.0", "@socialgouv/matomo-next": "^1.8.0", "chart.js": "^4.4.2", "chartjs-plugin-datalabels": "^2.2.0", @@ -64,7 +63,7 @@ "lodash.merge": "^4.6.2", "lodash.shuffle": "^4.2.0", "lodash.union": "^4.6.0", - "next": "^14.2.3", + "next": "^14.2.10", "next-i18next": "^14.0.3", "next-mdx-remote": "^3.0.8", "next-sitemap": "^4.2.3", @@ -82,7 +81,9 @@ "react-select": "5.8.0", "reading-time": "^1.5.0", "remark-gfm": "^3.0.1", + "swiper": "^11.1.10", "tailwind-merge": "^2.3.0", + "tailwind-variants": "^0.2.1", "tailwindcss-animate": "^1.0.7", "usehooks-ts": "^3.1.0", "yaml-loader": "^0.8.0" @@ -104,6 +105,8 @@ "@types/node": "^20.4.2", "@types/react": "18.2.57", "@types/react-dom": "18.2.19", + "@types/swiper": "^6.0.0", + "@types/xml2js": "^0.4.14", "@typescript-eslint/eslint-plugin": "^6.19.0", "@typescript-eslint/parser": "^6.19.0", "autoprefixer": "^10.4.19", @@ -133,7 +136,8 @@ "tsconfig-paths-webpack-plugin": "4.1.0", "typescript": "^5.5.2", "unified": "^10.0.0", - "unist-util-visit": "^5.0.0" + "unist-util-visit": "^5.0.0", + "xml2js": "^0.6.2" }, "resolutions": { "jackspeak": "2.1.1", diff --git a/public/content/about/index.md b/public/content/about/index.md index b52c09d9622..4eea5278db9 100644 --- a/public/content/about/index.md +++ b/public/content/about/index.md @@ -8,6 +8,8 @@ lang: en ethereum.org is a public, open-source resource for the Ethereum community that anyone can contribute to. We have a small core team dedicated to maintaining and developing the site with contributions from thousands of community members across the globe. +**Nobody from ethereum.org will ever contact you. Do not respond.** + ## A note on names {#a-note-on-names} It's common for people to confuse names within the Ethereum landscape, which can lead to poor mental models about how Ethereum works. Here's a quick explainer to clear things up: diff --git a/public/content/community/support/index.md b/public/content/community/support/index.md index c611b14165e..9a1ee1f0498 100644 --- a/public/content/community/support/index.md +++ b/public/content/community/support/index.md @@ -10,7 +10,7 @@ lang: en Are you looking for the official Ethereum support? The first thing you should know is that Ethereum is decentralized. This means no central organization, entity, or person owns Ethereum, and because of this, no official support channels exist. -Understanding the decentralized nature of Ethereum is vital because anyone claiming to be official support for Ethereum is probably trying to scam you! The best protection against scammers is educating yourself and taking security seriously. +Understanding the decentralized nature of Ethereum is vital because **anyone claiming to be official support for Ethereum is probably trying to scam you!** The best protection against scammers is educating yourself and taking security seriously. Ethereum security and scam prevention diff --git a/public/content/contributing/index.md b/public/content/contributing/index.md index 7897ae56553..2d680b80ce9 100644 --- a/public/content/contributing/index.md +++ b/public/content/contributing/index.md @@ -68,7 +68,7 @@ Before contributing, make sure you're familiar with: - our [style guide](/contributing/style-guide/) - our [code of conduct](/community/code-of-conduct) - + ## How decisions about the site are made {#how-decisions-about-the-site-are-made} diff --git a/public/content/contributing/translation-program/content-buckets/index.md b/public/content/contributing/translation-program/content-buckets/index.md index b5fbeace07c..ba38f7ffb97 100644 --- a/public/content/contributing/translation-program/content-buckets/index.md +++ b/public/content/contributing/translation-program/content-buckets/index.md @@ -341,7 +341,6 @@ Below is a breakdown of the website pages each content bucket contains. - [Set up web3.js to use the Ethereum blockchain in JavaScript](/developers/tutorials/set-up-web3js-to-use-ethereum-in-javascript/) - [Short ABIs for calldata optimization](/developers/tutorials/short-abi/) - [Smart contract security guidelines](/developers/tutorials/smart-contract-security-guidelines/) -- [Solidity and Truffle continuous integration setup](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) - [Testing ERC-20 tokens with Waffle](/developers/tutorials/testing-erc-20-tokens-with-waffle/) - [Token integration checklist](/developers/tutorials/token-integration-checklist/) - [Using WebSockets](/developers/tutorials/using-websockets/) diff --git a/public/content/dao/index.md b/public/content/dao/index.md index 6fc2f53630a..8d2f224a06a 100644 --- a/public/content/dao/index.md +++ b/public/content/dao/index.md @@ -1,5 +1,5 @@ --- -title: Decentralized autonomous organizations (DAOs) +title: What is a DAO? | Decentralized Autonomous Organizations description: An overview of DAOs on Ethereum lang: en template: use-cases diff --git a/public/content/defi/index.md b/public/content/defi/index.md index 50c42acc22f..dd88a121178 100644 --- a/public/content/defi/index.md +++ b/public/content/defi/index.md @@ -1,5 +1,5 @@ --- -title: Decentralized finance (DeFi) +title: What is DeFi? | Benefits and Use of Decentralised Finance description: An overview of DeFi on Ethereum lang: en template: use-cases diff --git a/public/content/desci/index.md b/public/content/desci/index.md index 4b358b03fa7..1abd03ddb7b 100644 --- a/public/content/desci/index.md +++ b/public/content/desci/index.md @@ -127,6 +127,7 @@ We welcome suggestions for new projects to list - please look at our [listing po - [DeSci: The Future of Research by Samuel Akinosho](https://lucidsamuel.medium.com/desci-the-future-of-research-b76cfc88c8ec) - [Science Funding (Epilogue: DeSci and new crypto primitives) by Nadia](https://nadia.xyz/science-funding) - [Decentralisation is Disrupting Drug Development](https://medium.com/id-theory/decentralisation-is-disrupting-drug-development-28b5ba5d447f) +- [What Is DeSci – Decentralized Science?](​https://usadailytimes.com/2022/09/12/what-is-desci-decentralized-science/) ### Videos {#videos} @@ -135,3 +136,4 @@ We welcome suggestions for new projects to list - please look at our [listing po - [Scientific Publishing Is Broken. Can Web3 Fix It?](https://www.youtube.com/watch?v=WkvzYgCvWj8) - [Juan Benet - DeSci, Independent Labs, & Large Scale Data Science](https://www.youtube.com/watch?v=zkXM9H90g_E) - [Sebastian Brunemeier - How DeSci Can Transform Biomedical Research & Venture Capital](https://www.youtube.com/watch?v=qB4Tc3FcVbM) +- [Paige Donner - Tooling Open Science with Web3 & The Blockchain](https://www.youtube.com/watch?v=nC-2QWQ-lgw&t=17s) diff --git a/public/content/developers/docs/bridges/index.md b/public/content/developers/docs/bridges/index.md index fe97e455db5..401c64f072c 100644 --- a/public/content/developers/docs/bridges/index.md +++ b/public/content/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ If a dapp goes down the route of integrating a bridge or an aggregator, there ar ### Deploying a dapp on multiple chains {#deploying-a-dapp-on-multiple-chains} -To deploy a dapp on multiple chains, developers can use development platforms like [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/), etc. Typically, these platforms come with composable plugins that can enable dapps to go cross-chain. For instance, developers can use a deterministic deployment proxy offered by the [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy). +To deploy a dapp on multiple chains, developers can use development platforms like [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/), etc. Typically, these platforms come with composable plugins that can enable dapps to go cross-chain. For instance, developers can use a deterministic deployment proxy offered by the [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy). #### Examples: diff --git a/public/content/developers/docs/development-networks/index.md b/public/content/developers/docs/development-networks/index.md index 9e7c76efc66..73e7cad8d4e 100644 --- a/public/content/developers/docs/development-networks/index.md +++ b/public/content/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ You _could_ [run a node](/developers/docs/nodes-and-clients/#running-your-own-no **Note**: Most [development frameworks](/developers/docs/frameworks/) include a built-in development network. We recommend starting with a framework to [set up your local development environment](/developers/local-environment/). -### Ganache {#ganache} - -Quickly fire up a personal Ethereum blockchain which you can use to run tests, execute commands, and inspect state while controlling how the chain operates. - -Ganache provides both a desktop application (Ganache UI), as well as a command-line tool (`ganache-cli`). It is part of the Truffle suite of tools. - -- [Website](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentation](https://www.trufflesuite.com/docs/ganache/overview) - ### Hardhat Network {#hardhat-network} A local Ethereum network designed for development. It allows you to deploy your contracts, run your tests and debug your code. diff --git a/public/content/developers/docs/frameworks/index.md b/public/content/developers/docs/frameworks/index.md index fd16ca308d5..cfe144acf6a 100644 --- a/public/content/developers/docs/frameworks/index.md +++ b/public/content/developers/docs/frameworks/index.md @@ -113,12 +113,6 @@ Before diving into frameworks, we recommend you first read through our introduct - [GitHub](https://github.com/eth-brownie/brownie) - **Brownie is currently unmaintained** -**Truffle -** **_A development environment, testing framework, build pipeline, and other tools._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **Truffle development has ended** - [read more](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK -** **_The Ultimate Smart Contract Toolkit: A suite of tools to help you develop, compile, upgrade, deploy and interact with smart contracts._** - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/developers/docs/gas/index.md b/public/content/developers/docs/gas/index.md index 2b6cedb16c8..36b1f4a7776 100644 --- a/public/content/developers/docs/gas/index.md +++ b/public/content/developers/docs/gas/index.md @@ -1,5 +1,5 @@ --- -title: Gas and fees +title: "Ethereum gas and fees: technical overview" description: lang: en --- diff --git a/public/content/developers/docs/mev/index.md b/public/content/developers/docs/mev/index.md index 24e43688d7d..b368dfc1b19 100644 --- a/public/content/developers/docs/mev/index.md +++ b/public/content/developers/docs/mev/index.md @@ -52,7 +52,7 @@ It works like this: if two DEXes are offering a token at two different prices, s Lending protocol liquidations present another well-known MEV opportunity. -Lending protocols like Maker and Aave require users to deposit some collateral (e.g. ETH). This deposited collateral is then used to then lend out to other users. +Lending protocols like Maker and Aave require users to deposit some collateral (e.g. ETH). This deposited collateral is then used to lend out to other users. Users can then borrow assets and tokens from others depending on what they need (e.g. you might borrow MKR if you want to vote in a MakerDAO governance proposal) up to a certain percentage of their deposited collateral. For example, if the borrowing amount is a maximum of 30%, a user who deposits 100 DAI into the protocol can borrow up to 30 DAI worth of another asset. The protocol determines the exact borrowing power percentage. @@ -122,7 +122,7 @@ As explained, MEV has negative implications for overall user experience and cons In post-Merge Ethereum, validators (having made security deposits of 32 ETH) come to consensus on the validity of blocks added to the Beacon Chain. Since 32 ETH may be out of the reach of many, [joining a staking pool](/staking/pools/) may be a more feasible option. Nevertheless, a healthy distribution of [solo stakers](/staking/solo/) is ideal, as it mitigates the centralization of validators and improves Ethereum’s security. -However, MEV extraction is believed to be capable of accelerating validator centralization. This is partly because, as validators [earn less for proposing blocks](/roadmap/merge/issuance/#how-the-merge-impacts-ETH-supply) than miners previous did, MEV extraction has greatly [influence validator earnings](https://github.com/flashbots/eth2-research/blob/main/notebooks/mev-in-eth2/eth2-mev-calc.ipynb) since The Merge. +However, MEV extraction is believed to be capable of accelerating validator centralization. This is partly because, as validators [earn less for proposing blocks](/roadmap/merge/issuance/#how-the-merge-impacts-ETH-supply) than miners previously did, MEV extraction has greatly [influenced validator earnings](https://github.com/flashbots/eth2-research/blob/main/notebooks/mev-in-eth2/eth2-mev-calc.ipynb) since [The Merge](/roadmap/merge/). Larger staking pools will likely have more resources to invest in necessary optimizations to capture MEV opportunities. The more MEV these pools extract, the more resources they have to improve their MEV-extraction capabilities (and increase overall revenue), essentially creating [economies of scale](https://www.investopedia.com/terms/e/economiesofscale.asp#). @@ -136,13 +136,13 @@ In response to sandwiching and frontrunning attacks, traders may start conductin Permissioned mempools would also accelerate the centralization risks described in the previous section. Large pools running multiple validators will likely benefit from offering transaction privacy to traders and users, increasing their MEV revenues. -Combating these MEV-related problems in post-Merge Ethereum is a core area of research. To date, two solutions proposed to reduce the negative impact of MEV on Ethereum’s decentralization and security after The Merge are **Proposer-Builder Separation (PBS)** and the **Builder API**. +Combating these MEV-related problems in post-Merge Ethereum is a core area of research. To date, two solutions proposed to reduce the negative impact of MEV on Ethereum’s decentralization and security after The Merge are [**Proposer-Builder Separation (PBS)**](/roadmap/pbs/) and the [**Builder API**](https://github.com/ethereum/builder-specs). ### Proposer-Builder Separation {#proposer-builder-separation} In both proof-of-work and proof-of-stake, a node that builds a block proposes it for addition to the chain to other nodes participating in consensus. A new block becomes part of the canonical chain after another miner builds on top of it (in PoW) or it receives attestations from the majority of validators (in PoS). -The combination of block producer and block proposer roles is what introduces most of the MEV-related problems described previously. For example, consensus nodes are incentivized to trigger chain reorganizations in time-bandit attacks to maximize MEV earnings. +The combination of block producer and block proposer roles is what introduces most of the MEV-related problems described previously. For example, consensus nodes are incentivized to trigger chain reorganizations in [time-bandit attacks](https://www.mev.wiki/attack-examples/time-bandit-attack) to maximize MEV earnings. [Proposer-builder separation](https://ethresear.ch/t/proposer-block-builder-separation-friendly-fee-market-designs/9725) (PBS) is designed to mitigate the impact of MEV, especially at the consensus layer. PBS’ major feature is the separation of block producer and block proposer rules. Validators are still responsible for proposing and voting on blocks, but a new class of specialized entities, called **block builders**, are tasked with ordering transactions and building blocks. diff --git a/public/content/developers/docs/networking-layer/portal-network/index.md b/public/content/developers/docs/networking-layer/portal-network/index.md index 1868533d7cc..b47f6e1ce40 100644 --- a/public/content/developers/docs/networking-layer/portal-network/index.md +++ b/public/content/developers/docs/networking-layer/portal-network/index.md @@ -59,7 +59,13 @@ The benefits of this network design are: The diagram below shows the functions of existing clients that can be delivered by the Portal Network, enabling users to access these functions on very low-resource devices. -![portal network table](portal-network-table2.png) +### The Portal Networks + +| Beacon light client | State network | Transaction gossip | History network | +| ------------------- | ---------------------------- | ------------------- | --------------- | +| Beacon chain light | Account and contract storage | Lightweight mempool | Headers | +| Protocol data | | | Block bodies | +| | | | Receipts | ## Client diversity by default {#client-diversity-as-default} diff --git a/public/content/developers/docs/programming-languages/dart/index.md b/public/content/developers/docs/programming-languages/dart/index.md index 6bfdd155294..fb705bed0db 100644 --- a/public/content/developers/docs/programming-languages/dart/index.md +++ b/public/content/developers/docs/programming-languages/dart/index.md @@ -10,15 +10,13 @@ incomplete: true ## Tutorials {#tutorials} - [Flutter and Blockchain – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) takes you through all the steps to get started: - 1. Installing the [Truffle development suite](https://www.trufflesuite.com/) - 2. Writing a smart contract in [Solidity](https://soliditylang.org/) - 3. Writing a user interface in Dart + 1. Writing a smart contract in [Solidity](https://soliditylang.org/) + 2. Writing a user interface in Dart - [Building a Mobile dapp with Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) is a lot shorter, which might be better if you already know the basics - If you prefer to learn by watching a video, you can watch [Build Your First Blockchain Flutter App](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), which is about an hour long - If you are impatient, you might prefer [Building a Blockchain Decentralized-app with Flutter and Dart on Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), which is only about twenty minutes - [Integrating MetaMask in Flutter application with Web3Modal by WalletConnect](https://www.youtube.com/watch?v=v_M2buHCpc4) - this short video takes you through the steps of integrating MetaMask into your Flutter applications with [Web3Modal](https://pub.dev/packages/web3modal_flutter) library by WalletConnect -- [Flutter Dapp Simple Wallet](https://youtu.be/JMfIBpuAhKA) and [First Flutter DApp - Solidity, Truffle, Ganache](https://youtu.be/bHw2gQZxJ_s) - these videos show how to make simple dapps in Flutter using Truffle and Ganache - [Mobile Blockchain Developer Bootcamp Course With Solidity & Flutter](https://youtube.com/playlist?list=PL4V4Unlk5luhQ26ERO6hWEbcUwHDSSmVH) - full stack mobile blockchain developer course playlist ## Working with Ethereum clients {#working-with-ethereum-clients} diff --git a/public/content/developers/docs/programming-languages/golang/index.md b/public/content/developers/docs/programming-languages/golang/index.md index 573482616cf..891395b7487 100644 --- a/public/content/developers/docs/programming-languages/golang/index.md +++ b/public/content/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Need a more basic primer first? Check out [ethereum.org/learn](/learn/) or [ethe ## Beginner articles and books {#beginner-articles-and-books} -- [Choosing an Ethereum Client](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Getting Started with Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Use Golang to Connect to Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Deploy Ethereum Smart Contracts Using Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/developers/docs/programming-languages/rust/index.md b/public/content/developers/docs/programming-languages/rust/index.md index 5e0882232e4..22b735b0b44 100644 --- a/public/content/developers/docs/programming-languages/rust/index.md +++ b/public/content/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Need a more basic primer first? Check out [ethereum.org/learn](/learn/) or [ethe ## Beginner articles {#beginner-articles} -- [Choosing an Ethereum Client](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [The Rust Ethereum Client](https://openethereum.github.io/) \* **Note that OpenEthereum [has been deprecated](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) and is no longer being maintained.** Use it with caution and preferably switch to another client implementation. - [Sending Transaction to Ethereum Using Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [A step-by-step tutorial on how to write contracts in rust Wasm for Kovan](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index f124bca7839..00000000000 --- a/public/content/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,475 +0,0 @@ ---- -title: Create and deploy a DeFi App -description: Deposit ERC20 tokens to the smart contract and mint Farm Tokens -author: "strykerin" -tags: ["solidity", "defi", "web3.js", "truffle", "ganache", "smart contracts"] -skill: intermediate -lang: en -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -In this tutorial we will build a DeFi Application with Solidity where users can deposit an ERC20 token to the smart contract and it will mint and transfer Farm Tokens to them. The users can later withdraw their ERC20 tokens by burning their Farm Token on smart contract and the ERC20 tokens will be transferred back to them. - -## Install Truffle and Ganache {#install-truffle-and-ganache} - -If this is the first time you are writing a smart contract, you will need to set up your environment. We are going to use two tools: [Truffle](https://www.trufflesuite.com/) and [Ganache](https://www.trufflesuite.com/ganache). - -Truffle is a development environment and testing framework for developing smart contracts for Ethereum. With Truffle it is easy to build and deploy smart contracts to the blockchain. Ganache allows us to create a local Ethereum blockchain in order to test smart contracts. It simulates the features of the real network and the first 10 accounts are funded with 100 test ether, thus making the smart contract deployment and testing free and easy. Ganache is available as a desktop application and a command-line tool. For this article we will be using the UI desktop application. - -![Ganache UI desktop application](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Ganache UI desktop application_ - -To create the project, run the following commands - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -This will create a blank project for the development and deployment of our smart contracts. The created project structure is the following: - -- `contracts`: Folder for the solidity smart contracts - -- `migrations`: Folder for the deployment scripts - -- `test`: Folder for testing our smart contracts - -- `truffle-config.js`: Truffle configuration file - -## Create the ERC20 Token {#create-the-erc20-token} - -First we need to create our ERC20 token that we will use to stake on the smart contract. To create our fungible token, we will first need to install the OpenZeppelin library. This library contains the implementations of standards such as the ERC20 and the ERC721. To install it, run the command: - -```bash -npm install @openzeppelin/contracts -``` - -Using the OpenZeppelin library we can create our ERC20 token by writing to `contracts/MyToken.sol` with the following solidity code: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -In the code above on: - -- Line 3: We import the contract ERC20.sol from openzeppelin that contains the implementation for this token standard. - -- Line 5: We inherit from the ERC20.sol contract. - -- Line 6: We are calling the ERC20.sol constructor and passing for the name and symbol parameters as `"MyToken"` and `"MTKN"` respectively. - -- Line 7: We are minting and transferring 1 million tokens for the account that is deploying the smart contract (we are using the default 18 decimals for the ERC20 token, that means that if we want to mint 1 token, you will represent it as 1000000000000000000, 1 with 18 zeros). - -We can see below the ERC20.sol constructor implementation where the `_decimals` field is set to 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compile the ERC20 Token {#compile-the-erc20-token} - -To compile our smart contract, we must first check our solidity compiler version. You can check that by running the command: - -```bash -truffle version -``` - -The default version is the `Solidity v0.5.16`. Since our token is written using the solidity version `0.6.2`, if we run the command to compile our contracts we will get a compiler error. In order to specify which solidity compiler version to use, go to the file `truffle-config.js` and set to the desired compiler version as seen below: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Now we can compile our smart contract by running the following command: - -```bash -truffle compile -``` - -## Deploy ERC20 Token {#deploy-erc20-token} - -After compiling, we can now deploy our token. - -On the `migrations` folder, create a file called `2_deploy_Tokens.js`. This file is where we will deploy both our ERC20 Token and our FarmToken smart contract. The code below is used to deploy our MyToken.sol contract: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Open Ganache and select the option "Quickstart" to start a local Ethereum blockchain. To deploy our contract, run: - -```bash -truffle migrate -``` - -The address used to deploy our contracts is the first one from the list of addresses that Ganache shows us. To verify that, we can open the Ganache desktop application and we can verify that the balance of ether for the first account has been reduced due to the cost of ether to deploy our smart contracts: - -![Ganache desktop application](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Ganache desktop application_ - -To verify that 1 million MyToken tokens have been sent to the deployer address, we can use the Truffle Console to interact with our deployed smart contract. - -> [Truffle Console is a basic interactive console connecting to any Ethereum client.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -In order to interact with our smart contract, run the following command: - -```bash -truffle console -``` - -Now we can write the following commands in the terminal: - -- Get the smart contract: `myToken = await MyToken.deployed()` - -- Get the array of accounts from Ganache: `accounts = await web3.eth.getAccounts()` - -- Get the balance for the first account: `balance = await myToken.balanceOf(accounts[0])` - -- Format the balance from 18 decimals: `web3.utils.fromWei(balance.toString())` - -By running the commands above, we will see that the first address has in fact 1 million MyTokens: - -![First address has 1000000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_First address has 1000000 MyTokens_ - -## Create FarmToken Smart Contract {#create-farmtoken-smart-contract} - -The FarmToken smart contract will have 3 functions: - -- `balance()`: Get the MyToken balance on the FarmToken smart contract. - -- `deposit(uint256 _amount)`: Transfer MyToken on behalf of the user to the FarmToken smart contract then mint and transfer FarmToken to the user. - -- `withdraw(uint256 _amount)`: Burn user's FarmTokens and transfer MyTokens to the user's address. - -Let's look at the FarmToken constructor: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Lines 3-6: We are importing the following contracts from openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol and ERC20.sol. - -- Line 8: The FarmToken will inherit from the ERC20 contract. - -- Lines 14-19: The FarmToken constructor will receive as parameter the address of MyToken contract and we will assign its contract to our public variable called `token`. - -Let's implement the `balance()` function. It will receive no parameters and it will return the balance of MyToken on this smart contract. It is implemented as shown below: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -For the `deposit(uint256 _amount)` function, it will receive as parameter the amount the user wants to deposit and it will mint and transfer FarmTokens to the user: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -For the `withdraw(uint256 _amount)` function, we will receive as parameter the amount of FarmTokens the user wants to burn and then transfer the same amount of MyTokens back to the user: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Now we will deploy our smart contract. To do so, we will go back to the file `2_deploy_Tokens.js` and add the new contract to be deployed: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Note that when deploying the FarmToken, we pass as parameter the address of the deployed MyToken contract. - -Now, run `truffle compile` and `truffle migrate` to deploy our contracts. - -Let's test our smart contract. Instead of using the `truffle console` to interact with our smart contract, we will create a script to automate this process. Create a folder called `scripts` and add the following file `getMyTokenBalance.js`. It will check the balance of MyTokens on the FarmToken smart contract: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -To execute this script, run the following cli command: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -We will get the expected result that is 0. If you get an error about the FarmToken not being deployed yet, the truffle network has not received the latest version of your contract code. Just close ganache, quickstart it again and make sure to run `truffle migrate`. - -Now, let's stake the MyToken to the smart contract. Since the function `deposit(uint256 _amount)` calls the function `safeTransferFrom` from the ERC20, the user must first approve the smart contract to transfer MyToken on the user's behalf. So on the script below, we will first approve this step then we will call the function: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -To run this script: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. You should see on your console: - -![output of transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_output of transferMyTokenToFarmToken.js_ - -As we can see, we have successfully deposited MyTokens to the smart contract as the first account has now FarmTokens. - -In order to withdraw: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -To run this script: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. As we can see on the output below, we have successfully got the MyTokens back and we have burned the FarmTokens: - -![output of withdrawMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_output of withdrawMyTokenFromTokenFarm.js_ - -## References {#references} - -[Contracts - OpenZeppelin Docs](https://docs.openzeppelin.com/contracts/3.x/) - -[Sweet Tools for Smart Contracts | Truffle Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[What is DeFi? A Beginner's Guide (2021 Updated) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - The Decentralized Finance Leaderboard at DeFi Llama](https://defillama.com/) diff --git a/public/content/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index f2b302154b3..48ae1bed1cb 100644 --- a/public/content/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -3,7 +3,7 @@ title: "Downsizing contracts to fight the contract size limit" description: What can you do to prevent your smart contracts from getting too large? author: Markus Waas lang: en -tags: ["solidity", "smart contracts", "storage", "truffle"] +tags: ["solidity", "smart contracts", "storage"] skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -20,16 +20,6 @@ This limit was introduced to prevent denial-of-service (DOS) attacks. Any call t Originally this was less of a problem because one natural contract size limit is the block gas limit. Obviously, a contract must be deployed within a transaction that holds all of the contract's bytecode. If you include only that one transaction into a block, you can use up all that gas, but it's not infinite. Since the [London Upgrade](/history/#london), the block gas limit has been able to vary between 15M and 30M units depending on network demand. -## Taking on the fight {#taking-on-the-fight} - -Unfortunately, there is no easy way of getting the bytecode size of your contracts. A great tool to help you that is the [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) plugin if you're using Truffle. - -1. `npm install truffle-contract-size` -2. Add the plugin to the _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Run `truffle run contract-size` - -This will help you figure out how your changes are affecting the total contract sizes. - In the following we will look at some methods ordered by their potential impact. Think about it in the terms of weight-loss. The best strategy for someone to hit their target weight (in our case 24kb) is to focus on the big impact methods first. In most cases just fixing your diet will get you there, but sometimes you need a little bit more. Then you might add some exercise (medium impact) or even supplements (small impact). ## Big impact {#big-impact} diff --git a/public/content/developers/tutorials/secure-development-workflow/index.md b/public/content/developers/tutorials/secure-development-workflow/index.md index b812729b5dc..1dbc4b96ad6 100644 --- a/public/content/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/developers/tutorials/secure-development-workflow/index.md @@ -23,7 +23,6 @@ Consider special features of your contract: - Are your contracts upgradeable? Review your upgradeability code for flaws with [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) or [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). We've documented 17 ways upgrades can go sideways. - Do your contracts purport to conform to ERCs? Check them with [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). This tool instantly identifies deviations from six common specs. -- Do you have unit tests in Truffle? Enrich them with [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation). It automatically generates a robust suite of security properties for features of ERC20 based on your specific code. - Do you integrate with 3rd party tokens? Review our [token integration checklist](/developers/tutorials/token-integration-checklist/) before relying on external contracts. Visually inspect critical security features of your code: diff --git a/public/content/developers/tutorials/server-components/fig-1.svg b/public/content/developers/tutorials/server-components/fig-1.svg new file mode 100644 index 00000000000..187264cce16 --- /dev/null +++ b/public/content/developers/tutorials/server-components/fig-1.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/public/content/developers/tutorials/server-components/fig-2.svg b/public/content/developers/tutorials/server-components/fig-2.svg new file mode 100644 index 00000000000..2082fba3846 --- /dev/null +++ b/public/content/developers/tutorials/server-components/fig-2.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/content/developers/tutorials/server-components/index.md b/public/content/developers/tutorials/server-components/index.md new file mode 100644 index 00000000000..14fae60d5ab --- /dev/null +++ b/public/content/developers/tutorials/server-components/index.md @@ -0,0 +1,290 @@ +--- +title: "Server components and agents for web3 apps" +description: After reading this tutorial, you will be able to write TypeScript servers that listen to events on a blockchain and respond accordingly with their own transactions. This will enable you to write centralized applications (because the server is a point of failure), but can interact with web3 entities. The same techniques can also be used to write an agent that responds to on-chain events without a human in the loop. + +author: Ori Pomerantz +lang: en +tags: ["agent", "server", "offchain", "centralized"] +skill: beginner +published: 2024-07-15 +--- + +## Introduction {#introduction} + +In most cases, a decentralized app uses a server to distribute the software, but all the actual interaction happens between the client (typically, web browser) and the blockchain. + +![Normal interaction between web server, client, and blockchain](./fig-1.svg) + +However, there are some cases where an application would benefit from having a server component that runs independently. Such a server would be able to respond to events, and to requests that come from other sources, such as an API, by issuing transactions. + +![The interaction with the addition of a server](./fig-2.svg) + +There are several possible tasks for such a server could fulfill. + +- Holder of secret state. In gaming it is often useful not to have all the information that the game knows available to the players. However, *there are no secrets on the blockchain*, any information that is in the blockchain is easy for anybody to figure out. Therefore, if part of the game state is to be kept secret, it has to be stored elsewhere (and possibly have the effects of that state verified using [zero-knowledge proofs](/zero-knowledge-proofs)). + +- Centralized oracle. If the stakes are sufficiently low, an external server that reads some information online and then posts it to the chain may be good enough to use as an [oracle](/developers/docs/oracles/). + +- Agent. Nothing happens on the blockchain without a transaction to activate it. A server can act on behalf of a user to perform actions such as [arbitrage](/developers/docs/mev/#mev-examples-dex-arbitrage) when the opportunity presents itself. + +## Sample program {#sample-program} + +You can see a sample server [on github](https://github.com/qbzzt/20240715-server-component). This server listens to events coming from [this contract](https://eth-holesky.blockscout.com/address/0xB8f6460Dc30c44401Be26B0d6eD250873d8a50A6?tab=contract_code), a modified version of Hardhat's Greeter. When the greeting is changed, it changes it back. + +To run it: + +1. Clone the repository. + + ```sh copy + git clone https://github.com/qbzzt/20240715-server-component.git + cd 20240715-server-component + ``` + +2. Install the necessary packages. If you don't have it already, [install Node first](https://nodejs.org/en/download/package-manager). + + ```sh copy + npm install + ``` + +3. Edit `.env` to specify the private key of an account that has ETH on the Holesky testnet. If you do not have ETH on Holesky, you can [use this faucet](https://holesky-faucet.pk910.de/). + + ```sh filename=".env" copy + PRIVATE_KEY=0x + ``` + +4. Start the server. + + ```sh copy + npm start + ``` + +5. Go to [a block explorer](https://eth-holesky.blockscout.com/address/0xB8f6460Dc30c44401Be26B0d6eD250873d8a50A6?tab=write_contract), and using a different address than the one that has the private key modify the greeting. See that the greeting is automatically modified back. + +### How does it work? {#how-it-works} + +The easiest way to understand how to write a server component is to go over the sample one line by line. + +#### `src/app.ts` {#src-app-ts} + +The vast majority of the program is contained in [`src/app.ts`](https://github.com/qbzzt/20240715-server-component/blob/main/src/app.ts). + + +##### Creating the prerequisite objects + +```typescript +import { createPublicClient, createWalletClient, getContract, http, Address } from 'viem' +``` + +These are the [Viem](https://viem.sh/) entities we need, functions and [the `Address` type](https://viem.sh/docs/glossary/types#address). This server is written in [TypeScript](https://www.typescriptlang.org/), which is an extension to JavaScript that makes it [strongly typed](https://en.wikipedia.org/wiki/Strong_and_weak_typing). + +```typescript +import { privateKeyToAccount } from 'viem/accounts' +``` + +[This function](https://viem.sh/docs/accounts/privateKey) lets us generate the wallet information, including address, corresponding to a private key. + +```typescript +import { holesky } from 'viem/chains' +``` + +To use a blockchain in Viem you need to import its definition. In this case, we want to connect to the [Holesky](https://github.com/eth-clients/holesky) test blockchain. + +```typescript +// This is how we add the definitions in .env to process.env. +import * as dotenv from "dotenv"; +dotenv.config() +``` + +This is how we read `.env` into the environment. We need it for the private key (see later). + +```typescript +const greeterAddress : Address = "0xB8f6460Dc30c44401Be26B0d6eD250873d8a50A6" +const greeterABI = [ + { + "inputs": [ + { + "internalType": "string", + "name": "_greeting", + "type": "string" + } + ], + "stateMutability": "nonpayable", + "type": "constructor" + }, + . + . + . + { + "inputs": [ + { + "internalType": "string", + "name": "_greeting", + "type": "string" + } + ], + "name": "setGreeting", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +] as const +``` + +To use a contract we need its address and the [ABI](/glossary/#abi) for it. We provide both here. + +In JavaScript (and therefore TypeScript) you can't assign a new value to a constant, but you *can* modify the object that is stored in it. By using the suffix `as const` we are telling TypeScript that the list itself is constant and may not be changed. + +```typescript +const publicClient = createPublicClient({ + chain: holesky, + transport: http(), +}) +``` + +Create a Viem [public client](https://viem.sh/docs/clients/public.html). Public clients do not have an attached private key, and therefore cannot send transactions. They can call [`view` functions](https://www.tutorialspoint.com/solidity/solidity_view_functions.htm), read account balances, etc. + +```typescript +const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`) +``` + +The environment variables are available in [`process.env`](https://www.totaltypescript.com/how-to-strongly-type-process-env). However, TypeScript is strongly typed. An environment variable can be be any string, or empty, so the type for an environment variable is `string | undefined`. However, a key is defined in Viem as `0x${string}` (`0x` followed by a string). Here we tell TypeScript that the `PRIVATE_KEY` environment variable will be of that type. If it isn't, we'll get a runtime error. + +The [`privateKeyToAccount`](https://viem.sh/docs/accounts/privateKey) function then uses this private key to create a full account object. + +```typescript +const walletClient = createWalletClient({ + account, + chain: holesky, + transport: http(), +}) +``` + +Next, we use the account object to create a [wallet client](https://viem.sh/docs/clients/wallet). This client has a private key and an address, so it can be used to send transactions. + +```typescript +const greeter = getContract({ + address: greeterAddress, + abi: greeterABI, + client: { public: publicClient, wallet: walletClient } +}) +``` + +Now that we have all the prerequisites, we can finally create a [contract instance](https://viem.sh/docs/contract/getContract). We will use this contract instance to communicate with the on-chain contract. + + +##### Reading from the blockchain + +```typescript +console.log(`Current greeting:`, await greeter.read.greet()) +``` + +The contract functions that are read only ([`view`](https://www.tutorialspoint.com/solidity/solidity_view_functions.htm) and [`pure`](https://www.tutorialspoint.com/solidity/solidity_pure_functions.htm)) are available under `read`. In this case, we use it to access the [`greet`](https://eth-holesky.blockscout.com/address/0xB8f6460Dc30c44401Be26B0d6eD250873d8a50A6?tab=read_contract#cfae3217) function, which returns the greeting. + +JavaScript is single-threaded, so when we fire off a long running process we need to [specify we do it asynchronously](https://eloquentjavascript.net/11_async.html#h-XvLsfAhtsE). Calling the blockchain, even for a read only operation, requires a round-trip between the computer and a blockchain node. That is the reason we specify here the code needs to `await` for the result. + +If you are interested in how this work you can [read about it here](https://www.w3schools.com/js/js_promise.asp), but in practical terms all you need to know is that you `await` the results if you start an operation that takes a long time, and that any function that does this has to be declared as `async`. + + +##### Issuing transactions + +```typescript +const setGreeting = async (greeting: string): Promise => { +``` + +This is the function you call to issue a transaction that changes the greeting. As this is a long operation, the function is declared as `async`. Because of the internal implementation, any `async` function needs to return a `Promise` object. In this case, `Promise` means that we don't specify what exactly will be returned in the `Promise`. + +```typescript + const txHash = await greeter.write.setGreeting([greeting]); +``` + +The `write` field of the contract instance has all the functions that write to the blockchain state (those that require sending a transaction), such as [`setGreeting`](https://eth-holesky.blockscout.com/address/0xB8f6460Dc30c44401Be26B0d6eD250873d8a50A6?tab=write_contract#a4136862). The parameters, if any, are provided as a list, and the function returns the hash of the transaction. + +```typescript + console.log(`Working on a fix, see https://eth-holesky.blockscout.com/tx/${txHash}`) + + return txHash +} +``` + +Report the hash of the transaction (as part of a URL to the block explorer to view it) and return it. + + +##### Responding to events + +```typescript +greeter.watchEvent.SetGreeting({ +``` + +[The `watchEvent` function](https://viem.sh/docs/actions/public/watchEvent) lets you specify that a function is to run when an event is emitted. If you only care about one type of event (in this case, `SetGreeting`), you can use this syntax to limit yourself to that event type. + + +```typescript + onLogs: logs => { +``` + +The `onLogs` function is called when there are log entries. In Ethereum "log" and "event" are usually interchangeable. + +```typescript + console.log(`Address ${logs[0].args.sender} changed the greeting to ${logs[0].args.greeting}`) +``` + +There could be multiple events, but foir simplicity we only care about the first one. `logs[0].args` are the arguments of the event, in this case `sender` and `greeting`. + +```typescript + if (logs[0].args.sender != account.address) + setGreeting(`${account.address} insists on it being Hello!`) + } +}) +``` + +If the sender is *not* this server, use `setGreeting` to change the greeting. + +#### `package.json` {#package-json} + +[This file](https://github.com/qbzzt/20240715-server-component/blob/main/package.json) controls the [Node.js](https://nodejs.org/en) configuration. This article only explains the important definitions. + +```json +{ + "main": "dist/index.js", +``` + +This definition specifies which JavaScript file to run. + +```json + "scripts": { + "start": "tsc && node dist/app.js", + }, +``` + +The scripts are various application actions. In this case, the only one we have is `start`, which compiles and then runs the server. The `tsc` command is part of the `typescript` package and compiles TypeScript into JavaScript. If you want to run it manually, it is located in `node_modules/.bin`. The second command runs the server. + +```json + "type": "module", +``` + +There are multiple types of JavaScript node applications. The `module` type lets us have `await` in the top level code, which is important when you do slow (and there asynchronous) operations. + +```json + "devDependencies": { + "@types/node": "^20.14.2", + "typescript": "^5.4.5" + }, +``` + +These are packages that are only required for development. Here we need `typescript` and the because we are using it with Node.js, we are also getting the types for node variables and objects, such as `process`. [The `^` notation](https://github.com/npm/node-semver?tab=readme-ov-file#caret-ranges-123-025-004) means that version or a higher version that doesn't have breaking changes. See [here](https://semver.org) for more information about the meaning of version numbers. + +```json + "dependencies": { + "dotenv": "^16.4.5", + "viem": "2.14.1" + } +} +``` + +These are packages that are required at runtime, when running `dist/app.js`. + +## Conclusion {#conclusion} + +The centralized server we created here does its job, which is to act as an agent for a user. Anybody else who wants the dapp to continue functioning and is willing to spend the gas can run a new instance of the server with their own address. + +However, this only works when the centralized server's actions can be easily verified. If the centralized server has any secret state information, or runs difficult calculations, it is a centralized entity that you need trust to use the application, which is exactly what blockchains try to avoid. In a future article I plan to show how to use [zero-knowledge proofs](/zero-knowledge-proofs) to get around this problem. \ No newline at end of file diff --git a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/coverall.png b/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/coverall.png deleted file mode 100644 index a0f289d1699..00000000000 Binary files a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/coverall.png and /dev/null differ diff --git a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/gas-reports.png b/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/gas-reports.png deleted file mode 100644 index 677be3fd922..00000000000 Binary files a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/gas-reports.png and /dev/null differ diff --git a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 36c0ca1f746..00000000000 --- a/public/content/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: "Solidity and Truffle continuous integration setup" -description: How to setup Travis or Circle CI for Truffle testing along with useful plugins -author: Markus Waas -lang: en -tags: ["solidity", "smart contracts", "testing", "truffle", "ganache"] -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -Continuous integration (CI) with Truffle is great for developing once you have a basic set of tests implemented. It allows you to run very long tests, ensure all tests pass before merging a [pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) and to keep track of various statistics using additional tools. - -We will use the [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) to setup our continuous integration. You can either choose Travis CI or Circle CI. - -## Setting up Travis CI {#setting-up-travis-ci} - -Adding [Travis CI](https://travis-ci.org/) is straight-forward. You will only need to add a `.travis.yml` config file to the root folder of the project: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -We are keeping it simple for now and are only running the test script which executes the Truffle unit tests. But we have one problem, there won't be a blockchain available on the Travis CI machine. A simple fix for this is to `npm install ganache-cli` and simply run it before the test. You can do this by adding a bash script with the line npx `ganache-cli > /dev/null` and before the `npx truffle test` call. The [full example bash script](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Setting up Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) requires a longer config file. The additional [`npm ci`](https://docs.npmjs.com/cli/ci.html) command is automatically done in Travis. It installs dependencies faster and more securely than `npm install` does. We again use the same script from the Travis version to run ganache-cli before the tests. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Adding the eth-gas-reporter plugin {#adding-the-eth-gas-reporter-plugin} - -The eth-gas-reporter plugin is quite useful for keeping track of the gas costs of your smart contract functions. Having it in your CI will further be useful for showing diffs when adding pull requests. - -### Step 1: Install the eth-gas-reporter plugin and codechecks {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Step 2: Add the plugin to the mocha settings inside your truffle-config.js {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[See options](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Step 3: Add a codechecks.yml to your project's root directory {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Step 4: Run codechecks after the test command {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Step 5: Create a Codechecks account {#step-5-create-a-codechecks-account} - -- Create an account with [Codechecks](http://codechecks.io/). -- Add the GitHub repo to it. -- Copy the secret and add the `CC_SECRET=COPIED SECRET` to your CI (see here for [Travis](https://docs.travis-ci.com/user/environment-variables/), here for [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Now go ahead and create a pull request. - -That's it. You will now find a nice report about changes in gas costs of your pull request. - -![Example gas reports](./gas-reports.png) - -## Adding the solidity-coverage plugin {#adding-the-solidity-coverage-plugin} - -With the solidity-coverage plugin you can check how much of your code paths are covered by your tests. Adding this to your CI makes is very convenient to use once it is set up. - -### Step 1: Create a metacoin project and install coverage tools {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### Step 2: Add solidity-coverage to the plugins array in truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Step 3: Add the coverage commands to the .travis.yml or Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Solidity coverage starts its own ganache-cli, so we don't have to worry about this. Do not replace the regular test command though, coverage's ganache-cli works differently and is therefore no replacement for running regular unit tests. - -### Step 4: Add repository to coveralls {#step-4-add-repository-to-coveralls} - -- Create an account with [Coveralls](https://coveralls.io/). -- Add the GitHub repo to it. -- Now go ahead and create a pull request. - -![Example coverall](./coverall.png) - -## Further ideas {#further-ideas} - -- [MythX](https://mythx.io/): With MythX you can automatically analyze your smart contract security. So it makes a lot of sense to [add this to your CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Good code can be enforced to some degree with linting tools. [Eslint](https://eslint.org/) works great for JavaScript, is [easy to setup](https://eslint.org/docs/user-guide/getting-started), while [Solhint](https://protofire.github.io/solhint/) can be used for Solidity. -- Long tests: Sometimes you may want to add extreme tests, e.g., testing a contracts with hundreds of users. This takes a lot of time. Instead of running those in every test run, add them to the CI. - -There you have it. Continuous integration is a very useful strategy for your developments. You can check out a full example at [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Just make sure to remove Circle-CI or Travis, one is enough! diff --git a/public/content/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index a21d6f0ea9f..6aed327d08c 100644 --- a/public/content/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -122,7 +122,7 @@ The manifest is our configuration file and defines: - other things to listen to like function calls or blocks - the mapping functions being called (see `mapping.ts` below) -You can define multiple contracts and handlers here. A typical setup would have a subgraph folder inside the Truffle/Hardhat project with its own repository. Then you can easily reference the ABI. +You can define multiple contracts and handlers here. A typical setup would have a subgraph folder inside the Hardhat project with its own repository. Then you can easily reference the ABI. For convenience reasons you also might want to use a template tool like mustache. Then you create a `subgraph.template.yaml` and insert the addresses based on the latest deployments. For a more advanced example setup, see for example the [Aave subgraph repo](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/enterprise/index.md b/public/content/enterprise/index.md index fce29269d2d..0725819503b 100644 --- a/public/content/enterprise/index.md +++ b/public/content/enterprise/index.md @@ -63,7 +63,6 @@ Some collaborative efforts to make Ethereum enterprise friendly have been made b - [Baseline Project](https://www.baseline-protocol.org/) - _The Baseline Protocol is a set of tools and libraries that helps enterprises coordinate complex, multi-party business processes and workflows with privacy while keeping data in respective systems of record. The standard enables two or more state machines to achieve and maintain data consistency and workflow continuity by using a network as a common frame of reference._ - [Chainlens](https://www.chainlens.com/) - _SaaS and on-prem blockchain data and analytics platform from Web3 Labs_ - [Ernst & Young's 'Nightfall'](https://github.com/EYBlockchain/nightfall_3) - _an application for transferring ERC20, ERC721 and ERC1155 applications under Zero Knowledge, using an Optimistic Rollup_ -- [Truffle Suite](https://trufflesuite.com) - _blockchain development suite (Truffle, Ganache, Drizzle)_ ### Scalability solutions {#scalability-solutions} diff --git a/public/content/guides/how-to-use-a-wallet/index.md b/public/content/guides/how-to-use-a-wallet/index.md index 600f2562cc9..484efefdef8 100644 --- a/public/content/guides/how-to-use-a-wallet/index.md +++ b/public/content/guides/how-to-use-a-wallet/index.md @@ -1,5 +1,5 @@ --- -title: How to use a wallet +title: How to use Ethereum Wallets | Step by Step description: A guide explaining how to send, receive tokens and connect to web3 projects. lang: en --- diff --git a/public/content/nft/index.md b/public/content/nft/index.md index e24cf4646db..4d682f21242 100644 --- a/public/content/nft/index.md +++ b/public/content/nft/index.md @@ -1,5 +1,5 @@ --- -title: Non-fungible tokens (NFT) +title: What are NFTs? | Benefits and use description: An overview of NFTs on Ethereum lang: en template: use-cases diff --git a/public/content/roadmap/index.md b/public/content/roadmap/index.md index 8c06c14c23a..781bf05e55d 100644 --- a/public/content/roadmap/index.md +++ b/public/content/roadmap/index.md @@ -7,9 +7,9 @@ image: /images/heroes/roadmap-hub-hero.jpg alt: "Ethereum roadmap" summaryPoints: buttons: - - label: Further upgrades + - content: Further upgrades toId: what-changes-are-coming - - label: Past upgrades + - content: Past upgrades href: /history/ variant: outline --- diff --git a/public/content/security/index.md b/public/content/security/index.md index fa26ad7374a..21f3a51e237 100644 --- a/public/content/security/index.md +++ b/public/content/security/index.md @@ -8,6 +8,8 @@ lang: en Rising interest in cryptocurrency brings with it growing risk from scammers and hackers. This article lays out some best practices to mitigate these risks. +**Remember: No one from ethereum.org will ever contact you. Don’t reply to emails saying they’re from official Ethereum support.** + ## Crypto security 101 {#crypto-security} diff --git a/public/content/smart-contracts/index.md b/public/content/smart-contracts/index.md index 64bf7d73a62..e1aefbec796 100644 --- a/public/content/smart-contracts/index.md +++ b/public/content/smart-contracts/index.md @@ -1,5 +1,5 @@ --- -title: Smart contracts +title: "Smart contracts: What are they and benefits" description: A non-technical introduction to smart contracts lang: en --- diff --git a/public/content/translations/ar/enterprise/index.md b/public/content/translations/ar/enterprise/index.md index ea38751a8ee..aa738ec4be7 100644 --- a/public/content/translations/ar/enterprise/index.md +++ b/public/content/translations/ar/enterprise/index.md @@ -74,7 +74,6 @@ lang: ar - [Alethio](https://explorer.aleth.io/) _منصة لتحليل البيانات بواسطة إيثريوم_ - [Treum](https://treum.io/) _جلب الشفافية وقابلية التتبع وقابلية الإتجار لسلالس الإمداد، باستخدام تقنية سلسلة الكتل_ -- [Truffle Suite](https://trufflesuite.com) _مجموعة تطوير سلسلة الكتل (Truffle, Ganache, Drizzle)_ ## المجتمع المؤسسي للمطورين {#enterprise-developer-community} diff --git a/public/content/translations/bn/enterprise/index.md b/public/content/translations/bn/enterprise/index.md index 9153b7717e2..6871e8aa31c 100644 --- a/public/content/translations/bn/enterprise/index.md +++ b/public/content/translations/bn/enterprise/index.md @@ -75,7 +75,6 @@ lang: bn - [Alethio](https://explorer.aleth.io/) _ইথেরিয়াম ডেটা অ্যানালিটিক্স প্ল্যাটফর্ম_ - [Treum](https://treum.io/) _ব্লকচেইন প্রযুক্তি ব্যবহার করে সাপ্লাই চেইনের ক্ষেত্রে স্বচ্ছতা, ট্রেসেবিলিটি এবং ব্যবসায়যোগ্যতা নিয়ে আসে_ -- [Truffle Suite](https://trufflesuite.com) _ব্লকচেইন ডেভেলপমেন্ট সুইট (Truffle, Ganache, Drizzle)_ ## এন্টারপ্রাইজ ডেভেলপার সম্প্রদায় {#enterprise-developer-community} diff --git a/public/content/translations/ca/community/support/index.md b/public/content/translations/ca/community/support/index.md index 7bab57e0de7..3e7db2d76be 100644 --- a/public/content/translations/ca/community/support/index.md +++ b/public/content/translations/ca/community/support/index.md @@ -55,7 +55,6 @@ Aquí teniu alguns exemples populars: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) ## Executar un node {#node-support} diff --git a/public/content/translations/cs/enterprise/index.md b/public/content/translations/cs/enterprise/index.md index 5451c72cd99..4d767e5ceaf 100644 --- a/public/content/translations/cs/enterprise/index.md +++ b/public/content/translations/cs/enterprise/index.md @@ -75,7 +75,6 @@ Veřejné a soukromé Ethereum sítě mohou v závislosti na tom, kdo je použí - [Alethio](https://explorer.aleth.io/) _Datově analytická platforma pro Ethereum_ - [Treum](https://treum.io/) _pomocí technologie blockchainu přináší transparentnost, dohledatelnost a obchodovatelnost dodavatelským řetězcům_ -- [Truffle Suite](https://trufflesuite.com) _sada nástrojů pro blockchainový vývoj (Truffle, Ganache, Drizzle)_ ## Komunita vývojářů funkcí pro firmy {#enterprise-developer-community} diff --git a/public/content/translations/de/community/support/index.md b/public/content/translations/de/community/support/index.md index 3eabdec118d..2b1e1c43b7f 100644 --- a/public/content/translations/de/community/support/index.md +++ b/public/content/translations/de/community/support/index.md @@ -57,7 +57,6 @@ Hier sind einige beliebte Beispiele: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/de/developers/docs/development-networks/index.md b/public/content/translations/de/developers/docs/development-networks/index.md index 66c24ddb964..4d026d82f5b 100644 --- a/public/content/translations/de/developers/docs/development-networks/index.md +++ b/public/content/translations/de/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Sie _könnten_ [einen Knoten betreiben](/developers/docs/nodes-and-clients/#runn **Hinweis**: Die meisten [Entwicklerframeworks](/developers/docs/frameworks/) enthalten ein integriertes Entwicklungsnetzwerk. Wir empfehlen Ihnen, mit einem Framework für die Einrichtung [Ihrer lokalen Entwicklungsumgebung](/developers/local-environment/) zu beginnen. -### Ganache {#ganache} - -Führen Sie kurzerhand eine persönliche Ethereum-Blockchain aus, die Sie zum Ausführen von Tests und Befehlen und zur Prüfung des Status verwenden können, während Sie die Funktionsweise der Chain kontrollieren. - -Ganache bietet sowohl eine Desktop-Anwendung (Ganache UI), als auch ein Befehlszeilentool (`ganache-cli`). Es ist Teil der Truffel-Toolsuite. - -- [Website](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Dokumentation](https://www.trufflesuite.com/docs/ganache/overview) - ### Hardhat Network {#hardhat-network} Ein lokales Ethereum-Netzwerk, das für die Entwicklung konzipiert ist. Die können darin Ihre Contracts bereitstellen, Tests durchführen und Ihren Code debuggen. diff --git a/public/content/translations/de/developers/docs/frameworks/index.md b/public/content/translations/de/developers/docs/frameworks/index.md index 36d99267b9a..5b5cbfa64d0 100644 --- a/public/content/translations/de/developers/docs/frameworks/index.md +++ b/public/content/translations/de/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Bevor Sie sich mit Frameworks beschäftigen, empfehlen wir, dass Sie sich mit de ## Verfügbare Frameworks {#available-frameworks} -**Truffle –** **_Eine Entwicklungsumgebung, Test-Framework, Build-Pipeline und weitere Tools_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Hardhat –** **_Ethereum-Entwicklungsumgebung für Experten_** - [hardhat.org](https://hardhat.org) diff --git a/public/content/translations/de/developers/docs/programming-languages/dart/index.md b/public/content/translations/de/developers/docs/programming-languages/dart/index.md index 14c9d1d5515..d09f35a7bb6 100644 --- a/public/content/translations/de/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/de/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutorials {#tutorials} - [Flutter und Blockchain – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) führt Sie durch die ersten Schritte: - 1. [Truffle-Entwicklungssuite](https://www.trufflesuite.com/) installieren - 2. Smart Contract in [Solidity](https://soliditylang.org/) schreiben - 3. Benutzeroberfläche in Dart schreiben + 1. Smart Contract in [Solidity](https://soliditylang.org/) schreiben + 2. Benutzeroberfläche in Dart schreiben - Eine [mobile dApp mit Flutter zu erstellen](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) ist wesentlich kürzer und empfehlenswert für alle, die mit den Grundlagen bereits vertraut sind - Wenn Sie Erklärungsvideos bevorzugen, ist [Ihre erste Blockchain-Flutter-App erstellen](https://www.youtube.com/watch?v=3Eeh3pJ6PeA) empfehlenswert. Die Dauer beträgt etwa eine Stunde. - Für Ungeduldige ist [Bau einer dezentralen Blockchain-Anwendung mit Flutter und Dart auf Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s) empfehlenswert, denn die Dauer beträgt nur etwa zwanzig Minuten. diff --git a/public/content/translations/de/developers/docs/programming-languages/golang/index.md b/public/content/translations/de/developers/docs/programming-languages/golang/index.md index 06fec34dd5d..8284879ea83 100644 --- a/public/content/translations/de/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/de/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Sind Sie an einigen grundlegenden Informationen interessiert? Dann sehen Sie sic ## Artikel und Bücher für Einsteiger {#beginner-articles-and-books} -- [Einen Ethereum-Client wählen](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Erste Schritte mit Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Golang für die Verbindung mit Ethereum verwenden](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Ethereum-Smart Contracts mit Golang bereitstellen](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/de/developers/docs/programming-languages/rust/index.md b/public/content/translations/de/developers/docs/programming-languages/rust/index.md index a3f543a3b76..9731c5bd298 100644 --- a/public/content/translations/de/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/de/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Sind Sie an einigen grundlegenden Informationen interessiert? Dann sehen Sie sic ## Informationen für Einsteiger {#beginner-articles} -- [Einen Ethereum-Client wählen](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Der Rust-Ethereum-Client](https://openethereum.github.io/) \* **Beachten Sie, dass OpenEthereum [veraltet](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) ist und nicht mehr gepflegt wird.** Nutzen Sie es mit Vorsicht und wechseln Sie besser zu einer anderen Client-Implementierung. - [Transaktion mit Rust an Ethereum senden](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Eine Einführung in Smart Contracts mit dem Parity-Ethereum-Client](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/de/developers/docs/smart-contracts/deploying/index.md b/public/content/translations/de/developers/docs/smart-contracts/deploying/index.md index fe1aea23024..a418dd86bd3 100644 --- a/public/content/translations/de/developers/docs/smart-contracts/deploying/index.md +++ b/public/content/translations/de/developers/docs/smart-contracts/deploying/index.md @@ -27,7 +27,7 @@ Zu guter letzt muss ein Vertrag vor der Bereitstellung kompiliert werden. Lesen ### Schritte zur Bereitstellung eines Smart Contracts {#steps-to-deploy} -Die einzelnen Schritte hängen von den verwendeten Tools ab. Ein Beispiel dafür finden Sie in der [Hardhat-Dokumentation über die Bereitstellung Ihrer Verträge](https://hardhat.org/guides/deploying.html) oder in der [Truffle-Dokumentation über Netzwerke und die Bereitstellung von Anwendungen](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment). Das sind zwei der beliebtesten Tools für die Bereitstellung von Smart Contracts, bei denen ein Skript geschrieben werden muss, um die Bereitstellungsschritte durchzuführen. +Die einzelnen Schritte hängen von den verwendeten Tools ab. Ein Beispiel dafür finden Sie in der [Hardhat-Dokumentation über die Bereitstellung Ihrer Verträge](https://hardhat.org/guides/deploying.html). Das sind zwei der beliebtesten Tools für die Bereitstellung von Smart Contracts, bei denen ein Skript geschrieben werden muss, um die Bereitstellungsschritte durchzuführen. Sobald Ihr Smart Contract integriert ist, hat er eine Ethereum-Adresse, wie andere [-Konten](/developers/docs/accounts/). @@ -51,12 +51,6 @@ Sobald Ihr Smart Contract integriert ist, hat er eine Ethereum-Adresse, wie ande - [GitHub](https://github.com/nomiclabs/hardhat) - [Discord](https://discord.com/invite/TETZs2KK4k) -**Truffle –** **_Entwicklungsumgebung, Test-Framework, Build-Pipeline und weitere Tools_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [Dokumente über Netzwerke und Anwendungsbereitstellung](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) -- [GitHub](https://github.com/trufflesuite/truffle) - **thirdweb - _Einfache Bereitstellung eines beliebigen Vertrags für eine EVM-kompatible Blockchain mit einem einzigen Befehl_** - [Dokumentation](https://portal.thirdweb.com/deploy/) diff --git a/public/content/translations/de/developers/docs/smart-contracts/testing/index.md b/public/content/translations/de/developers/docs/smart-contracts/testing/index.md index f705599b516..c76d7379942 100644 --- a/public/content/translations/de/developers/docs/smart-contracts/testing/index.md +++ b/public/content/translations/de/developers/docs/smart-contracts/testing/index.md @@ -34,13 +34,11 @@ incomplete: true ## Verwandte Tutorials {#related-tutorials} -- [Solidity and Truffle Continuous Integration Setup](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) _ – So richten Sie Travis oder Circle CI für Trüffel-Tests zusammen mit nützlichen Plugins ein._ - [Übersicht über Testprodukte](/developers/tutorials/guide-to-smart-contract-security-tools/) _ – Eine Übersicht und ein Vergleich verschiedener Testprodukte_ - [So verwenden Sie Echidna zum Testen von Smart Contracts](/developers/tutorials/how-to-use-echidna-to-test-smart-contracts/) - [So finden Sie mit Manticore Fehler in Smart Contracts](/developers/tutorials/how-to-use-manticore-to-find-smart-contract-bugs/) - [So finden Sie mit Slither Fehler in Smart Contracts](/developers/tutorials/how-to-use-slither-to-find-smart-contract-bugs/) - [So simulieren Sie Solidity-Verträge zum Testen](/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -- [So migrieren Sie von Truffle-Tests zur OpenZeppelin-Testumgebung](https://docs.openzeppelin.com/test-environment/0.1/migrating-from-truffle) - [So testen Sie Verträge, nachdem sie in einem Netzwerk bereitgestellt wurden](https://fulldecent.blogspot.com/2019/04/testing-deployed-ethereum-contracts.html) ## Weiterführende Informationen {#further-reading} diff --git a/public/content/translations/de/enterprise/index.md b/public/content/translations/de/enterprise/index.md index 58474ee5367..a111ef40c17 100644 --- a/public/content/translations/de/enterprise/index.md +++ b/public/content/translations/de/enterprise/index.md @@ -68,7 +68,6 @@ Verschiedene Organisationen unternahmen gemeinsame Anstrengungen, um Ethereum un - [Ernst & Youngs 'Nightfall'](https://github.com/EYBlockchain/nightfall) _ein Toolkit für private Transaktionen_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _eine Transaktionssignierungsanwendung zur Verwendung mit einem Web3-Anbieter_ - [Tenderly](https://tenderly.co/) _, eine Datenplattform, die Echtzeit-Analysen, Alarmierung und Überwachung mit Unterstützung für private Netzwerke bereitstellt_ -- [Truffle Suite](https://trufflesuite.com) _Blockchain Development Suite (Truffle, Ganache, Drizzle)_ ### Skalierungslösungen {#scalability-solutions} diff --git a/public/content/translations/el/community/support/index.md b/public/content/translations/el/community/support/index.md index d81c1ddc37a..05aa82b3083 100644 --- a/public/content/translations/el/community/support/index.md +++ b/public/content/translations/el/community/support/index.md @@ -73,7 +73,6 @@ lang: el - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/es/community/support/index.md b/public/content/translations/es/community/support/index.md index 97886c53823..0aefcdecfb3 100644 --- a/public/content/translations/es/community/support/index.md +++ b/public/content/translations/es/community/support/index.md @@ -57,7 +57,6 @@ He aquí algunos ejemplos: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/es/developers/docs/bridges/index.md b/public/content/translations/es/developers/docs/bridges/index.md index a2a48c774a8..1709eb7eca9 100644 --- a/public/content/translations/es/developers/docs/bridges/index.md +++ b/public/content/translations/es/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Si una dapp va por la ruta de integrar un puente o un agregador, hay diferentes ### Implementar una dapp en múltiples cadenas {#deploying-a-dapp-on-multiple-chains} -Para implementar una dapp en múltiples cadenas, los desarrolladores pueden usar plataformas de desarrollo como [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/), etc. Por lo general, estas plataformas vienen con complementos componibles que pueden permitir que las dapps se hagan multicadena o se usen en otras. Por ejemplo, los desarrolladores pueden usar un proxy de implementación determinista ofrecido por el [complemento hardhat-deploy](https://github.com/wighawag/hardhat-deploy). +Para implementar una dapp en múltiples cadenas, los desarrolladores pueden usar plataformas de desarrollo como [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/), etc. Por lo general, estas plataformas vienen con complementos componibles que pueden permitir que las dapps se hagan multicadena o se usen en otras. Por ejemplo, los desarrolladores pueden usar un proxy de implementación determinista ofrecido por el [complemento hardhat-deploy](https://github.com/wighawag/hardhat-deploy). #### Ejemplos: diff --git a/public/content/translations/es/developers/docs/development-networks/index.md b/public/content/translations/es/developers/docs/development-networks/index.md index 4e8801f4265..56241aa3668 100644 --- a/public/content/translations/es/developers/docs/development-networks/index.md +++ b/public/content/translations/es/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ _Podría_ [ejecutar un nodo](/developers/docs/nodes-and-clients/#running-your-ow **Nota**: La mayoría de los [frameworks de desarrollo](/developers/docs/frameworks/) incluyen una red de desarrollo integrada. Te recomendamos comenzar con un framework para [configurar tu entorno de desarrollo local](/developers/local-environment/). -### Ganache {#ganache} - -Rápidamente inicia una blockchain de Ethereum personal con el que puedes ejecutar pruebas y comandos, así como inspeccionar el estado mientras controlas el funcionamiento de la cadena. - -Ganache proporciona una aplicación de escritorio (Ganache UI) y una herramientas de línea de comandos (`ganache-cli`). Forma parte del conjunto de herramientas Truffle. - -- [Sitio web](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentación](https://www.trufflesuite.com/docs/ganache/overview) - ### Red de tipo Hardhat {#hardhat-network} Una red local de Ethereum diseñada para el desarrollo. Le permite implementar sus contratos, ejecutar sus pruebas y depurar su código. diff --git a/public/content/translations/es/developers/docs/frameworks/index.md b/public/content/translations/es/developers/docs/frameworks/index.md index 05cc51c2aa4..21dea9d5872 100644 --- a/public/content/translations/es/developers/docs/frameworks/index.md +++ b/public/content/translations/es/developers/docs/frameworks/index.md @@ -93,12 +93,6 @@ Antes de profundizar en los marcos o frameworks, le recomendamos que lea nuestra - [GitHub](https://github.com/eth-brownie/brownie) - **Brownie se encuentra actualmente en mantenimiento** -**Truffle:** **_Un entorno de desarrollo y de pruebas, un proceso de creación y otras herramientas._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **El desarrollo de Truffle ha finalizado** - [leer más](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK: ****_El kit definitivo de herramientas para contratos inteligentes; una serie de herramientas que lo ayuda a desarrollar, compilar, actualizar, implementar e interactuar con contratos inteligentes._** - [SDK de OpenZeppelin](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/es/developers/docs/programming-languages/dart/index.md b/public/content/translations/es/developers/docs/programming-languages/dart/index.md index eca9a226453..3dded530edd 100644 --- a/public/content/translations/es/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/es/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutoriales {#tutorials} - [Flutter and Blockchain – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) le muestra los pasos para comenzar: - 1. Cómo instalar el [conjunto de herramientas de desarrollo de Truffle](https://www.trufflesuite.com/) - 2. Cómo escribir un contrato inteligente en [Solidity](https://soliditylang.org/) - 3. Cómo escribir una interfaz de usuario en Dart + 1. Cómo escribir un contrato inteligente en [Solidity](https://soliditylang.org/) + 2. Cómo escribir una interfaz de usuario en Dart - [Crear una dapp móvil con Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) es mucho más breve, lo que puede ser mejor si ya sabe lo básico. - Si prefiere aprender viendo un video, puedes ver [Construya su primera aplicación de Flutter con la cadena de bloques](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), que dura aproximadamente una hora - Si es impaciente, tal vez prefiera [Crear una app decentralizada de cadena de bloques con Flutter y Dart en Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), que dura solo veinte minutos. diff --git a/public/content/translations/es/developers/docs/programming-languages/golang/index.md b/public/content/translations/es/developers/docs/programming-languages/golang/index.md index 55c10e8c8c2..77bd5af0db6 100644 --- a/public/content/translations/es/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/es/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Usa Ethereum para crear aplicaciones descentralizadas (o "dapps"). Estas dapps p ## Artículos y libros para principiantes {#beginner-articles-and-books} -- [Seleccionar a un cliente de Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Comenzar con Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Usar Golang para conectarte a Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Implementar contratos inteligentes de Ethereum mediante Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/es/developers/docs/programming-languages/rust/index.md b/public/content/translations/es/developers/docs/programming-languages/rust/index.md index fb77f5aa4b6..460c3959140 100644 --- a/public/content/translations/es/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/es/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Utiliza Ethereum para crear aplicaciones descentralizadas (o "dapps"), que aprov ## Artículos para principiantes {#beginner-articles} -- [Seleccionar a un cliente de Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [El cliente Ethereum de Rust](https://openethereum.github.io/)\***Note que OpenEthereum [ha quedado obsoleto](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) y no se mantiene.** Úselo con precaución y preferiblemente cambie a otro cliente. - [Enviar una transacción a Ethereum mediante Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Tutorial paso a paso sobre cómo escribir contratos en Rust Wasm para Kovan](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/es/developers/docs/security/index.md b/public/content/translations/es/developers/docs/security/index.md index d2f4e59c036..9d321396909 100644 --- a/public/content/translations/es/developers/docs/security/index.md +++ b/public/content/translations/es/developers/docs/security/index.md @@ -29,7 +29,7 @@ Como mínimo: - Todo el código almacenado en un sistema de control de versiones, como git - Todas las modificaciones de código hechas a través de solicitudes de pull - Todas las solicitudes de pull tienen, al menos, un revisor. _Si tu proyecto es individual, plantéate encontrar a otro autor de proyecto individual para realizar revisiones de código._ -- Un solo comando compila, implementa y ejecuta un conjunto de pruebas con respecto a tu código mediante un entorno de desarrollo Ethereum (consulta: Truffle) +- Un solo comando compila, implementa y ejecuta un conjunto de pruebas con respecto a tu código mediante un entorno de desarrollo Ethereum - Has ejecutado tu código a través de herramientas de análisis de código básicas como Mythril y Slither, idealmente antes de que cada solicitud de pull se fusione, comparando diferencias en la salida - Solidity no emite ninguna advertencia del compilador - Tu código está bien documentado diff --git a/public/content/translations/es/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/es/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index 4e5f47b108e..00000000000 --- a/public/content/translations/es/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Crear e implementar una aplicación DeFi -description: Deposite tokens ERC20 en el contrato inteligente y mintee Farme Tokens -author: "strykerin" -tags: - - "solidez" - - "defi" - - "web3.js" - - "truffle" - - "ganache" - - "contratos inteligentes" -skill: intermediate -lang: es -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -En este tutorial crearemos una aplicación DeFi con Solidity donde los usuarios pueden depositar un token ERC20 en el contrato inteligente y este minteará y transferirá Farm Tokens. Los usuarios pueden retirar más tarde sus tokens ERC20 quemando su Farm Token en un contrato inteligente, y se les devolverán los tokens ERC20. - -## Instalar Truffle y Ganache {#install-truffle-and-ganache} - -Si es la primera vez que escribe un contrato inteligente, deberá configurar su entorno. Vamos a utilizar dos herramientas: [Truffle](https://www.trufflesuite.com/) y [Ganache](https://www.trufflesuite.com/ganache). - -Truffle es un entorno de desarrollo y marco de pruebas para desarrollar contratos inteligentes para Ethereum. Con Truffle es fácil crear e implementar contratos inteligentes en la cadena de bloques. Ganache nos permite crear una cadena de bloques de Ethereum local para probar contratos inteligentes. Simula las características de la red real y las primeras 10 cuentas cuentan con 100 ether de prueba, lo que hace que la implementación y las pruebas de contratos inteligentes sean gratuitas y fáciles. Ganache está disponible como aplicación de escritorio y herramienta de línea de comandos. Para este artículo usaremos la aplicación de escritorio de UI. - -![Aplicación de escritorio de UI de Ganache](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Aplicación de escritorio de UI de Ganache_ - -Para crear el proyecto, ejecute los siguientes comandos: - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Esto creará un proyecto en blanco para el desarrollo e implementación de nuestros contratos inteligentes. La estructura de proyecto creada es la siguiente: - -- `contracts`: Carpeta para los contratos inteligentes de Solidity - -- `migrations`: Carpeta para los scripts de implementación - -- `test`: Carpeta para probar nuestros contratos inteligentes - -- `truffle-config.js`: Archivo de configuración Truffle - -## Crear el token ERC20 {#create-the-erc20-token} - -Primero necesitamos crear nuestro token ERC20 que utilizaremos para apostar, o hacer staking, en el contrato inteligente. Para crear nuestro token fungible, primero necesitamos instalar la biblioteca OpenZeppelin. Esta biblioteca contiene las implementaciones de estándares como ERC20 y ERC721. Para instalarla, ejecute el comando: - -```bash -npm install @openzeppelin/contracts -``` - -Utilizando la biblioteca OpenZeppelin podemos crear nuestro token ERC20 escribiendo a `contracts/MyToken.sol` con el siguiente código de Solidity: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -En el código de arriba en: - -- Línea 3: Importamos el contrato ERC-20.sol desde openzeppelin que contiene la implementación para este estándar de tokens. - -- Línea 5: Heredamos desde el contrato ERC-20.sol. - -- Línea 6: Estamos llamando al contructor ERC20.sol y pasando los parámetros de nombre y símbolo como `"MyToken"` y `"MTKN"`, respectivamente. - -- Línea 7: Estamos minteando y transfiriendo 1 millon de tokens para la cuenta que está implementando el contrato inteligente (estamos usando los 18 decimales por defecto del token ERC20; eso significa que, si queremos mintear 1 token, lo representaremos como 1000000000000000000, 1 con 18 ceros). - -Debajo podemos ver la implementacion del constructor ERC20.sol, donde el campo `_decimals` está establecido en 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compilar el token ERC20 {#compile-the-erc20-token} - -Para compilar nuestro contrato inteligente, primer debemos verificar la versión de nuestro compilador de Solidity. Puede verificarla ejecutando el comando: - -```bash -truffle version -``` - -La versión por defecto es `Solidity v0.5.16`. Como nuestro token está escrito usando la versión de Solidity `0.6.2`, si corremos el comando para compilar nuestros contratos, obtendremos un error de compilador. Para especificar qué versión del compilador de Solidity usar, vaya al archivo `truffle-config.js` y establezca la versión deseada del compilador como se ve a continuación: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Ahora podemos compilar nuestro contrato inteligente ejecutando el siguiente comando: - -```bash -truffle compile -``` - -## Implementar el token ERC20 {#deploy-erc20-token} - -Despues de compilar, ahora podemos implementar nuestro token. - -En la carpeta `migrations`, cree un archivo llamado `2_deploy_Tokens.js`. Este archivo es donde vamos a implementar tanto nuestro token ERC20 como nuestro contrato inteligente FarmToken. El siguiente código se utiliza para implementar nuestro contrato MyToken.sol: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Abra Ganache y seleccione la opción "Quickstart" para comenzar una cadena de bloques local de Ethereum. Para implementar nuestro contrato, ejecute: - -```bash -truffle migrate -``` - -La dirección utilizada para implementar nuestros contratos es la primera de la lista de direcciones que Ganache nos muestra. Para verificarlo, podemos abrir la aplicacion de escritorio de Ganache y verificar que el saldo de ether de nuestra primera cuenta haya sido reducido debido al costo de ether para implementar nuestros contratos inteligentes: - -![Aplicación de escritorio de Ganache](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Aplicación de escritorio de Ganache_ - -Para verificar que se hayan enviado 1 millón de tokens de MyToken a la dirección del implementador, podemos usar la consola de Truffle para interactuar con nuestro contrato inteligente implementado. - -> [Truffle Console es una consola básica e interactiva que se conecta con cualquier cliente de Ethereum.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Para poder interactuar con nuestro contrato inteligente, ejecute el siguiente comando: - -```bash -truffle console -``` - -Ahora podemos escribir los siguientes comandos en el terminal: - -- Obtener el contrato inteligente: `myToken = await MyToken.deployed()` - -- Obtener el array de cuentas de Ganache: `accounts = await web3.eth.getAccounts()` - -- Obtener el saldo de la primera cuenta: `balance = await myToken.balanceOf(accounts[0])` - -- Formatear el saldo a partir de 18 decimales: `web3.utils.fromWei(balance.toString())` - -Al ejecutar los comandos de arriba, veremos que la primera dirección tiene de hecho 1 millón de MyTokens: - -![La primera dirección tiene 1000000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_La primera dirección tiene 1000000 MyTokens_ - -## Crear un contrato inteligente FarmToken {#create-farmtoken-smart-contract} - -El contrato inteligente FarmToken tendrá 3 funciones: - -- `balance()`: Obtener el saldo de MyToken en el contrato inteligente FarmToken. - -- `deposit(uint256 _amount)`: Transferir MyToken en nombre del usuario al contrato inteligente FarmToken y luego mintear y transferir FarmToken al usuario. - -- `withdraw(uint256 _amount)`: Quemar FarmTokens del usuario y transferir MyTokens a la dirección del usuario. - -Veamos el constructor de FarmToken: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Líneas 3-6: Importamos los siguientes contratos de openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol y ERC20.sol. - -- Línea 8: El FarmToken heredará del contrato ERC20. - -- Líneas 14-19: El constructor de FarmToken recibirá como parámetro la dirección del contrato MyToken y asignará su contrato a nuestra variable pública llamada `token`. - -Vamos a implementar la función `balance()`. No recibirá ningún parámetro y devolverá el saldo de MyToken en este contrato inteligente. Se implementa así: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -Para la función `deposite(uint256 _amount)`, recibirá como parámetro la cantidad que el usuario quiere depositar y minteará y transferirá FarmTokens al usuario: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -Para la función `withdraw(uint256 _amount)`, recibiremos como parámetro la cantidad de FarmTokens que el usuario desea quemar y luego transferir la misma cantidad de MyTokens de vuelta al usuario: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Ahora implementaremos nuestro contrato inteligente. Para hacerlo, regresaremos al archivo `2_deploy_Tokens.js` y agregaremos el nuevo contrato que se va a implementar: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Tenga en cuenta que, al implementar FarmToken, pasamos como parámetro la dirección del contrato implementado MyToken. - -Ahora, ejecute `truffle compile` y `truffle migrate` para implementar nuestros contratos. - -Probemos nuestro contrato inteligente. En lugar de usar la `consola de truffle` para interactuar con nuestro contrato inteligente, crearemos un script para automatizar este proceso. Cree una carpeta llamada `scripts` y añada el siguiente archivo `getMyTokenBalance.js`. Comprobará el saldo de MyTokens en el contrato inteligente FarmToken: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Para ejecutar este script, ejecute el siguiente comando de CLI: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Obtendremos el resultado esperado, que es 0. Si recibe un error que indica que el FarmToken aún no se implementó, se debe a que la red de Truffle no ha recibido la última versión del código de su contrato. Cierre Ganache, vuelva a iniciarlo y asegúrese de ejecutar `truffle migrate`. - -Ahora, vamos a apostar MyToken en el contrato inteligente. Puesto que la función `deposit(uint256 _amount)` llama a la función `safeTransferFrom` desde el ERC20, el usuario debe aprobar primero el contrato inteligente para transferir MyToken en nombre del usuario. Así que, en el siguiente script, primero aprobaremos este paso y luego llamaremos a la función: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Para ejecutar este script: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Debería ver en la consola: - -![salida de transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_salida de transferMyTokenToFarmToken.js_ - -Como podemos ver, hemos depositado exitosamente MyTokens en el contrato inteligente, ya que la primera cuenta ahora tiene FarmTokens. - -Para poder retirar: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Para ejecutar este script: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. Como podemos ver a continuación, hemos recuperado con éxito los MyTokens y quemado los FarmTokens: - -![salida de DropMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_salida de DropMyTokenFromTokenFarm.js_ - -## Referencias {#references} - -[Contratos: documentos OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/) - -[Sweet Tools for Smart Contracts | Truffle Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[¿Qué es DeFi? Guía para principiantes (actualizado 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - La tabla de clasificación de finanzas descentralizadas en DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/es/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/es/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index eb98be8eb16..8f0bc7b21ce 100644 --- a/public/content/translations/es/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/es/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "contratos inteligentes" - "almacenamiento" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Este límite se introdujo para prevenir ataques de denegación de servicio (DOS) Originalmente esto era un problema menor porque el tamaño natural de un contrato es el límite de gas de un bloque. Obviamente, un contrato debe implementarse dentro de una transacción que contenga todo el código de bytes del contrato. Si incluye solo esa transacción en un bloque, puede usar todo ese gas, pero no es infinito. Desde la [Actualización London](/history/#london), el límite de gas de un bloque ha podido variar entre 15 millones y 30 millones de unidades dependiendo de la demanda de la red. -## Asuma el reto {#taking-on-the-fight} - -Desafortunadamente, no hay una manera fácil de obtener el tamaño del código de bytes de sus contratos. Una gran herramienta que lo ayudará es el complemento [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) si usa Truffle. - -1. `npm install truffle-contract-size` -2. Añadir el complemento a _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Ejecutar `truffle run contract-size` - -Esto le ayudará a averiguar cómo sus cambios están afectando los tamaños totales del contrato. - A continuación veremos algunos métodos ordenados según su posible impacto. Piénsalo en términos de pérdida de peso. La mejor estrategia para que alguien alcance su peso deseado (en nuestro caso 24kb) es centrarse primero en los métodos de gran impacto. En la mayoría de los casos, basta con corregir la dieta para conseguirlo, pero a veces se necesita un poco más. Luego puedes añadir algo de ejercicio (impacto medio) o incluso suplementos (impacto bajo). ## Gran impacto {#big-impact} diff --git a/public/content/translations/es/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/es/developers/tutorials/secure-development-workflow/index.md index 534a5d3f10b..857267bbf7c 100644 --- a/public/content/translations/es/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/es/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Tenga en cuenta las características especiales de su contrato: - ¿Sus contratos pueden mejorarse? Revise su código de mejora para errores con [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) o [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). Hemos documentado 17 formas en que las actualizaciones pueden fallar. - ¿Sus contratos pretenden ajustarse a los ERC? Compruébalos con [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). Esta herramienta identifica instantáneamente las desviaciones de seis especificaciones comunes. -- ¿Tienes pruebas unitarias en Truffle? Compleméntelos con [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation). Genera automáticamente un robusto conjunto de propiedades de seguridad para las funciones de ERC20 basadas en su código específico. - ¿Se integra con tókenes de terceros? Revise nuestra [lista de verificación de integración de tókenes](/developers/tutorials/token-integration-checklist/) antes de depender de contratos externos. Inspeccione visualmente las características de seguridad críticas de su código: diff --git a/public/content/translations/es/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/es/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 1f2c49d3ff7..00000000000 --- a/public/content/translations/es/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Configuración de integración continua de Solidity y Truffle" -description: Cómo configurar Travis o Circle CI para pruebas de Truffle junto con complementos útiles -author: Markus Waas -lang: es -tags: - - "solidity" - - "contratos inteligentes" - - "pruebas" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -La integración continua (CI) con Truffle es genial para el desarrollo una vez que se implementa un conjunto básico de pruebas. Le permite realizar pruebas muy largas, asegurarse de que todas las pruebas pasen antes de combinar una [solicitud de pull](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) y llevar un seguimiento de varias estadísticas utilizando herramientas adicionales. - -Utilizaremos el [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) para configurar nuestra integración continua. Puede elegir Travis CI o Circle CI. - -## Configurar Travis CI {#setting-up-travis-ci} - -Añadir [Travis CI](https://travis-ci.org/) es sencillo. Solo necesitará añadir un archivo de configuración `.travis.yml` a la carpeta raíz del proyecto: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Lo haremos simple por ahora y solo ejecutaremos el script de prueba que ejecuta las pruebas unitarias o individuales de Truffle. Pero tenemos un problema, no habrá una cadena de bloques disponible en la máquina de Travis CI. Una solución simple para esto es `npm install ganache-cli` y simplemente ejecutarlo antes de la prueba. Puede hacer esto agregando un bash script con la línea npx `ganache-cli > 7dev/null` y antes de la llamada `npx truffle test`. El [bash script de ejemplo completo](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Configurar Circle CI {#setting-up-circle-ci} - -[CircleCI](https://circleci.com/) requiere un archivo de configuración más grande. El comando adicional [`npm ci`](https://docs.npmjs.com/cli/ci.html) se hace automáticante en Travis. Instala las dependencias más rápido y de forma más segura que `npm install`. Otra vez usamos el mismo script de la versión de Travis para ejecutar ganache-cli antes de las pruebas. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Añadir el complemento eth-gas-reporter {#adding-the-eth-gas-reporter-plugin} - -El complemento eth-gas-reporter es muy útil para llevar un seguimiento de los costos de gas de las funciones de su contrato inteligente. Tenerlo en su CI será útil además para mostrar diferencias cuando se agreguen solicitudes de pull. - -### Paso 1: Instalar el complemento eth-gas-reporter y comprobaciones de código {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Paso 2: Agrega el complemento a la configuración de moca dentro de su truffle-config.js {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Ver opciones](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Paso 3: Agregar un codechecks.yml al directorio raíz de su proyecto {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Paso 4: Ejecutar comprobaciones de código después del comando de prueba {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Paso 5: Crear una cuenta de Codechecks {#step-5-create-a-codechecks-account} - -- Cree una cuenta con [Codechecks](http://codechecks.io/). -- Agregue el repositorio de GitHub a ella. -- Copie el secreto y agregue el `CC_SECRET=COPIED SECRET` a su CI (vea aquí para [Travis](https://docs.travis-ci.com/user/environment-variables/), aquí para [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Ahora cree una solicitud de pull. - -Eso es todo. Ahora encontrará un buen reporte acerca de los cambios en los costos del gas de sus solicitud de pull. - -![Reportes de gas de ejemplo](./gas-reports.png) - -## Agregar el complemento solidity-coverage {#adding-the-solidity-coverage-plugin} - -Con el complemento solidity-coverage puede chequear cuánto de sus rutas de código están cubiertas por sus pruebas. Agregar esto a su CI es muy conveniente una vez hecha la configuración. - -### Paso 1: Crear un proyecto de metacoin e instalar herramientas de cobertura {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### Paso 2: Agregar solidity-coverage a la matriz de complementos en truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Paso 3: Agregar los comandos de cobertura al .travis.yml o Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -La cobertura de Solidity inicia su propio ganache-cli, así que no tenemos que preocuparnos de esto. Sin embargo, no remplace el comando de prueba normal, la cobertura de ganache-cli funciona diferente y es por lo tanto no reemplazable para ejecutar pruebas unitarias regulares. - -### Step 4: Agregar repositorio a Coveralls {#step-4-add-repository-to-coveralls} - -- Cree una cuenta con [Coveralls](https://coveralls.io/). -- Agregue el repositorio de GitHub a ella. -- Ahora cree una solicitud de pull. - -![Ejemplo de coverall](./coverall.png) - -## Otras ideas {#further-ideas} - -- [MythX](https://mythx.io/): Con MythX puede analizar automáticamente la seguridad de su contrato inteligente. Así que tiene mucho sentido [agregar esto a su CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Un buen código puede ser aplicado hasta cierto grado con herramientas de linting. [Eslint](https://eslint.org/) funciona bien para JavaScript, es [fácil de configurar](https://eslint.org/docs/user-guide/getting-started), mientras que [Solhint](https://protofire.github.io/solhint/) se puede usar para Solidity. -- Pruebas largas: Algunas veces es posible que desee agregar pruebas extremas, p. ej., probar contratos con cientos de usuarios. Esto toma mucho tiempo. En lugar de ejecutarlos en cada ejecución de prueba, agréguelos a la CI. - -Ahí lo tiene. La integración continua es una estrategía muy útil para sus desarrollos. Puede ver un ejemplo completo en [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Solo asegúrese de eliminar Circle-CI o Travis, ¡con uno es suficiente! diff --git a/public/content/translations/es/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/es/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index a405996fb9e..1a7656ccb12 100644 --- a/public/content/translations/es/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/es/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ El manifiesto es nuestro archivo de configuración y define: - otros aspectos a escuchar, como llamadas a funciones o bloques - las funciones de mapeo invocadas (ver `mapping.ts` abajo) -Puede definir múltiples contratos y manejadores (handlers) aquí. Una configuración típica tendría una carpeta de subgraphs dentro del proyecto Truffle/Hardhat con su propio repositorio. Luego puede referenciar fácilmente el ABI. +Puede definir múltiples contratos y manejadores (handlers) aquí. Una configuración típica tendría una carpeta de subgraphs dentro del proyecto Hardhat con su propio repositorio. Luego puede referenciar fácilmente el ABI. Por razones de conveniencia también puede querer usar una herramienta de plantillas como mustache. Luego creará un `subgraph.template.yaml` e insertará las direcciones con base en las últimas implementaciones. Para una configuración de ejemplo más avanzada, vea por ejemplo el [repositorio de subgraphs de Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/es/enterprise/index.md b/public/content/translations/es/enterprise/index.md index b963da6d5bf..79d89a36545 100644 --- a/public/content/translations/es/enterprise/index.md +++ b/public/content/translations/es/enterprise/index.md @@ -72,7 +72,6 @@ Diferentes organizaciones han emprendido iniciativas de colaboración para que E - [Ernst & Nightfall's "Nightfall"](https://github.com/EYBlockchain/nightfall) _: un conjunto de herramientas para realizar transacciones privadas_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _: una aplicación de firmado de transacción para utilizarse con un proveedor de web3_ - [Anteriormente](https://tenderly.co/) _era una plataforma de datos que proporciona análisis en tiempo real, alertas y monitoreo con soporte para redes privadas._ -- [Truffle Suite:](https://trufflesuite.com) _suite de desarrollo de cadena de bloques (Truffle, Ganache, Drizzle)_ ### Soluciones de escalabilidad {#scalability-solutions} diff --git a/public/content/translations/fa/community/support/index.md b/public/content/translations/fa/community/support/index.md index 457ca28d9a4..0e27feb5330 100644 --- a/public/content/translations/fa/community/support/index.md +++ b/public/content/translations/fa/community/support/index.md @@ -57,7 +57,6 @@ _این یک فهرست جامع نیست. برای پیدا کردن پشتیب - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/fi/enterprise/index.md b/public/content/translations/fi/enterprise/index.md index aab9de6a63b..e4548446971 100644 --- a/public/content/translations/fi/enterprise/index.md +++ b/public/content/translations/fi/enterprise/index.md @@ -75,7 +75,6 @@ Julkiset ja yksityiset Ethereum-verkot saattavat tarvita tiettyjä ominaisuuksia - [Alethio](https://explorer.aleth.io/) _Ethereumin data-analytiikka-alusta_ - [Treum](https://treum.io/) _tuo läpinäkyvyyttä, jäljitettävyyttä ja vaihdettavuutta toimitusketjuille lohkoketjuteknologiaa hyödyntäen_ -- [Truffle Suite](https://trufflesuite.com) _lohkoketjujen kehityskokoelma (Truffle, Ganache, Drizzle)_ ## Yrityskehitysyhteisö {#enterprise-developer-community} diff --git a/public/content/translations/fr/community/support/index.md b/public/content/translations/fr/community/support/index.md index e9711889ee3..e915c9bad33 100644 --- a/public/content/translations/fr/community/support/index.md +++ b/public/content/translations/fr/community/support/index.md @@ -73,7 +73,6 @@ Voici quelques exemples connus : - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/fr/developers/docs/bridges/index.md b/public/content/translations/fr/developers/docs/bridges/index.md index a5e6d7d082d..69527a87bab 100644 --- a/public/content/translations/fr/developers/docs/bridges/index.md +++ b/public/content/translations/fr/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Si une dapp emprunte la voie de l'intégration d'un pont ou d'un agrégateur, il ### Déploiement d'une dApp sur plusieurs chaînes {#deploying-a-dapp-on-multiple-chains} -Pour déployer une dApp sur plusieurs chaînes, les développeurs peuvent utiliser des plateformes de développement telles que [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/), etc. En général, ces plateformes sont fournies avec des plugins composables qui permettent aux dApps de passer d'une chaîne à l'autre. Par exemple, les développeurs peuvent utiliser un proxy de déploiement déterministe proposé par le plugin [hardhat-deploy](https://github.com/wighawag/hardhat-deploy). +Pour déployer une dApp sur plusieurs chaînes, les développeurs peuvent utiliser des plateformes de développement telles que [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/), etc. En général, ces plateformes sont fournies avec des plugins composables qui permettent aux dApps de passer d'une chaîne à l'autre. Par exemple, les développeurs peuvent utiliser un proxy de déploiement déterministe proposé par le plugin [hardhat-deploy](https://github.com/wighawag/hardhat-deploy). #### Exemples : diff --git a/public/content/translations/fr/developers/docs/development-networks/index.md b/public/content/translations/fr/developers/docs/development-networks/index.md index 0337da8867b..cd9e8a20cb2 100644 --- a/public/content/translations/fr/developers/docs/development-networks/index.md +++ b/public/content/translations/fr/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Vous _pourriez_ [ exécuter un nœud](/developers/docs/nodes-and-clients/#runnin **Remarque** : La plupart des [cadres de développement](/developers/docs/frameworks/) incluent un réseau de développement intégré. Nous recommandons de démarrer avec un cadre pour [configurer votre environnement de développement local](/developers/local-environment/). -### Ganache {#ganache} - -Lance rapidement une blockchain Ethereum personnelle que vous pouvez utiliser pour exécuter des tests et des commandes, et inspecter l'état tout en contrôlant comment la chaîne opère. - -Ganache fournit une interface (Ganache UI), ainsi qu'un outil en ligne de commande (`ganache-cli`). C'est un élément de la suite d'outils Truffle. - -- [Site Web](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentation](https://www.trufflesuite.com/docs/ganache/overview) - ### Réseau Hardhat {#hardhat-network} Un réseau Ethereum local conçu pour le développement. Il vous permet de déployer vos contrats, d'effectuer vos tests et de déboguer votre code. diff --git a/public/content/translations/fr/developers/docs/frameworks/index.md b/public/content/translations/fr/developers/docs/frameworks/index.md index 184d2fdd81b..9b81ef11338 100644 --- a/public/content/translations/fr/developers/docs/frameworks/index.md +++ b/public/content/translations/fr/developers/docs/frameworks/index.md @@ -93,12 +93,6 @@ Avant de plonger dans les infrastructures, nous vous recommandons de commencer p - [GitHub](https://github.com/eth-brownie/brownie) - **Brownie n'est plus développé actuellement** -**Truffle -** **_ Environnement de développement, infrastructure de test, pipeline de construction et autres outils_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **Le développement de Truffle a été arrêté** - [en savoir plus](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK - \*\***_The Ultimate Smart Contract Toolkit : la suite d'outils par excellence pour vous aider à développer, compiler, mettre à niveau, déployer et interagir avec des contrats intelligents._\*\* - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/fr/developers/docs/programming-languages/dart/index.md b/public/content/translations/fr/developers/docs/programming-languages/dart/index.md index eaa11246a2e..9956feea4a7 100644 --- a/public/content/translations/fr/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/fr/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutos {#tutorials} - [Flutter et blockchain – la dApp Hello World](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) vous emmène à travers toutes les étapes pour bien débuter : - 1. Installer la suite de développement [Truffle](https://www.trufflesuite.com/) - 2. Écrire un contrat intelligent avec [Solidity](https://soliditylang.org/) - 3. Écrire une interface utilisateur avec Dart + 1. Écrire un contrat intelligent avec [Solidity](https://soliditylang.org/) + 2. Écrire une interface utilisateur avec Dart - [Créer une dApp mobile avec Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) est beaucoup plus court, ce qui pourrait mieux convenir si vous connaissez déjà les bases - Si vous préférez apprendre en regardant une vidéo, vous pouvez regarder [Elaborez votre première App Blockchain avec Flutter](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), en une heure. - Si vous êtes impatient, vous préférerez peut-être [créer une application décentralisée blockchain avec Flutter et Dart sur Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), en seulement vingt minutes. diff --git a/public/content/translations/fr/developers/docs/programming-languages/golang/index.md b/public/content/translations/fr/developers/docs/programming-languages/golang/index.md index af891dac5c7..3198d5c8789 100644 --- a/public/content/translations/fr/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/fr/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Besoin d’une approche plus élémentaire ? Consultez [ethereum.org/learn](/le ## Articles et livres pour les débutants {#beginner-articles-and-books} -- [Choisir un client Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Commencer avec Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Utiliser Golang pour se connecter à Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Déployer des contrats intelligents Ethereum en utilisant Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/fr/developers/docs/programming-languages/rust/index.md b/public/content/translations/fr/developers/docs/programming-languages/rust/index.md index f53bff6c209..dc7a22193fb 100644 --- a/public/content/translations/fr/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/fr/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Besoin d’une approche plus élémentaire ? Consultez [ethereum.org/learn](/le ## Articles pour les débutants {#beginner-articles} -- [Choisir un client Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Le client Rust Ethereum](https://openethereum.github.io/) **Veuillez noter que OpenEthereum [a été déprécié](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) et n'est plus maintenu.** Utilisez-le avec prudence et passez de préférence à une autre implémentation client. - [Envoi de la transaction à Ethereum en utilisant Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Un tutoriel sur la façon d'écrire des contrats dans Rust Wasm pour Kovan](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/fr/developers/docs/security/index.md b/public/content/translations/fr/developers/docs/security/index.md index a9c3661bd54..a6c101614c6 100644 --- a/public/content/translations/fr/developers/docs/security/index.md +++ b/public/content/translations/fr/developers/docs/security/index.md @@ -29,7 +29,7 @@ Il faut au minimum que : - tout le code soit stocké dans un système de contrôle de version comme git ; - toutes les modifications de code soient effectuées via des PR (Pull Requests) ; - toutes les PR aient au moins un réviseur ; _Si vous travaillez sur un projet en solo, envisagez de trouver un autre auteur solo pour négocier des révisions de code !_ -- une seule commande compile, déploie et exécute une suite de tests sur votre code en utilisant un environnement de développement Ethereum (Voir : Truffle) ; +- une seule commande compile, déploie et exécute une suite de tests sur votre code en utilisant un environnement de développement Ethereum; - vous ayez exécuté votre code via des outils d'analyse basiques comme Mythril et Slither, idéalement avant que chaque PR soit fusionnée, en comparant les différences de sortie ; - Solidity n'émette aucune alerte à la compilation ; - votre code soit bien documenté. diff --git a/public/content/translations/fr/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/fr/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index c3cbeb8dd43..00000000000 --- a/public/content/translations/fr/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Créer et déployer une application DeFi -description: Déposez des jetons ERC20 dans le contrat intelligent et générez des jetons Farm -author: "strykerin" -tags: - - "solidity" - - "DeFi" - - "web3.js" - - "truffle" - - "ganache" - - "contrats intelligents" -skill: intermediate -lang: fr -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -Dans ce tutoriel, nous allons créer une application DeFi avec Solidity dans laquelle les utilisateurs peuvent déposer un jeton ERC20 dans le contrat intelligent et ce jeton va générer et leur transférer des jetons Farm. Par la suite, les utilisateurs pourront retirer leurs jetons ERC20 en brûlant leur jeton Farm sur un contrat intelligent et les jetons ERC20 leur seront transférés en retour. - -## Installer Truffle et Ganache {#install-truffle-and-ganache} - -Si c'est votre première création de contrat intelligent, il vous faudra configurer votre environnement. Nous allons utiliser deux outils : [Truffle](https://www.trufflesuite.com/) et [Ganache](https://www.trufflesuite.com/ganache). - -Truffle est un environnement de développement et un framework de test pour l'établissement de contrats intelligents pour Ethereum. Avec Truffle, il est facile de créer et de déployer des contrats intelligents sur la blockchain. Ganache permet de créer une blockchain Ethereum locale afin de tester les contrats intelligents. Il simule les fonctionnalités du réseau réel et les 10 premiers comptes sont financés avec 100 éther de test, rendant ainsi le déploiement et le test du contrat intelligent gratuit et facile. Ganache est disponible en tant qu'application de bureau et outil de ligne de commande. Pour cet article nous allons utiliser l'application UI Desktop. - -![Application de bureau pour utilisateur Ganache (Ganache UI)](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Application de bureau pour utilisateur Ganache_ - -Pour créer notre projet, exécutez les commandes suivantes : - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Cela créera un projet vide pour l'établissement et le déploiement de nos contrats intelligents. La structure du projet créée est la suivante : - -- `test` : Dossier des contrats intelligents Solidity - -- `migrations` : Dossier des scripts de déploiement - -- `test` : Dossier pour tester nos contrats intelligents - -- `truffle-config.js` : Fichier de configuration Truffle - -## Créer un jeton ERC20 {#create-the-erc20-token} - -Nous devons premièrement créer notre jeton ERC20 que nous miserons dans le contrat intelligent. Pour créer notre jeton fongible, nous devrons commencer par installer la bibliothèque OpenZeppelin. Cette bibliothèque contient les implémentations de normes telles qu'ERC20 et ERC721. Pour l'installer, exécutez la commande : - -```bash -npm install @openzeppelin/contracts -``` - -En utilisant la bibliothèque OpenZeppelin nous pouvons créer notre jeton ERC20 en écrivant sur `contracts/MyToken.sol` avec le code de Solidity suivant : - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -Dans le code ci-dessus à la : - -- Ligne 3 : Nous importons le contrat ERC20.sol depuis openzeppelin qui contient l'implémentation de la norme de ce jeton. - -- Ligne 5 : Nous héritons du contrat ERC20.sol. - -- Ligne 6 : Nous appelons le constructeur ERC20.sol et passons le nom et les paramètres du symbole respectivement en tant que `"MyToken"` et `"MTKN"`. - -- Ligne 7 : Nous générons et transférons 1 million de jetons pour le compte qui déploie le contrat intelligent (nous utilisons les 18 décimales par défaut pour le jeton ERC20, ce qui signifie que si nous voulons générer 1 jeton, il se présentera sous la forme 1000000000000000000, 1 avec 18 zéros). - -Nous pouvons voir ci-dessous l'implémentation du constructeur ERC20.sol où le champ `_decimals` est défini à 18 : - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compiler le jeton ERC20 {#compile-the-erc20-token} - -Pour compiler notre contrat intelligent, nous devons d'abord vérifier notre version du compilateur de Solidity. Vous pouvez la vérifier en exécutant la commande : - -```bash -truffle version -``` - -La version par défaut est la version `Solidity v0.5.16`. Puisque notre jeton est écrit en utilisant la version Solidity `0.6.2`, si nous exécutons la commande pour compiler nos contrats, nous allons générer une erreur de compilation. Afin de spécifier quelle version de compilateur Solidity utiliser, allez dans le fichier `truffle-config.js` et définissez la version désirée du compilateur comme ci-dessous : - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Maintenant, nous pouvons compiler notre contrat intelligent en exécutant la commande suivante : - -```bash -truffle compile -``` - -## Déployer le jeton ERC20 {#deploy-erc20-token} - -Après la compilation, nous pouvons maintenant déployer notre jeton. - -Dans le dossier `migrations`, créez un fichier appelé `2_deploy_Tokens.js`. Ce fichier est l'endroit où nous allons déployer à la fois notre jeton ERC20 et notre contrat intelligent FarmToken. Le code ci-dessous est utilisé pour déployer notre contrat MyToken.sol : - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Ouvrez Ganache et sélectionnez l'option "Quickstart" pour démarrer une blockchain Ethereum en local. Pour déployer notre contrat, lancez : - -```bash -truffle migrate -``` - -L'adresse utilisée pour déployer nos contrats est la première de la liste d'adresses que Ganache nous indique. Pour vérifier, nous pouvons ouvrir l'application de bureau Ganache et ainsi vérifier que le solde d'ether pour le premier compte a été réduit en raison du coût d'ether pour déployer nos contrats intelligents : - -![Application de bureau Ganache](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Application de bureau Ganache_ - -Pour vérifier que 1 million de jetons MyToken ont été envoyés à l'adresse de déploiement, nous pouvons utiliser la console Truffle pour interagir avec notre contrat intelligent déployé. - -> [Truffle Console est une console interactive de base qui se connecte à n'importe quel client Ethereum.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Afin d'interagir avec notre contrat intelligent, exécutez la commande suivante : - -```bash -truffle console -``` - -Nous pouvons maintenant écrire les commandes suivantes dans le terminal : - -- Récupère le contrat intelligent : `myToken = await MyToken.deployed()` - -- Récupère le tableau de comptes depuis Ganache : `accounts = await web3.eth.getAccounts()` - -- Récupère le solde pour le premier compte : `balance = await myToken.balanceOf(accounts[0])` - -- Formate le solde à partir de 18 décimales : `web3.utils.fromWei(balance.toString())` - -En exécutant les commandes ci-dessus, nous constatons que la première adresse a en fait 1 million de MyTokens : - -![Première adresse à 1 000 000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_La première adresse dispose de 1 000 000 de MyTokens_ - -## Créer un Contrat Intelligent FarmToken {#create-farmtoken-smart-contract} - -Le contrat intelligent FarmToken aura 3 fonctions : - -- `balance()` : Transférer le solde de MyToken sur le contrat intelligent FarmToken. - -- `deposit(uint256 _amount)` : Transférer MyToken pour le compte de l'utilisateur sur le Contrat Intelligent FarmToken puis frapper et transférer FarmToken à l'utilisateur. - -- `withdraw(uint256 _amount)` : Brûler les FarmTokens de l'utilisateur et transférer MyTokens à l'adresse de l'utilisateur. - -Jetons un œil au constructeur FarmToken : - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Lignes 3-6 : Nous importons depuis openzeppelin les contrats suivants : IERC20.sol, Address.sol, SafeERC20.sol et ERC20.sol. - -- Ligne 8 : Le FarmToken héritera du contrat ERC20. - -- Lignes 14-19 : Le constructeur FarmToken recevra comme paramètre l'adresse du contrat MyToken et nous attribuerons son contrat à notre variable publique appelée `token`. - -Implémentons la fonction `balance()`. Elle ne recevra aucun paramètre et retournera le solde de MyToken sur ce contrat intelligent. Il s'implémente comme indiqué ci-dessous : - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -Pour la fonction `deposit(uint256 _amount)`, il recevra comme paramètre le montant que l'utilisateur veut déposer et il frappera et transférera FarmTokens à l'utilisateur : - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -Pour la fonction `withdraw(uint256 _amount)`, nous recevrons comme paramètre la quantité de FarmTokens que l'utilisateur veut brûler, puis transférerons la même quantité de MyTokens à l'utilisateur : - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Nous allons maintenant déployer notre contrat intelligent. Pour ce faire, nous retournerons au fichier `2_deploy_Tokens.js` et ajouterons le nouveau contrat à déployer : - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Notez que lors du déploiement du FarmToken, nous passons comme paramètre l'adresse du contrat MyToken déployé. - -Exécutez maintenant `truffle compile` et `truffle migrate` pour déployer nos contrats. - -Testons notre contrat intelligent. Au lieu d'utiliser la `console truffle` pour interagir avec notre contrat intelligent, nous allons créer un script pour automatiser ce processus. Créez un dossier appelé `scripts` et ajoutez le fichier suivant `getMyTokenBalance.js`. Il vérifiera le solde de MyTokens sur le contrat intelligent FarmToken : - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Pour exécuter ce script, exécutez la commande suivante : - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Nous obtiendrons le résultat attendu qui est 0. Si vous avez comme message d'erreur que FarmToken n'est pas encore déployé, cela signifie que le réseau truffle n'a pas reçu la dernière version du code du contrat. Fermez tout simplement ganache, démarrez-le à nouveau et veillez à exécuter `truffle migrate`. - -Maintenant, misons MyToken sur le contrat intelligent. Dès lors que la fonction `deposit(uint256 _amount)` appelle la fonction `safeTransferFrom` de l'ERC20, l'utilisateur doit d'abord approuver le contrat intelligent pour transférer MyToken en nom et place de l'utilisateur. Donc, sur le script ci-dessous, nous allons d'abord approuver cette étape puis nous appellerons la fonction : - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Pour exécuter ce script : `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Vous devriez voir sur votre console : - -![sortie de transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_sortie de transferMyTokenToFarmToken.js_ - -Comme nous pouvons le voir, nous avons déposé avec succès MyTokens sur le contrat intelligent car le premier compte est maintenant associé à FarmTokens. - -Afin de retirer : - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Pour exécuter ce script : `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Comme nous pouvons le constater avec l'exemple ci-dessous, nous avons réussi à récupérer les MyTokens et nous avons supprimé les FarmTokens : - -![sortie de withdrawMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_sortie de withdrawMyTokenFromTokenFarm.js_ - -## Références {#references} - -[Contrats - Documentation OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/) - -[Outils Sympas pour contrats intelligents | Suite Truffle](https://www.trufflesuite.com/) - -[Ganache | Suite Truffle](https://www.trufflesuite.com/ganache) - -[Qu'est-ce que DeFi ? Guide du débutant (mise à jour 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - Le classement de la finance décentralisée sur DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/fr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/fr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index c64d59f7f21..8a9cf541912 100644 --- a/public/content/translations/fr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/fr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "contrats intelligents" - "stockage" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Cette limite a été apportée pour empêcher les attaques par déni de service À l'origine, le problème était moins préoccupant, car la limite naturelle de la taille des contrats était la limite de gaz par bloc. Bien entendu, un contrat doit être déployé dans une transaction qui contient tout le bytecode du contrat. Si vous n'incluez ensuite que cette seule transaction dans un bloc, vous pourrez utiliser tout le gaz, mais il ne sera pas illimité. Depuis la [mise à niveau de Londres](/history/#london), la limite de gaz de bloc a pu varier entre 15M et 30M unités selon la demande du réseau. -## Relever le défi {#taking-on-the-fight} - -Malheureusement, il n'existe pas de moyen simple d'obtenir la taille du bytecode de vos contrats. Pour vous aider, le plugin [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) est un excellent outil si vous utilisez Truffle. - -1. `npm install truffle-contract-size` -2. Ajoutez le plugin au fichier _truffle-config.js_ : `plugins: ["truffle-contract-size"]` -3. Lancez `truffle run contract-size` - -Cela vous aidera à comprendre comment vos changements affectent la taille totale des contrats. - Dans les prochaines lignes, nous examinerons certaines méthodes classées en fonction de leur impact potentiel. Considérez ça comme perdre du poids. La meilleure stratégie pour atteindre son poids cible (dans notre cas, 24 kb) est de se concentrer en premier lieu sur les méthodes à fort impact. Dans la plupart des cas, il suffit de revoir son régime alimentaire pour y parvenir, mais il faut parfois aller un peu plus loin. Ensuite, vous pouvez ajouter à cela un peu d'exercice (impact modéré) ou même des suppléments (impact faible). ## Impact important {#big-impact} diff --git a/public/content/translations/fr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/fr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index b3305838ae9..00000000000 --- a/public/content/translations/fr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Configuration de l'intégration continue entre Solidy et Truffle" -description: Comment configurer Travis ou Circle CI pour les tests de Truffle avec des plugins utiles -author: Markus Waas -lang: fr -tags: - - "solidity" - - "contrats intelligents" - - "tests" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -L'intégration continue (CI) avec Truffle est idéale pour le développement une fois que vous avez un ensemble de tests de base implémentés. Elle vous permet de faire de très longs tests, s'assurer que tous les tests passent avant de fusionner une [pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) et garder une trace de diverses statistiques à l'aide d'outils supplémentaires. - -Nous utiliserons la [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) pour configurer notre intégration continue. Vous pouvez choisir entre Travis CI ou Circle CI. - -## Configuration de Travis CI {#setting-up-travis-ci} - -Ajouter [Travis CI](https://travis-ci.org/) est très simple. Vous n'avez qu'à ajouter un fichier de configuration `.travis.yml` au dossier racine du projet : - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Pour le moment, nous allons garder ça de façon aussi simple que possible et lancerons uniquement le script de test qui exécute les tests unitaires Truffle. Mais nous avons un problème : il n'y a pas de blockchain disponible sur la machine Travis CI. Un simple correctif à cela consiste à lancer `npm install ganache-cli` et simplement l'exécuter avant le test. Vous pouvez le faire en ajoutant un script bash avec la ligne npx `ganache-cli > /dev/null` et avant l'appel `npx truffle test`. L'[exemple complet du script bash](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Configuration de Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) nécessite un fichier de configuration plus long. La commande supplémentaire [`npm ci`](https://docs.npmjs.com/cli/ci.html) se fait automatiquement dans Travis. Elle installe les dépendances plus rapidement et de manière plus sécurisée que ne le fait `npm install`. Nous utilisons à nouveau le même script de la version Travis pour exécuter ganache-cli avant les tests. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Ajout du plugin eth-gas-reporter {#adding-the-eth-gas-reporter-plugin} - -Le plugin eth-gas-reporter est utile pour garder une trace des coûts de gaz de vos fonctions de contrat intelligent. L'avoir dans votre CI sera plus utile pour afficher des « diffs » lors de l'ajout de pull requests. - -### Étape 1 : Installez le plugin eth-gas-reporter et Codechecks {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Étape 2 : Ajoutez le plugin aux paramètres mocha dans votre truffle-config.js {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Voir les options](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Étape 3 : Ajouter un codechecks.yml à la racine de votre projet {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Étape 4 : Exécutez des Codechecks après la commande de test {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Étape 5 : Créer un compte Codechecks {#step-5-create-a-codechecks-account} - -- Créez un compte [Codechecks](http://codechecks.io/). -- Ajoutez-y le dépôt GitHub. -- Copiez le secret et ajoutez le `CC_SECRET=COPIED SECRET` à votre CI (voir ici pour [Travis](https://docs.travis-ci.com/user/environment-variables/), ici pour [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Maintenant, allez de l'avant et créez un pull request. - -C’est tout. Vous retrouverez maintenant un bon rapport sur les changements dans le coût du gaz de votre pull resquest. - -![Exemple de rapports de gaz](./gas-reports.png) - -## Ajout du plugin solidity-coverage {#adding-the-solidity-coverage-plugin} - -Avec le plugin solidity-coverage vous pouvez vérifier combien de chemins de code sont couverts par vos tests. Ajouter ceci à votre CI rend son utilisation très pratique une fois qu'il est configuré. - -### Étape 1 : Créer un projet Metacoin et installez des outils de couverture {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### Étape 2 : Ajouter solidity-coverage au tableau des plugins dans truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Étape 3 : Ajouter les commandes de couverture au fichier .travis.yml ou Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -La coverage de Solidity démarre sa propre ganache-cli, pour que nous n'ayons pas à nous en occuper. Cependant, ne remplacez pas la commande de test standard, le coverage de la ganache-cli fonctionne différemment et ne remplace donc pas les tests unitaires réguliers. - -### Étape 4 : Ajouter un dépôt à Coveralls {#step-4-add-repository-to-coveralls} - -- Créez un compte [Coveralls](https://coveralls.io/). -- Ajoutez-y le dépôt GitHub. -- Maintenant, allez de l'avant et créez une pull request. - -![Exemple Coverall](./coverall.png) - -## Plus d'idées {#further-ideas} - -- [MythX](https://mythx.io/) : Avec MythX, vous pouvez analyser automatiquement la sécurité de votre contrat intelligent. Il est donc très logique d'[ajouter ceci à votre CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29) : Un bon code peut être appliqué dans une certaine mesure avec des outils de linting. [Eslint](https://eslint.org/) fonctionne parfaitement pour JavaScript, est [facile à installer](https://eslint.org/docs/user-guide/getting-started), tandis que [Solhint](https://protofire.github.io/solhint/) peut être utilisé pour Solidity. -- Examens longs: Parfois, vous pouvez vouloir ajouter des tests extrêmes, par exemple, tester un contrat avec des centaines d'utilisateurs. Cela prend beaucoup de temps. Au lieu de les faire tourner à chaque exécution de tests, ajoutez-les à la CI. - -Voilà, c'est fait. L'intégration continue est une stratégie très utile pour vos développements. Vous pouvez consulter un exemple complet sur [Truffle-CI-Exemple](https://github.com/gorgos/Truffle-CI-Example). Il suffit de supprimer Circle-CI ou Travis, un seul suffit ! diff --git a/public/content/translations/fr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/fr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index 4803160999b..33b46b8ca27 100644 --- a/public/content/translations/fr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/fr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Le manifeste est notre fichier de configuration et définit : - d'autres éléments à prendre en compte comme des appels de fonction ou des blocs - les fonctions de mapping étant appelées (voir `mapping.ts` ci-dessous) -Ici, vous pouvez définir plusieurs contrats et handlers. Une configuration typique a un dossier de sous-graphes à l'intérieur du projet Truffle/Hardhat avec son propre dépôt. Ensuite, vous pouvez facilement référencer l'ABI. +Ici, vous pouvez définir plusieurs contrats et handlers. Une configuration typique a un dossier de sous-graphes à l'intérieur du projet Hardhat avec son propre dépôt. Ensuite, vous pouvez facilement référencer l'ABI. Pour des raisons de commodité, vous pouvez également utiliser un outil de template comme Mustache. Ensuite, vous allez créer un template `subgraph.template.yaml` et y insérez les adresses basées sur les derniers déploiements. Pour un exemple plus avancé, vous pouvez consulter le [répertoire de subgraphs Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/fr/enterprise/index.md b/public/content/translations/fr/enterprise/index.md index 120acf8eac0..9f8a4a4106a 100644 --- a/public/content/translations/fr/enterprise/index.md +++ b/public/content/translations/fr/enterprise/index.md @@ -72,7 +72,6 @@ Différentes organisations sont à l'origine d'initiatives collaboratives afin d - [Ernst & Young Nightfall](https://github.com/EYBlockchain/nightfall) _- Boîte à outils pour les transactions privées_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _- Application de signature de transactions à utiliser avec un prestataire Web3_ - [Tenderly](https://tenderly.co/) _ - Plateforme de données fournissant des analyses en temps réel, des alertes et une surveillance avec support pour les réseaux privés_ -- [Truffle Suite](https://trufflesuite.com) _- Suite de développement de blockchain (Truffle, Ganache, Drizzle)_ ### Solutions d'évolutivité {#scalability-solutions} diff --git a/public/content/translations/hu/community/support/index.md b/public/content/translations/hu/community/support/index.md index 5fd7f0e8ff1..78d03bde48d 100644 --- a/public/content/translations/hu/community/support/index.md +++ b/public/content/translations/hu/community/support/index.md @@ -73,7 +73,6 @@ Néhány népszerű példa: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/hu/developers/docs/bridges/index.md b/public/content/translations/hu/developers/docs/bridges/index.md index cbbd6a8124c..5d9a7a9a6ce 100644 --- a/public/content/translations/hu/developers/docs/bridges/index.md +++ b/public/content/translations/hu/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Ha egy dapp egy híd vagy egy aggregátor integrációját választja, az integr ### Egy dapp telepítése több láncra {#deploying-a-dapp-on-multiple-chains} -Egy dapp több láncra történő telepítéséhez a fejlesztők olyan fejlesztési platformokat használhatnak, mint az [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/) stb. Ezek a platformok olyan összeállítható bővítményekkel rendelkeznek, amelyek lehetővé teszik a dappoknak a láncok közötti átjárhatóságot. A fejlesztők például használhatják a [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy) által kínált determinisztikus telepítési proxyt. +Egy dapp több láncra történő telepítéséhez a fejlesztők olyan fejlesztési platformokat használhatnak, mint az [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/) stb. Ezek a platformok olyan összeállítható bővítményekkel rendelkeznek, amelyek lehetővé teszik a dappoknak a láncok közötti átjárhatóságot. A fejlesztők például használhatják a [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy) által kínált determinisztikus telepítési proxyt. #### Példák: diff --git a/public/content/translations/hu/developers/docs/development-networks/index.md b/public/content/translations/hu/developers/docs/development-networks/index.md index 3c38dbad142..7a9fa7487e3 100644 --- a/public/content/translations/hu/developers/docs/development-networks/index.md +++ b/public/content/translations/hu/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ _Akár _ [saját csomópontot is futtathat](/developers/docs/nodes-and-clients/# **Megjegyzés**: A legtöbb [fejlesztői keretrendszer](/developers/docs/frameworks/) egy beépített fejlesztői hálózatot tartalmaz. Ajánljuk, hogy egy keretrendszer segítségével [állítsa be a helyi fejlesztési környezetét](/developers/local-environment/). -### Ganache {#ganache} - -Indítson be gyorsan egy személyes Ethereum blokkláncot, melyet tesztek futtatására, parancsok végrehajtására és az állapot megtekintésére használhat, mialatt a lánc működését irányítja. - -A Ganache-nak van asztali alkalmazása (Ganache UI) és parancssori alkalmazása is (`ganache-cli`). A Truffle eszközsorozat része. - -- [Honlap](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Dokumentáció](https://www.trufflesuite.com/docs/ganache/overview) - ### Hardhat Network {#hardhat-network} Egy helyi Ethereum hálózat fejlesztésre tervezve. Szerződéseket telepíthet, teszteket futtathat, hibakeresést és javítást végezhet a kódján. diff --git a/public/content/translations/hu/developers/docs/frameworks/index.md b/public/content/translations/hu/developers/docs/frameworks/index.md index 871520b35e8..931c5d635f9 100644 --- a/public/content/translations/hu/developers/docs/frameworks/index.md +++ b/public/content/translations/hu/developers/docs/frameworks/index.md @@ -93,12 +93,6 @@ Mielőtt elmerülne a keretrendszerekben, javasoljuk, hogy olvassa át a bevezet - [GitHub](https://github.com/eth-brownie/brownie) - **A Brownie karbantartása jelenleg szünetel** -**Truffle -** **_Fejlesztői környezet, tesztelési keretrendszer, folyamatépítő és további eszközök._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **A Truffle fejlesztése befejeződött** – [további információk](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK -** **_The Ultimate Smart Contract Toolkit: egy eszköztár okosszerződések fejlesztéséhez, összeállításához, továbbfejlesztéséhez, telepítéséhez és az okosszerződésekkel való interakciókhoz._** - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/hu/developers/docs/programming-languages/dart/index.md b/public/content/translations/hu/developers/docs/programming-languages/dart/index.md index 83fb2ebca2e..01b65c1cb96 100644 --- a/public/content/translations/hu/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/hu/developers/docs/programming-languages/dart/index.md @@ -10,14 +10,12 @@ incomplete: true ## Oktatóanyagok {#tutorials} - [Flutter és blokklánc – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) átvezeti Önt a kezdeti lépéseken: - 1. A [Truffle fejlesztői környezet](https://www.trufflesuite.com/) telepítése - 2. Okosszerződés megírása [Solidity](https://soliditylang.org/) nyelven - 3. Felhasználói felület megírása Dart nyelven + 1. Okosszerződés megírása [Solidity](https://soliditylang.org/) nyelven + 2. Felhasználói felület megírása Dart nyelven - A [mobilalkalmazások építése a Flutterrel](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) sokkal rövidebb, amely jobb lehet, ha már ismeri az alapokat - Ha videók segítségével jobban szeret tanulni, akkor nézze meg az [Építse meg első blokkláncos Flutter alkalmazását](https://www.youtube.com/watch?v=3Eeh3pJ6PeA) videót, amely nagyjából egy óra hosszú - Ha ennél kevesebb ideje van, akkor talán tetszeni fog az [Egy blokklánc decentralizált alkalmazás építése a Flutterrel és a Darttal az Ethereumon](https://www.youtube.com/watch?v=jaMFEOCq_1s) videó, amely csak húsz percet veszi igénybe - [A MetaMask integrációja a Flutter alkalmazásban](https://youtu.be/8qzVDje3IWk) – ez a rövid videó bemutatja, hogyan kell a MetaMaskot beintegrálni a Flutter alkalmazásokba -- [Flutter Dapp egyszerű tárca](https://youtu.be/JMfIBpuAhKA) és [Az első Flutter DApp – Solidity, Truffle, Ganache](https://youtu.be/bHw2gQZxJ_s) – ezek a videók megmutatják, hogyan lehet egyszerű dappokat készíteni Flutterben a Truffle és Ganache segítségével - [Mobil blokkláncfejlesztői képzés Solidity-val és Flutterrel](https://youtube.com/playlist?list=PL4V4Unlk5luhQ26ERO6hWEbcUwHDSSmVH) – mobil blokkláncfejlesztői tanfolyam a teljes stack-kel (lejátszási lista) ## Az Ethereum-kliensek használata {#working-with-ethereum-clients} diff --git a/public/content/translations/hu/developers/docs/programming-languages/golang/index.md b/public/content/translations/hu/developers/docs/programming-languages/golang/index.md index cd3c258f790..926bdc6de6f 100644 --- a/public/content/translations/hu/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/hu/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Szükséged van egy méginkább kezdőknek szóló alapozóra? Tekintse meg az [ ## Cikkek és könyvek kezdőknek {#beginner-articles-and-books} -- [Ethereum kliens kiválasztása](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Kezdő lépések Geth-tel](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Golang használata Ethereumra való kapcsolódásra](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Ethereum okosszerződések telepítése Golang használatával](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/hu/developers/docs/programming-languages/rust/index.md b/public/content/translations/hu/developers/docs/programming-languages/rust/index.md index 104efc41166..eed8841548d 100644 --- a/public/content/translations/hu/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/hu/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Szükséged van egy méginkább kezdőknek szóló alapozóra? Tekintse meg az [ ## Cikkek kezdőknek {#beginner-articles} -- [Ethereum kliens kiválasztása](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [A Rust Ethereum-kliens](https://openethereum.github.io/) \* **Felhívjuk figyelmét, hogy az OpenEthereum [támogatása megszűnt](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd), karbantartása nem biztosított.** Használja körültekintően, és inkább térjen át másik kliensimplementációra. - [Tranzakció küldése Ethereumra Rust használatával](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Részletes útmutató arról, hogyan lehet szerződéseket írni Rust Wasm nyelven Kovanra](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/hu/developers/docs/security/index.md b/public/content/translations/hu/developers/docs/security/index.md index 2ef77eba86e..0d34146fecc 100644 --- a/public/content/translations/hu/developers/docs/security/index.md +++ b/public/content/translations/hu/developers/docs/security/index.md @@ -29,7 +29,7 @@ Minimum: - Az összes kódot egy verzió követő rendszer tárolja, mint a git - Minden kódmódosítást pull requesteken keresztül kell végezni - Minden pull requestet át kell néznie legalább egy valakinek. _Ha egyedül vagy a projekten, akkor keress valakit aki szintén egyedül van és cseréljetek kód review-kat._ -- Egy egyedüli parancs fordítja, telepíti és futtatja a tesztek sorozatát a kódodra egy Ethereum fejlesztői környezet használatával (lásd Truffle) +- Egy egyedüli parancs fordítja, telepíti és futtatja a tesztek sorozatát a kódodra egy Ethereum fejlesztői környezet használatával - Végig futtatod a kódodat valamilyen alapszintű kód analitikai eszközzel, mint a Mythril vagy a Slither, ideálisan mielőtt az egyes pull requesteket mergeled, így össze tudod hasonlítani a végeredményeket - A Solidity nem fog SEMMILYEN fordítói hibát visszaadni - A kódot megfelelően dokumentációval kell ellátni diff --git a/public/content/translations/hu/enterprise/index.md b/public/content/translations/hu/enterprise/index.md index 98a2eb455c9..b2f3f27fe18 100644 --- a/public/content/translations/hu/enterprise/index.md +++ b/public/content/translations/hu/enterprise/index.md @@ -81,7 +81,6 @@ Különféle szervezetek számtalan együttműködésen alapuló erőfeszítést - [Baseline Project](https://www.baseline-protocol.org/) - _A Baseline Protocol egy olyan eszköz- és könyvtárkészlet, amely segít a vállalatoknak az összetett, többszereplős üzleti folyamatok és munkafolyamatok adatvédelmi szempontból történő koordinálásában, miközben az adatok a megfelelő nyilvántartási rendszerekben maradnak. A szabvány lehetővé teszi, hogy két vagy több állapotgép elérje és fenntartsa az adatok konzisztenciáját és a munkafolyamatok folytonosságát a hálózat közös referenciakeretként való használatával._ - [Chainlens](https://www.chainlens.com/) - _SaaS és on-prem blokklánc adat- és elemzési platform a Web3 Labs-től_ - [Ernst & Young 'Nightfall'](https://github.com/EYBlockchain/nightfall_3) - _egy alkalmazás az ERC-20, ERC-721 és ERC-1155 alkalmazások átvitelére zero-knowledge módon, optimista összesítés használatával_ -- [Truffle Suite](https://trufflesuite.com) - _blokkláncfejlesztési csomag (Truffle, Ganache, Drizzle)_ ### Skálázási megoldások {#scalability-solutions} diff --git a/public/content/translations/id/community/support/index.md b/public/content/translations/id/community/support/index.md index 319ab59fd40..77e464525ab 100644 --- a/public/content/translations/id/community/support/index.md +++ b/public/content/translations/id/community/support/index.md @@ -55,7 +55,6 @@ Berikut adalah beberapa contoh populer: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) ## Menjalankan node {#node-support} diff --git a/public/content/translations/id/developers/docs/development-networks/index.md b/public/content/translations/id/developers/docs/development-networks/index.md index 8db31ab23a6..080a51c45fa 100644 --- a/public/content/translations/id/developers/docs/development-networks/index.md +++ b/public/content/translations/id/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Anda _dapat_ [menjalankan node](/developers/docs/nodes-and-clients/#running-your **Catatan**: Sebagian besar [kerangka kerja pengembangan](/developers/docs/frameworks/) menyertakan jaringan pengembangan bawaan. Kami menyarankan memulai dengan kerangka kerja untuk [menyiapkan lingkungan pengembangan lokal Anda](/developers/local-environment/). -### Ganache {#ganache} - -Dengan cepat menjalankan blockchain Ethereum pribadi yang bisa Anda gunakan untuk menjalankan pengujian, mengeksekusi perintah, dan memeriksa state, sambil mengontrol bagaimana rantai bekerja. - -Ganache menyediakan aplikasi desktop (UI Ganache), serta peralatan baris perintah (`ganache-cli`). Ini adalah bagian dari rangkaian peralatan Truffle. - -- [Situs web](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Dokumentasi](https://www.trufflesuite.com/docs/ganache/overview) - ### Jaringa Hardhat {#hardhat-network} Jaringan Ethereum lokal yang didesain untuk pengembangan. Jaringan ini memungkinkan Anda menggunakan kontrak, menjalankan pengujian, dan melakukan debug kode Anda diff --git a/public/content/translations/id/developers/docs/frameworks/index.md b/public/content/translations/id/developers/docs/frameworks/index.md index f220198be3a..6644ebf55f6 100644 --- a/public/content/translations/id/developers/docs/frameworks/index.md +++ b/public/content/translations/id/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Sebelum menyelami kerangka kerja, kami menyarankan Anda terlebih dahulu membaca ## Kerangka kerja yang tersedia {#available-frameworks} -**Truffle -** **_Lingkungan pengembangan, kerangka kerja pengujian, pipeline pengembangan, dan peralatan lainnya._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Hardhat -** **_Lingkungan pengembangan Ethereum untuk kalangan profesional_** - [hardhat.org](https://hardhat.org) diff --git a/public/content/translations/id/developers/docs/programming-languages/dart/index.md b/public/content/translations/id/developers/docs/programming-languages/dart/index.md index 836959f8274..bda7f0a8c6e 100644 --- a/public/content/translations/id/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/id/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutorial {#tutorials} - [Flutter dan Blockchain – Dapp Hello World](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) memandu Anda melalui semua langkah untuk memulai: - 1. Menginstal [Suite pengembangan Truffle](https://www.trufflesuite.com/) - 2. Menulis kontrak pintar di [Solidity](https://soliditylang.org/) - 3. Menulis antarmuka pengguna di Dart + 1. Menulis kontrak pintar di [Solidity](https://soliditylang.org/) + 2. Menulis antarmuka pengguna di Dart - [Membangun dApp Seluler dengan Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) jauh lebih singkat, yang mungkin lebih baik jika Anda telah mengetahui dasarnya. - Jika Anda lebih suka belajar dengan menonton video, Anda dapat menonton [Bangun App Flutter Blockchain Pertama Anda](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), yang kira - kira berdurasi satu jam - Jika tidak sabar, Anda mungkin lebih suka [Membangun Aplikasi Terdesentralisasi Blockchain dengan Flutter dan Dart di Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), yang diperkirakan hanya berdurasi dua puluh menit diff --git a/public/content/translations/id/developers/docs/programming-languages/golang/index.md b/public/content/translations/id/developers/docs/programming-languages/golang/index.md index c7302a9d585..ee01fdb7e7c 100644 --- a/public/content/translations/id/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/id/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Perlu penjelasan yang lebih mendasar? Kunjungi [ethereum.org/learn](/learn/) ata ## Artikel dan buku untuk pemula {#beginner-articles-and-books} -- [Memilih Klien Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Mulai Menggunakan Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Gunakan Golang untuk Terhubung ke Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Gunakan Kontrak Pintar Ethereum Menggunakan Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/id/developers/docs/programming-languages/rust/index.md b/public/content/translations/id/developers/docs/programming-languages/rust/index.md index f52ad68f164..020d881e2e2 100644 --- a/public/content/translations/id/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/id/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Perlu penjelasan yang lebih mendasar? Kunjungi [ethereum.org/learn](/learn/) ata ## Artikel Untuk Pemula {#beginner-articles} -- [Memilih Klien Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Klien Ethereum Rust](https://openethereum.github.io/) \* **Perhatikan bahwa OpenEthereum [telah menjadi usang](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) dan tidak lagi dipertahankan.** Gunakan dengan hati-hati dan lebih baik beralih ke implementasi klien lainnya. - [Mengirimkan Transaksi ke Ethereum Menggunakan Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Pengantar Kontrak Pintar dengan Klien Ethereum Parity](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/id/developers/docs/smart-contracts/deploying/index.md b/public/content/translations/id/developers/docs/smart-contracts/deploying/index.md index 317c9b2e348..47a51bb3130 100644 --- a/public/content/translations/id/developers/docs/smart-contracts/deploying/index.md +++ b/public/content/translations/id/developers/docs/smart-contracts/deploying/index.md @@ -27,7 +27,7 @@ Akhirnya, Anda hanya perlu mengompilasi kontrak sebelum menggunakannya, jadi pas ### Langkah-langkah untuk menggunakan kontrak pintar {#steps-to-deploy} -Langkah-langkah khusus yang diperlukan akan bergantung pada peralatan yang Anda gunakan. Sebagai contoh, lihat [dokumentasi Hardhat tentang menggunakan kontrak Anda](https://hardhat.org/guides/deploying.html) atau [dokumentasi Truffle tentang penggunaan jaringan dan aplikasi](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment). Ini adalah dua dari peralatan paling populer untuk penggunaan kontrak pintar, yang melibatkan penulisan skrip untuk menangani langkah-langkah penggunaan. +Langkah-langkah khusus yang diperlukan akan bergantung pada peralatan yang Anda gunakan. Sebagai contoh, lihat [dokumentasi Hardhat tentang menggunakan kontrak Anda](https://hardhat.org/guides/deploying.html). Ini adalah dua dari peralatan paling populer untuk penggunaan kontrak pintar, yang melibatkan penulisan skrip untuk menangani langkah-langkah penggunaan. Setelah digunakan, kontrak Anda akan memiliki alamat Ethereum seperti [akun](/developers/docs/accounts/) lainnya. @@ -51,12 +51,6 @@ Setelah digunakan, kontrak Anda akan memiliki alamat Ethereum seperti [akun](/de - [GitHub](https://github.com/nomiclabs/hardhat) - [Discord](https://discord.com/invite/TETZs2KK4k) -**Truffle -** **_Lingkungan pengembangan, kerangka kerja pengujian, pipeline pengembangan, dan peralatan lainnya._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [Dokumentasi tentang penggunaan jaringan dan aplikasi](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) -- [GitHub](https://github.com/trufflesuite/truffle) - **thirdweb - _Sebarkan setiap kontrak dengan mudah ke setiap rantai yang kompatibel dengan EVM, dengan menggunakan satu perintah tunggal_** - [Dokumentasi](https://portal.thirdweb.com/deploy/) diff --git a/public/content/translations/id/developers/docs/smart-contracts/testing/index.md b/public/content/translations/id/developers/docs/smart-contracts/testing/index.md index 2fec20609ef..75a998b995d 100644 --- a/public/content/translations/id/developers/docs/smart-contracts/testing/index.md +++ b/public/content/translations/id/developers/docs/smart-contracts/testing/index.md @@ -34,13 +34,11 @@ incomplete: true ## Tutorial terkait {#related-tutorials} -- [Pengaturan Integrasi Berkelanjutan Solidity dan Truffle](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) _– Cara menyiapkan Travis atau Circle CI untuk pengujian Truffle bersama dengan plugin yang berguna._ - [Gambaran umum produk pengujian](/developers/tutorials/guide-to-smart-contract-security-tools/) _– Gambaran umum dan perbandingan dari produk pengujian berbeda._ - [Cara menggunakan Echidna untuk menguji kontrak pintar](/developers/tutorials/how-to-use-echidna-to-test-smart-contracts/) - [Cara menggunakan Manticore untuk menemukan bug kontrak pintar](/developers/tutorials/how-to-use-manticore-to-find-smart-contract-bugs/) - [Cara menggunakan Slither untuk menemukan bug kontrak pintar](/developers/tutorials/how-to-use-slither-to-find-smart-contract-bugs/) - [Cara meniru kontrak Solidity untuk pengujian](/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -- [Cara berpindah dari Uji Truffle ke Lingkungan Uji OpenZeppelin](https://docs.openzeppelin.com/test-environment/0.1/migrating-from-truffle) - [Cara menguji kontrak setelah digunakan di jaringan](https://fulldecent.blogspot.com/2019/04/testing-deployed-ethereum-contracts.html) ## Bacaan lebih lanjut {#further-reading} diff --git a/public/content/translations/id/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/id/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index 6779a1524a6..00000000000 --- a/public/content/translations/id/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Buat dan sebarkan aplikasi DeFi -description: Setor token ERC20 ke kontrak pintar dan cetak Token Farm -author: "strykerin" -tags: - - "solidity" - - "defi" - - "web3.js" - - "truffle" - - "ganache" - - "kontrak pintar" -skill: intermediate -lang: id -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -Dalam tutorial ini, kita akan membangun Aplikasi DeFi dengan Solidity di mana pengguna dapat menyetor token ERC20 ke kontrak pintar dan kontrak pintar akan mencetak serta mentransfer Token Farm ke mereka. Pengguna nantinya dapat menarik token ERC20 mereka dengan membakar Token Farm pada kontrak pintar dan token ERC20 akan ditransfer kembali ke mereka. - -## Instal Truffle dan Ganache {#install-truffle-and-ganache} - -Jika ini adalah pertama kalinya Anda menulis kontrak pintar, maka Anda perlu mengatur lingkungan kerja. Kita akan menggunakan dua perangkat: [Truffle](https://www.trufflesuite.com/) dan [Ganache](https://www.trufflesuite.com/ganache). - -Truffle adalah lingkungan pengembangan dan kerangka pengujian untuk pengembangan kontrak pintar bagi Ethereum. Dengan menggunakan Truffle, kita mudah membangun dan menyebarkan kontrak pintar ke rantai blok. Ganache membuat kita dapat menciptakan rantai blok Ethereum lokal untuk menguji kontrak pintar. Ganache menyimulasikan fitur dari jaringan yang sebenarnya dan 10 akun pertama didanai dengan 100 ether pengujian, sehingga membuat penyebaran dan pengujian kontrak pintar menjadi gratis dan mudah. Ganache tersedia sebagai aplikasi desktop dan perangkat baris perintah. Untuk artikel ini, kita akan menggunakan aplikasi desktop UI. - -![Aplikasi desktop UI Ganache](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Aplikasi desktop UI Ganache_ - -Untuk membuat proyek, jalankan perintah berikut - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Perintah ini akan membuat sebuah proyek kosong untuk pengembangan dan penyebaran kontrak pintar kita. Struktur proyek yang dibuat adalah sebagai berikut: - -- `contracts`: Folder untuk kontrak pintar solidity - -- `migrations`: Folder untuk skrip penyebaran - -- `test`: Folder untuk menguji kontrak pintar kita - -- `truffle-config.js`: File konfigurasi Truffle - -## Buat Token ERC20 {#create-the-erc20-token} - -Pertama, kita perlu membuat token ERC20 yang akan digunakan untuk melakukan taruhan pada kontrak pintar. Untuk membuat token yang dapat ditukarkan, kita terlebih dahulu perlu menginstal pustaka OpenZeppelin. Pustaka ini memuat penerapan standar seperti ERC20 dan ERC721. Untuk menginstal pustaka tersebut, jalankan perintah: - -```bash -npm install @openzeppelin/contracts -``` - -Dengan menggunakan pustaka OpenZeppelin, kita dapat membuat token ERC20 dengan menulis ke `contracts/MyToken.sol` dengan kode solidity berikut: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -Dalam kode di atas: - -- Baris 3: Kita mengimpor kontrak ERC20.sol dari openzeppelin yang memuat penerapan untuk standar token ini. - -- Baris 5: Kita mewariskan dari kontrak ERC20.sol. - -- Baris 6: Kita memanggil konstruktor ERC20.sol dan melewatkan parameter nama dan simbol sebagai `"MyToken"` dan `"MTKN"` secara berurutan. - -- Baris 7: Kita mencetak dan mentransfer 1 juta token untuk akun yang menyebarkan kontrak pintar (kita menggunakan 18 desimal default untuk token ERC20, yang berarti bahwa jika kita ingin mencetak 1 token, Anda akan menyatakannya sebagai 1000000000000000000, 1 dengan 18 nol). - -Kita dapat melihat di bawah penerapan konstruktor ERC20.sol di mana field `_decimals` ditetapkan menjadi 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Kumpulkan Token ERC20 {#compile-the-erc20-token} - -Untuk mengumpulkan kontrak pintar kita, kita harus terlebih dahulu memeriksa versi pengumpul solidity kita. Anda dapat memeriksa versi tersebut dengan menjalankan perintah: - -```bash -truffle version -``` - -Versi default adalah `Solidity v0.5.16`. Karena token kita ditulis menggunakan versi solidity `0.6.2`, jika kita menjalankan perintah untuk mengumpulkan kontrak kita, maka kita akan mendapatkan kesalahan pada pengumpul. Untuk menentukan versi pengumpul solidity yang digunakan, buka file `truffle-config.js` dan tetapkan versi pengumpul yang diinginkan seperti terlihat di bawah: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Sekarang, kita dapat mengumpulkan kontrak pintar kita dengan menjalankan perintah berikut: - -```bash -truffle compile -``` - -## Sebarkan Token ERC20 {#deploy-erc20-token} - -Setelah dikumpulkan, kita sekarang dapat menyebarkan token kita. - -Pada folder `migrasi`, buat file yang diberi nama `2_deploy_Tokens.js`. File ini adalah tempat kita akan menyebarkan baik Token ERC20 maupun kontrak pintar FarmToken kita. Kode di bawah digunakan untuk menyebarkan kontrak MyToken.sol kita: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Buka Ganache dan pilih opsi "Quickstart" untuk memulai rantai blok Ethereum lokal. Untuk menyebarkan kontrak kita, jalankan: - -```bash -truffle migrate -``` - -Alamat yang digunakan untuk menyebarkan kontrak kita adalah daftar alamat pertama yang ditunjukkan Ganache kepada kita. Untuk memverifikasinya, kita dapat membuka aplikasi desktop Ganache, dan kita dapat memverifikasi bahwa saldo ether karena saldo akun pertama telah berkurang akibat biaya ether untuk menyebarkan kontrak pintar kita: - -![Aplikasi desktop Ganache](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Aplikasi desktop Ganache_ - -Untuk memverifikasi bawa 1 juta token MyToken telah dikirimkan ke alamat penyebar, kita dapat menggunakan Konsol Truffle untuk berinteraksi dengan kontrak pintar yang telah disebarkan. - -> [Konsol Truffle adalah konsol interaktif dasar yang terhubung ke klien Ethereum mana pun.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Agar dapat berinteraksi dengan kontrak pintar kita, jalankan perintah berikut: - -```bash -truffle console -``` - -Sekarang, kita dapat menulis perintah berikut dalam terminal: - -- Dapatkan kontrak pintar: `myToken = menunggu MyToken.deployed()` - -- Dapatkan susunan akun dari Ganache: `accounts = menunggu web3.eth.getAccounts()` - -- Dapatkan saldo akun pertama: `saldo = menunggu myToken.balanceOf(accounts[0])` - -- Format saldo dari 18 desimal: `web3.utils.fromWei(balance.toString())` - -Dengan menjalankan perintah di atas, kita akan melihat bahwa alamat pertama sebenarnya memiliki 1 juta MyTokens: - -![Alamat pertama memiliki 1000000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_Alamat pertama memiliki 1000000 MyTokens_ - -## Buat Kontrak Pintar FarmToken {#create-farmtoken-smart-contract} - -Kontrak pintar FarmToken akan memiliki 3 fungsi: - -- `balance()`: Dapatkan saldo MyToken pada kontrak pintar FarmToken. - -- `deposit(uint256 _amount)`: Transfer MyToken atas nama pengguna ke kontrak pintar FarmToken, kemudian cetak dan transfer FarmToken ke pengguna tersebut. - -- `withdraw(uint256 _amount)`: Bakar FarmToken pengguna dan transfer MyToken ke alamat pengguna tersebut. - -Mari kita lihat konstruktor FarmToken: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Baris 3-6: Kita mengimpor kontrak berikut dari openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol, dan ERC20.sol. - -- Baris 8: FarmToken akan mewarisi dari kontrak ERC20. - -- Baris 14-19: Konstruktor FarmToken akan diterima sebagai parameter alamat kontrak MyToken dan kita akan menugaskan kontrak tersebut ke variabel publik kita yang disebut `token`. - -Mari kita terapkan fungsi `balance()`. Fungsi ini tidak akan menerima parameter dan akan mengembalikan saldo MyToken pada kontrak pintar ini. Fungsi ini diterapkan seperti terlihat di bawah: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -Untuk fungsi `deposit(uint256 _amount)`, fungsi ini akan diterima sebagai parameter jumlah yang ingin disetor pengguna dan fungsi ini akan mencetak dan mentransfer FarmToken ke pengguna: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -Untuk fungsi `withdraw(uint256 _amount)`, kita akan menerima fungsi tersebut sebagai parameter jumlah FarmToken yang ingin di bakar oleh pengguna dan kemudian mentransfer kembali jumlah MyToken yang sama ke pengguna: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Sekarang, kita akan menyebarkan kontrak pintar kita. Untuk melakukannya, kita akan kembali ke file `2_deploy_Tokens.js` dan menambahkan kontrak baru yang akan disebarkan: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Perlu diperhatikan bahwa saat menyebarkan FarmToken, kita menyebarkan alamat kontrak MyToken yang digunakan sebagai parameter. - -Sekarang, jalankan `truffle compile` dan `truffle migrate` untuk menyebarkan kontrak kita. - -Mari kita menguji kontrak pintar kita. Alih-alih menggunakan `konsol truffle` untuk berinteraksi dengan kontrak pintar kita, kita akan membuat skrip untuk mengautomasi proses ini. Buat folder bernama `skrip` dan tambahkan file `getMyTokenBalance.js` berikut. Folder ini akan memeriksa saldo MyToken pada kontrak pintar FarmToken: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Untuk melaksanakan skrip, jalankan perintah cli berikut: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Kita akan mendapatkan hasil yang diinginkan, yaitu 0. Jika Anda mendapatkan kesalahan tentang FarmToken yang belum disebarkan, jaringan truffle belum menerima versi terbaru dari kode kontrak Anda. Cukup tutup ganache, mulai cepat lagi dan pastikan untuk menjalankan `truffle migrate`. - -Sekarang, mari kita bertaruh MyToken ke kontrak pintar. Karena fungsi `deposit(uint256 _amount)` memangil fungsi `safeTransferFrom` dari ERC20, pengguna harus terlebih dahulu menyetujui kontrak pintar untuk mentransfer MyToken atas nama pengguna. Jadi, pada skrip di bawah, kita akan terlebih dahulu menyetujui langkah ini, kemudian kita akan memanggil fungsi: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Untuk menjalankan skrip ini: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Anda seharusnya melihat pada konsol Anda: - -![output dari transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_output dari transferMyTokenToFarmToken.js_ - -Seperti yang dapat kita lihat, kita telah berhasil menyetor MyToken ke kontrak pintar karena akun pertama sekarang memiliki FarmToken. - -Untuk melakukan penarikan: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Untuk menjalankan skrip ini: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. Seperti yang dapat kita lihat pada output di bawah, kita telah berhasil mendapatkan MyToken kembali dan kita telah membakar FarmToken: - -![output dari withdrawMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_output dari withdrawMyTokenFromTokenFarm.js_ - -## Referensi {#references} - -[Kontrak - Dokumentasi OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/) - -[Perangkat Berguna untuk Kontrak Pintar | Truffle Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[Apa yang Dimaksud dengan DeFi? Panduan bagi Pemula (Diperbarui Tahun 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - Papan Peringkat Keuangan Terdesentralisasi di DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/id/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/id/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index 8c15f31380d..e4a9e72e5ae 100644 --- a/public/content/translations/id/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/id/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "kontrak pintar" - "penyimpanan" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Batasan ini diperkenalkan untuk mencegah serangan layanan penolakan (DOS). Setia Pada awalnya ini tidak menjadi masalah, karena batasan ukuran kontrak dasar seseorang adalah batasan gas blok. Jelas sebuah kontrak perlu digunakan dalam transaksi yang menampung semua kode bita kontrak. Jika Anda kemudian memasukkan hanya satu transaksi tersebut ke dalam sebuah blok, Anda dapat menggunakan semua gas tersebut, tapi itu tak terbatas. Namun, masalah dalam kasus ini adalah bahwa batasan gas blok berubah dari waktu ke waktu dan secara teori tidak terbatas. Saat peluncuran EIP-170, batasan gas blok hanya 4,7 juta. Sekarang batasan gas blok baru [meningkat lagi](https://etherscan.io/chart/gaslimit) pada bulan lalu ke angka 11,9 juta. -## Menghadapi pertempuran {#taking-on-the-fight} - -Sayangnya, tidak ada cara mudah untuk mendapatkan ukuran kode bita kontrak Anda. Sebuat peralatan hebat yang dapat membantu Anda untuk ini adalah plugin [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) jika Anda menggunakan Truffle. - -1. `npm install truffle-contract-size` -2. Tambahkan plugin ke _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Jalankan `truffle run contract-size` - -Ini akan membantu Anda menemukan bagaimana perubahan Anda berdampak terhadap ukuran kontrak total. - Berikutnya kita akan melihat beberapa metode yang diurutkan berdasarkan potensi dampaknya. Bayangkan ini seperti upaya mengurangi berat badan. Strategi terbaik bagi seseorang untuk mencapai berat badan idealnya (dalam kasus kita 24kb) adalah memusatkan perhatian pada metode yang berdampak besar terlebih dahulu. Dalam kebanyakan kasus, hanya memperbaiki pola makan Anda akan membawa Anda pada sasaran, tetapi terkadang Anda memerlukan upaya yang sedikit lebih banyak. Lalu Anda mungkin menambahkan beberapa jenis latihan (dampak sedang) atau bahkan mengonsumsi suplemen (dampak kecil). ## Dampak besar {#big-impact} diff --git a/public/content/translations/id/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/id/developers/tutorials/secure-development-workflow/index.md index a6a39e74aa9..0ce520061b2 100644 --- a/public/content/translations/id/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/id/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Pertimbangkan fitur spesial kontrak Anda: - Apakah kontrak Anda dapat ditingkatkan? Tinjau kode yang dapat ditingkatkan untuk mencari kelemahannya dengan [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) atau [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). Kami telah mendokumentasikan 17 alur dari peningkatan yang bermasalah. - Apakah kontrak Anda mengklaim telah sesuai dengan ERC? Periksa dengan [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). Peralatan ini dengan segera mengidentifikasi deviasi dari enam spesifikasi umum. -- Apakah Anda memiliki tes unit di Truffle? Perkuat dengan [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation). Secara otomatis ini akan menghasilkan serangkaian properti keamanan yang kokoh untuk fitur ERC20 yang didasarkan pada kode spesifik Anda. - Apakah Anda berintegrasi dengan token pihak ketiga? Tinjau [daftar periksa integrasi token](/developers/tutorials/token-integration-checklist/) kami sebelum menggunakan kontrak eksternal. Secara visual periksa fitur keamanan kritikal kode Anda: diff --git a/public/content/translations/id/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/id/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index ad579195488..00000000000 --- a/public/content/translations/id/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: "Pengaturan integrasi berkelanjutan untuk Solidity dan Truffle" -description: Cara menyiapkan Travis atau Circle CI untuk pengujian Truffle bersama dengan plugin yang berguna -author: Markus Waas -lang: id -tags: - - "solidity" - - "kontrak pintar" - - "pengujian" - - "truffle" - - "integrasi berkelanjutan" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -Integrasi berkelanjutan (CI) dengan Truffle merupakan cara yang bagus untuk pekerjaan pengembangan setelah Anda memiliki sekumpulan tes dasar yang diimplementasikan. CI memungkinkan Anda menjalankan tes yang sangat panjang, memastikan semua tes lolos uji sebelum bergabung dengan [permintaan penarikan](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) dan untuk melacak berbagai statistik menggunakan peralatan tambahan. - -Kita akan menggunakan [Kotak Metacoin Truffle](https://www.trufflesuite.com/boxes/metacoin) untuk menyiapkan integrasi berkelanjutan kita. Anda dapat memilih Travis CI atau Circle CI. - -## Menyiapkan Travis CI {#setting-up-travis-ci} - -Menambahkan [Travis CI](https://travis-ci.org/) merupakan hal yang mudah. Anda hanya perlu menambahkan file konfigurasi `.travis.yml` ke folder akar proyeknya: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Kita akan menjaganya tetap tampak mudah untuk saat ini dan hanya akan menjalankan skrip tes yang mengeksekusi tes unit Truffle. Tapi kita memiliki satu masalah, tidak akan ada blockchain yang tersedia di mesin Travis CI. Solusi mudah untuk ini adalah melakukan`npm instal ganache-cli` dan cukup menjalankannya sebelum tes. Anda dapat melakukan ini dengan menambahkan skrip bash dengan barisan npx `ganache-cli > /dev/null` dan sebelum pemanggilan `npx truffle test`. [Contoh lengkap skrip bash](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Menyiapkan Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) memerlukan file konfigurasi yang lebih panjang. Perintah tambahan [`npm ci`](https://docs.npmjs.com/cli/ci.html) secara otomatis dijalankan di Travis. Perintah ini menginstal dependensi dengan lebih cepat dan lebih aman daripada yang dilakukan oleh `npm install`. Kita sekali lagi menggunakan skrip yang sama dari versi Travis untuk menjalankan ganache-cli sebelum pengujiannya. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Menambahkan plugin eth-gas-reporter {#adding-the-eth-gas-reporter-plugin} - -Plugin eth-gas-reporter cukup berguna untuk melacak biaya gas dari fungsi kontrak pintar Anda. Memilikinya dalam CI Anda akan jauh lebih berguna untuk menunjukkan perbedaan saat menambahkan permintaan penarikan. - -### Langkah 1: Instal plugin eth-gas-reporter dan codechecks {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Langkah 2: Tambahkan plugin ke pengaturan mocha di dalam truffle-config.js Anda {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Lihat opsi](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Langkah 3: Tambahkan codechecks.yml ke direktori akar proyek Anda {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Langkah 4: Jalankan codechecks setelah perintah pengujian {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Langkah 5: Buat akun Codechecks {#step-5-create-a-codechecks-account} - -- Buat akun dengan [Codechecks](http://codechecks.io/). -- Add the GitHub repo to it. -- Salin rahasianya dan tambahkan `CC_SECRET=COPIED SECRET` ke dalam CI Anda (lihat di sini untuk [Travis](https://docs.travis-ci.com/user/environment-variables/), di sini untuk [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Sekarang lanjutkan dan buat permintaan penarikan. - -Selesai. Sekarang Anda akan menemukan laporan yang bagus tentang perubahan biaya gas dari permintaan penarikan Anda. - -![Contoh laporan gas](./gas-reports.png) - -## Menambahkan plugin solidity-coverage {#adding-the-solidity-coverage-plugin} - -Dengan plugin solidity-coverage, Anda dapat memeriksa seberapa banyak jalur kode Anda yang dicakup oleh tes Anda. Menambahkan ini ke CI Anda sangatlah praktis untuk digunakan setelah disiapkan. - -### Langkah 1: Buat proyek metacoin dan instal peralatan coverage {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle -npm install --save-dev coveralls -npm install --save-dev solidity-coverage -``` - -### Langkah 2: Tambahkan solidity-coverage ke dalam array plugin di dalam truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Langkah 3: Tambahkan perintah coverage ke dalam .travis.yml atau Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Coverage Solidity memulai ganache-cli miliknya, sehingga kita tidak perlu merisaukan tentang ini. Namun, jangan mengganti perintah tes reguler, ganache-cli coverage bekerja dengan cara berbeda dan oleh karena itu bukanlah pengganti untuk menjalankan tes reguler. - -### Langkah 4: Tambahkan repositori ke coveralls {#step-4-add-repository-to-coveralls} - -- Buat akun dengan [Coveralls](https://coveralls.io/). -- Add the GitHub repo to it. -- Sekarang lanjutkan dan buat permintaan penarikan. - -![Contoh coverall](./coverall.png) - -## Ide lebih lanjut {#further-ideas} - -- [MythX](https://mythx.io/): Dengan MythX, Anda dapat secara otomatis menganalisa keamanan kontrak pintar Anda. Jadi, sangat masuk akal untuk [menambahkan ini ke dalam CI Anda](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Good code can be enforced to some degree with linting tools. [Eslint](https://eslint.org/) works great for JavaScript, is [easy to setup](https://eslint.org/docs/user-guide/getting-started), while [Solhint](https://protofire.github.io/solhint/) can be used for Solidity. -- Tes panjang: Terkadang Anda mungkin ingin menambahkan tes ekstrim, seperti menguji kontrak yang memiliki ratusan pengguna. Ini memerlukan waktu yang lama. Alih-alih menjalankannya di setiap pengoperasian tes, tambahkan ke dalam CI. - -Begitu mudah, bukan. Integrasi berkelanjutan merupakan strategi yang sangat berguna untuk pengembangan Anda. Anda dapat melihat contoh lengkapnya di [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Pastikan saja menghapus Circle-CI atau Travis, satu sudah cukup! diff --git a/public/content/translations/id/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/id/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index 96dc68b2c9b..85d0684162d 100644 --- a/public/content/translations/id/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/id/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Manifestasi adalah file konfigurasi kita dan menentukan: - hal lain untuk didengarkan seperti fungsi pemanggilan atau blok - the mapping functions being called (see `mapping.ts` below) -Anda bisa menentukan kontrak dan handler beragam di sini. Pengaturan umumnya akan memiliki folder subgraph di dalam proyek Truffle/Hardhat dengan repositorinya sendiri. Lalu Anda bisa dengan mudah merujuk ABI-nya. +Anda bisa menentukan kontrak dan handler beragam di sini. Pengaturan umumnya akan memiliki folder subgraph di dalam proyek Hardhat dengan repositorinya sendiri. Lalu Anda bisa dengan mudah merujuk ABI-nya. Untuk alasan kenyamanan, Anda mungkin juga mau menggunakan peralatan templat seperti mustache. Then you create a `subgraph.template.yaml` and insert the addresses based on the latest deployments. Untuk pengaturan percontohan yang lebih canggih, lihat contoh [repo subgraph Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/id/enterprise/index.md b/public/content/translations/id/enterprise/index.md index 3b77246d436..828f37a9197 100644 --- a/public/content/translations/id/enterprise/index.md +++ b/public/content/translations/id/enterprise/index.md @@ -67,7 +67,6 @@ Beberapa usaha kolaboratif untuk membuat Ethereum ramah bagi perusahaan telah di - [Ernst & Young's ‘Nightfall'](https://github.com/EYBlockchain/nightfall) _sebuah kotak peralatan untuk transaksi privat_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _sebuah aplikasi penandatanganan transaksi untuk digunakan dengan penyedia web3_ - [Tenderly](https://tenderly.co/) _sebuah Platform Data yang menyediakan analitik, peringatan, dan pengawasan dalam waktu sebenarnya dengan dukungan untuk jaringan privat._ -- [Truffle Suite](https://trufflesuite.com) _rangkaian pengembangan blockchain (Truffle, Ganache, Drizzle)_ ### Solusi skalabilitas {#scalability-solutions} diff --git a/public/content/translations/it/community/support/index.md b/public/content/translations/it/community/support/index.md index 9a18548671c..038e9dd2864 100644 --- a/public/content/translations/it/community/support/index.md +++ b/public/content/translations/it/community/support/index.md @@ -73,7 +73,6 @@ Ecco alcuni esempi più diffusi: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/it/contributing/index.md b/public/content/translations/it/contributing/index.md index 94dcb8ec7fd..665dc55ee3d 100644 --- a/public/content/translations/it/contributing/index.md +++ b/public/content/translations/it/contributing/index.md @@ -68,7 +68,7 @@ Prima di contribuire, assicurati di avere familiarità con: - la nostra [guida di stile](/contributing/style-guide/) - il nostro [codice di condotta](/community/code-of-conduct) - + ## Come vengono prese le decisioni sul sito {#how-decisions-about-the-site-are-made} diff --git a/public/content/translations/it/developers/docs/bridges/index.md b/public/content/translations/it/developers/docs/bridges/index.md index d76a4718117..da7e0bdb749 100644 --- a/public/content/translations/it/developers/docs/bridges/index.md +++ b/public/content/translations/it/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Se una dapp prosegue lungo il percorso di integrazione di un ponte o di un aggre ### Distribuire una dapp su diverse catene {#deploying-a-dapp-on-multiple-chains} -Per distribuire una dapp su più catene, gli sviluppatori possono utilizzare piattaforme di sviluppo come [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/), ecc. In genere, queste piattaforme sono dotate di plugin componibili che possono consentire alle dapp di essere distribuite su diverse catene. Per esempio, gli sviluppatori possono utilizzare un proxy di distribuzione deterministico offerto dal [plugin hardhat-deploy](https://github.com/wighawag/hardhat-deploy). +Per distribuire una dapp su più catene, gli sviluppatori possono utilizzare piattaforme di sviluppo come [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/), ecc. In genere, queste piattaforme sono dotate di plugin componibili che possono consentire alle dapp di essere distribuite su diverse catene. Per esempio, gli sviluppatori possono utilizzare un proxy di distribuzione deterministico offerto dal [plugin hardhat-deploy](https://github.com/wighawag/hardhat-deploy). #### Esempi: diff --git a/public/content/translations/it/developers/docs/development-networks/index.md b/public/content/translations/it/developers/docs/development-networks/index.md index 60e58e46f37..048445d02f4 100644 --- a/public/content/translations/it/developers/docs/development-networks/index.md +++ b/public/content/translations/it/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ _Potresti_ [eseguire un nodo](/developers/docs/nodes-and-clients/#running-your-o **Nota**: la maggior parte dei [framework di sviluppo](/developers/docs/frameworks/) include una rete di sviluppo incorporata. Raccomandiamo di iniziare con un framework per [impostare l'ambiente di sviluppo locale](/developers/local-environment/). -### Ganache {#ganache} - -Imposta rapidamente una blockchain Ethereum personale che permette di eseguire test, comandi e ispezionare lo stato durante il controllo del funzionamento della catena. - -Ganache offre sia un'applicazione desktop (Ganache UI) che uno strumento da riga di comando (`ganache-cli`). Fa parte della suite di strumenti Truffle. - -- [Sito Web](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentazione](https://www.trufflesuite.com/docs/ganache/overview) - ### Rete Hardhat {#hardhat-network} Rete Ethereum locale progettata per lo sviluppo. Permette di distribuire contratti, eseguire test e il debug del codice. diff --git a/public/content/translations/it/developers/docs/frameworks/index.md b/public/content/translations/it/developers/docs/frameworks/index.md index 12f7fe652f8..9b8740b9211 100644 --- a/public/content/translations/it/developers/docs/frameworks/index.md +++ b/public/content/translations/it/developers/docs/frameworks/index.md @@ -105,12 +105,6 @@ Prima di iniziare a studiare i framework, raccomandiamo la lettura della nostra - [GitHub](https://github.com/eth-brownie/brownie) - **Brownie non è al momento mantenuto** -**Truffle -** **_ Ambiente di sviluppo, framework di test, pipeline di sviluppo e altri strumenti_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **Lo sviluppo di Truffle è terminato**: [leggi di più](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK -** **_Il kit di strumenti definitivo per i contratti intelligenti: una suite di strumenti per aiutarti a sviluppare, compilare, aggiornare, distribuire e interagire con i contratti intelligenti_** - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/it/developers/docs/programming-languages/dart/index.md b/public/content/translations/it/developers/docs/programming-languages/dart/index.md index 53d03ffe789..3ab5364015b 100644 --- a/public/content/translations/it/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/it/developers/docs/programming-languages/dart/index.md @@ -10,14 +10,12 @@ incomplete: true ## Tutorial {#tutorials} - [Flutter e Blockchain – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) è una guida passo dopo passo per chi inizia da zero: - 1. Installare la [suite di sviluppo di Truffle](https://www.trufflesuite.com/) - 2. Scrivere un contratto intelligente in [Solidity](https://soliditylang.org/) - 3. Scrivere un'interfaccia utente su Dart + 1. Scrivere un contratto intelligente in [Solidity](https://soliditylang.org/) + 2. Scrivere un'interfaccia utente su Dart - [Creare una dapp Mobile con Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) è molto più breve, il che potrebbe esser meglio se conosci già le basi - Se preferisci imparare guardando un video, puoi guardare [Build Your First Blockchain Flutter App](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), lungo all'incirca un'ora - Se sei impaziente, questo potrebbe fare al caso tuo [Building a Blockchain Decentralized-app with Flutter and Dart on Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s) (Creare un'app decentralizzata sulla Blockchain con Flutter e Dart su Ethereum), che dura solo circa venti minuti - [Integrating MetaMask in Flutter application with Web3Modal by WalletConnect](https://www.youtube.com/watch?v=v_M2buHCpc4) - questo breve video ti guida nei passaggi dell'integrazione di MetaMask nelle tue applicazioni di Flutter con la libreria [Web3Modal](https://pub.dev/packages/web3modal_flutter) di WalletConnect -- [Flutter Dapp Simple Wallet](https://youtu.be/JMfIBpuAhKA) e [First Flutter DApp - Solidity, Truffle, Ganache](https://youtu.be/bHw2gQZxJ_s) - questi video dimostrano come creare semplici dapp in Flutter utilizzando Truffle e Ganache - [Mobile Blockchain Developer Bootcamp Course With Solidity & Flutter](https://youtube.com/playlist?list=PL4V4Unlk5luhQ26ERO6hWEbcUwHDSSmVH) - playlist del corso per sviluppatori di blockchain mobili full stack ## Lavorare con i client di Ethereum {#working-with-ethereum-clients} diff --git a/public/content/translations/it/developers/docs/programming-languages/golang/index.md b/public/content/translations/it/developers/docs/programming-languages/golang/index.md index 6c8d6960dbc..87694a4fc17 100644 --- a/public/content/translations/it/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/it/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Hai prima bisogno di nozioni di base? Dai un'occhiata a [ethereum.org/learn](/le ## Articoli e libri per principianti {#beginner-articles-and-books} -- [Choosing an Ethereum Client](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Getting Started with Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Use Golang to Connect to Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Distribuisci i Contratti Intelligenti di Ethereum Usando Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/it/developers/docs/programming-languages/rust/index.md b/public/content/translations/it/developers/docs/programming-languages/rust/index.md index 0140cfb5586..96fc9709025 100644 --- a/public/content/translations/it/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/it/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Hai prima bisogno di nozioni di base? Dai un'occhiata a [ethereum.org/learn](/le ## Articoli per chi inizia ora {#beginner-articles} -- [Choosing an Ethereum Client](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [The Rust Ethereum Client](https://openethereum.github.io/) \* **Notare che OpenEthereum [è ormai superato](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) e non viene più mantenuto.** Usalo con cautela e preferibilmente passa a un'altra implementazione client. - [Sending Transaction to Ethereum Using Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Tutorial passo-passo per scrivere contratti in rust Wasm per Kovan (in inglese)](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/it/developers/docs/security/index.md b/public/content/translations/it/developers/docs/security/index.md index 56df3cd9693..4f7d4de2bc3 100644 --- a/public/content/translations/it/developers/docs/security/index.md +++ b/public/content/translations/it/developers/docs/security/index.md @@ -29,7 +29,7 @@ Requisiti minimi: - Tutto il codice memorizzato in un sistema di controllo delle versioni, come git - Tutte le modifiche al codice effettuate tramite richieste pull - Tutte le richieste pull hanno almeno un revisore. _Se sei l'unico sviluppatore nel progetto, prendi in considerazione la possibilità di trovare un altro sviluppatore che lavori da solo per revisionarvi i progetti a vicenda_ -- Un singolo comando compila, distribuisce ed esegue una serie di test sul codice utilizzando un ambiente di sviluppo per Ethereum (vedi: Truffle) +- Un singolo comando compila, distribuisce ed esegue una serie di test sul codice utilizzando un ambiente di sviluppo per Ethereum - Hai verificato il codice con strumenti di base di analisi del codice come Mythril e Slither, idealmente prima dell'unione di ogni richiesta pull, e confrontato le differenze nell'output - Solidity non produce NESSUN avviso in fase di compilazione - Il codice è ben documentato diff --git a/public/content/translations/it/developers/docs/smart-contracts/deploying/index.md b/public/content/translations/it/developers/docs/smart-contracts/deploying/index.md index 4a626aecf69..ef522dba17d 100644 --- a/public/content/translations/it/developers/docs/smart-contracts/deploying/index.md +++ b/public/content/translations/it/developers/docs/smart-contracts/deploying/index.md @@ -27,7 +27,7 @@ Infine, dovrai compilare il tuo contratto prima di distribuirlo, quindi, assicur ### Passaggi per distribuire un contratto intelligente {#steps-to-deploy} -I passaggi specifici dipenderanno dagli strumenti utilizzati. Per esempio, dai un'occhiata alla [documentazione di Hardhat sulla distribuzione dei tuoi contratti](https://hardhat.org/guides/deploying.html) o alla [documentazione di Truffle su reti e distribuzione delle app](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment). Questi sono due degli strumenti più popolari per la distribuzione dei contratti intelligenti, che coinvolgono la scrittura di uno script per gestire i passaggi di distribuzione. +I passaggi specifici dipenderanno dagli strumenti utilizzati. Per esempio, dai un'occhiata alla [documentazione di Hardhat sulla distribuzione dei tuoi contratti](https://hardhat.org/guides/deploying.html). Questi sono due degli strumenti più popolari per la distribuzione dei contratti intelligenti, che coinvolgono la scrittura di uno script per gestire i passaggi di distribuzione. Una volta distribuito, il contratto avrà un indirizzo Ethereum come gli altri [conti](/developers/docs/accounts/). @@ -51,12 +51,6 @@ Una volta distribuito, il contratto avrà un indirizzo Ethereum come gli altri [ - [GitHub](https://github.com/nomiclabs/hardhat) - [Discord](https://discord.com/invite/TETZs2KK4k) -**Truffle:** **_ ambiente di sviluppo, framework di test, pipeline di sviluppo e altri strumenti_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [Documentazione sulle reti e la distribuzione delle app](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) -- [GitHub](https://github.com/trufflesuite/truffle) - **thirdweb - _Distribuisci con facilità qualsiasi contratto a qualsiasi catena che sia compatibile con EVM, utilizzando un singolo comando_** - [Documentazione](https://portal.thirdweb.com/deploy/) diff --git a/public/content/translations/it/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/it/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index a3007169c04..00000000000 --- a/public/content/translations/it/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Creare e distribuire un'App DeFi -description: Deposita i token ERC20 sullo smart contract e conia token Farm -author: "strykerin" -tags: - - "solidity" - - "defi" - - "web3.js" - - "truffle" - - "ganache" - - "Smart Contract" -skill: intermediate -lang: it -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -In questo tutorial creeremo un'applicazione DeFi con Solidity in cui gli utenti possono depositare un token ERC20 sullo smart contract, per poter coniare e trasferire i token Farm. Gli utenti possono quindi prelevare i token ERC20: una volta bruciato il token Farm sullo smart contract, i token ERC20 verranno ritrasferiti. - -## Installa Truffle e Ganache {#install-truffle-and-ganache} - -Se questa è la prima volta che scrivi uno smart contract, dovrai configurare il tuo ambiente. Useremo due strumenti: [Truffle](https://www.trufflesuite.com/) e [Ganache](https://www.trufflesuite.com/ganache). - -Truffle è un ambiente di sviluppo e framework di verifica per lo sviluppo di smart contract per Ethereum. Con Truffle è facile costruire e distribuire gli smart contract alla blockchain. Ganache consente di creare una blockchain locale di Ethereum per poter testare gli smart contract. Simula le funzionalità della rete reale e, i primi 10 conti, sono finanziati con 100 ether di prova, rendendo la distribuzione e i test del contratto intelligente, gratuiti e facili. Ganache è disponibile come applicazione desktop e strumento di riga di comando. Per questo articolo useremo l'applicazione desktop dell'UI. - -![Applicazione desktop dell'UI di Ganache](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Applicazione desktop dell'UI di Ganache_ - -Per creare il progetto, esegui i seguenti comandi - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Verrà creato un progetto vuoto per lo sviluppo e la distribuzione dei nostri smart contract. La struttura del progetto creato è la seguente: - -- `contracts`: Cartella per gli smart contract in Solidity - -- `migrations`: Cartella per gli script di distribuzione - -- `test`: Cartella per collaudare i nostri smart contract - -- `truffle-config.js`: File di configurazione di Truffle - -## Crea il Token ERC20 {#create-the-erc20-token} - -Innanzi tutto dobbiamo creare il nostro token ERC20, che useremo per lo staking sullo smart contract. Per creare il nostro token fungibile, dovremo prima installare la libreria di OpenZeppelin. Essa contiene le implementazioni di standard come ERC20 ed ERC721. Per installare, esegui il comando: - -```bash -npm install @openzeppelin/contracts -``` - -Usando la libreria di OpenZeppelin possiamo creare il nostro token ERC20 scrivendo in `contracts/MyToken.sol` con il seguente codice in Solidity: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -Nel codice seguente alla: - -- Riga 3: Importiamo l'ERC20.sol del contratto da openzeppelin, che contiene l'implementazione per questo standard del token. - -- Riga 5: Ereditiamo dal contratto ERC20.sol. - -- Riga 6: Chiamiamo il costruttore di ERC20.sol e passiamo per il nome e i parametri del simbolo come `"MyToken"` e `"MTKN"` rispettivamente. - -- Riga 7: Coniamo e trasferiamo 1 milione di token per il conto che sta distribuendo il contratto intelligente (usiamo i 18 decimali predefiniti per il token ERC20, il che significa che se vogliamo coniare 1 token, lo rappresenterai come 1000000000000000000, 1 con 18 zeri). - -Possiamo vedere di seguito l'implementazione del costruttore di ERC20.sol, dove il campo `_decimals` è impostato a 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compila il Token ERC20 {#compile-the-erc20-token} - -Per compilare il nostro smart contract, dobbiamo prima verificare la nostra versione del compilatore in Solidity. Puoi verificarla eseguendo il comando: - -```bash -truffle version -``` - -La versione predefinita è `Solidity v0.5.16`. Poiché il nostro token è scritto usando la versione `0.6.2` di Solidity, se eseguiamo il comando per compilare i nostri contratti otterremo un errore del compilatore. Per poter specificare quale versione del compilatore di Solidity usare, vai al file `truffle-config.js` e imposta sulla versione del compilatore desiderata, come mostrato di seguito: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Ora possiamo compilare il nostro smart contract eseguendo il seguente comando: - -```bash -truffle compile -``` - -## Distribuisci il Token ERC20 {#deploy-erc20-token} - -Dopo la compilazione, possiamo distribuire il nostro token. - -Sulla cartella `migrations`, crea un file denominato `2_deploy_Tokens.js`. Questo file è dove distribuiremo sia il nostro Token ERC20 che il nostro contratto intelligente di FarmToken. Il codice seguente è usato per distribuire il nostro contratto MyToken.sol: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Apri Ganache e seleziona l'opzione "Avvio Rapido" per avviare una blockchain locale di Ethereum. Per distribuire il nostro contratto, esegui: - -```bash -truffle migrate -``` - -L'indirizzo usato per distribuire i nostri contratti è il primo dall'elenco di indirizzi che Ganache ci mostra. Per verificarlo, possiamo aprire l'applicazione desktop di Ganache e possiamo verificare che il saldo di ether per il primo conto sia stato ridotto a causa del costo di ether per distribuire i nostri contratti intelligenti: - -![Applicazione desktop di Ganache](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Applicazione desktop di Ganache_ - -Per verificare che 1 milione di token MyToken sia stato inviato all'indirizzo del distributore, possiamo usare la Console di Truffle per interagire con il nostro smart contract distribuito. - -> [La Console di Truffle è una console interattiva di base che si connette a qualsiasi client di Ethereum.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Per poter interagire con il nostro smart contract, esegui il seguente comando: - -```bash -truffle console -``` - -Ora possiamo scrivere i seguenti comandi nel terminale: - -- Ottieni lo smart contract: `myToken = await MyToken.deployed()` - -- Ottieni l'insieme di conti da Ganache: `accounts = await web3.eth.getAccounts()` - -- Ottieni il saldo del primo conto: `balance = await myToken.balanceOf(accounts[0])` - -- Formatta il saldo da 18 decimali: `web3.utils.fromWei(balance.toString())` - -Eseguendo i suddetti comandi, vedremo che il primo indirizzo ha difatti 1 milione di MyToken: - -![Il primo indirizzo ha 1000000 MyToken](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_Il primo indirizzo ha 1000000 MyToken_ - -## Crea lo smart contract del FarmToken {#create-farmtoken-smart-contract} - -Lo smart contract FarmToken avrà 3 funzioni: - -- `balance()`: Ottieni il saldo di MyToken sullo smart contract di FarmToken. - -- `deposit(uint256 _amount)`: Trasferisci MyToken per conto dell'utente dello smart contract di FarmToken, quindi conia e trasferisci il FarmToken all'utente. - -- `withdraw(uint256 _amount)`: Brucia i FarmToken dell'utente e trasferisci i MyToken all'indirizzo dell'utente. - -Diamo un'occhiata al costruttore del FarmToken: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Righe 3-6: Importiamo i seguenti contratti da OpenZeppelin: IERC20.sol, Address.sol, SafeERC20.sol ed ERC20.sol. - -- Riga 8: Il FarmToken erediterà dal contratto ERC20. - -- Righe 14-19: Il costruttore del FarmToken riceverà come parametro l'indirizzo del contratto MyToken e ne assegneremo il contratto alla nostra variabile pubblica, chiamata `token`. - -Implementiamo la funzione `balance()`. Non riceverà alcun parametro e restituirà il saldo di MyToken su questo smart contract. È implementato come mostrato sotto: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -Per la funzione `deposit(uint256 _amount)`, riceverà come parametro la quantità che l'utente desidera depositare e conierà e trasferirà i FarmToken all'utente: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -Per la funzione `withdraw(uint256 _amount)`, riceveremo come parametro l'importo di FarmToken che l'utente vuole bruciare e poi trasferiremo lo stesso importo di MyToken all'utente: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Ora distribuiremo il nostro smart contract. Per farlo, torneremo al file `2_deploy_Tokens.js` e aggiungeremo il nuovo contratto da distribuire: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Nota che distribuendo il FarmToken, passiamo come parametro l'indirizzo del contratto MyToken distribuito. - -Ora, esegui `truffle compile` e `truffle migrate` per distribuire i nostri contratti. - -Testiamo il nostro smart contract. Anziché usare la `truffle console` per interagire con il nostro smart contract, creeremo uno script per automatizzare questo processo. Crea una cartella denominata `scripts` e aggiungi il seguente file `getMyTokenBalance.js`. Verificherà il saldo di MyToken sullo smart contract del FarmToken: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Per eseguire questo script, esegui il seguente comando CLI: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Otterremo il risultato previsto, pari a 0. Se ottieni un errore secondo cui FarmToken non è stato ancora distribuito, la rete di Truffle non ha ricevuto l'ultima versione del codice del contratto. Basta chiudere Ganache, riavviarlo rapidamente e assicurarsi di eseguire `truffle migrate`. - -Ora, mettiamo in gioco il MyToken sullo smart contract Poiché la funzione `deposit(uint256_amount)` chiama la funzione `safeTransferFrom` dall'ERC20, l'utente deve prima approvare lo smart contract per trasferire i MyToken per conto dell'utente. Quindi sullo script seguente, approveremo prima questa fase, poi chiameremo la funzione: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Per eseguire questo script: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Dovresti vedere sulla tua console: - -![output di transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_output di transferMyTokenToFarmToken.js_ - -Come possiamo vedere, abbiamo depositato correttamente i MyToken al contratto intelligente, poiché il primo conto ha ora dei FarmToken. - -Per poter prelevare: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Per eseguire questo script: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. Come possiamo vedere sull'output seguente, abbiamo correttamente riottenuto i MyToken e abbiamo bruciato i FarmToken: - -![output di withdrawMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_output di withdrawMyTokenFromTokenFarm.js_ - -## Riferimenti {#references} - -[Contratti - Documentazione di OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/) - -[Sweet Tool per smart contract | Suite di Truffle](https://www.trufflesuite.com/) - -[Ganache | Suite di Truffle](https://www.trufflesuite.com/ganache) - -[Cos'è la DeFi? Una Guida per Principianti (Aggiornata al 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - La Classifica di Finanza Decentralizzata, su DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/it/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/it/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index 5260470697f..bda4e22f771 100644 --- a/public/content/translations/it/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/it/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "contratti intelligenti" - "archiviazione" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Questo limite è stato introdotto per prevenire gli attacchi DOS (denial-of-serv In origine, questo era un problema minore, dato che il limite naturale di dimensioni del contratto è il limite di gas del blocco. Ovviamente, un contratto dev'esser distribuito entro una transazione che detenga tutto il codice del byte del contratto. Se includi solo quella transazione in un blocco, puoi usare anche tutto il gas, ma non è infinito. Dall'[Aggiornamento di Londra](/history/#london), il limite di gas del blocco è stato capace di variare tra le 15M e le 30M unità, a seconda della domanda di rete. -## Affrontare la lotta {#taking-on-the-fight} - -Sfortunatamente, non esiste un modo facile per ottenere la dimensione del bytecode dei tuoi contratti. Un ottimo strumento per aiutarti è il plugin [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size), se utilizzi Truffle. - -1. `npm install truffle-contract-size` -2. Aggiungi il plugin al the _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Esegui `truffle run contract-size` - -Questo ti aiuterà a capire come le tue modifiche influiscono sulle dimensioni totali del contratto. - Di seguito, passeremo in rassegna alcuni metodi, ordinati in base al loro impatto potenziale. Pensiamo ad esempio alla perdita di peso: la strategia migliore per raggiungere il proprio peso target (nel nostro caso 24kb) consiste nel concentrarsi prima sui metodi a maggiore impatto. In gran parte dei casi è sufficiente adattare la propria dieta, mentre in altri serve qualcosa di più. Si può aggiungere un po' di esercizio fisico (impatto medio) o persino degli integratori (impatto ridotto). ## Impatto elevato {#big-impact} diff --git a/public/content/translations/it/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/it/developers/tutorials/secure-development-workflow/index.md index 99fb2c1a6f2..f418bdf96b7 100644 --- a/public/content/translations/it/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/it/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Considera le funzionalità speciali del tuo contratto: - I tuoi contratti sono aggiornabili? Revisiona il tuo codice di aggiornabilità per i difetti con [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) o [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). Abbiamo documentato 17 modi in cui gli aggiornamenti possono andare male. - I tuoi contratti pretendono di esser conformi agli ERC? Controllali con [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). Questo strumento identifica istantaneamente le deviazioni da sei specifiche comuni. -- Hai test unitari su Truffle? Arricchiscili con [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation). Genera automaticamente una robusta suite di proprietà di sicurezza per le funzionalità di ERC20 in base al tuo codice specifico. - Integri con token di terze parti? Revisiona il nostro [elenco di controllo di integrazione del token](/developers/tutorials/token-integration-checklist/) prima di affidarti a contratti esterni. Ispeziona visivamente le funzionalità di sicurezza critiche del tuo codice: diff --git a/public/content/translations/it/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/it/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 5d2157d787e..00000000000 --- a/public/content/translations/it/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Configurazione dell'integrazione continua di Solidity e Truffle" -description: Come configurare Travis o Circle CI per il test con Truffle insieme ai plugin utili -author: Markus Waas -lang: it -tags: - - "solidity" - - "contratti intelligenti" - - "test" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -L'integrazione continua (CI) con Truffle è ottima per lo sviluppo una volta implementata una serie di test di base. Permette di eseguire test molto lunghi, assicurare che passino tutti prima di fondere una [richiesta di pull](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) e tenere traccia delle varie statistiche usando strumenti aggiuntivi. - -Useremo la [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) per configurare la nostra integrazione continua. Puoi scegliere Travis CI o Circle CI. - -## Configurare Travis CI {#setting-up-travis-ci} - -Aggiungere [Travis CI](https://travis-ci.org/) è semplice. Dovrai solo aggiungere il file di configurazione `.travis.yml` alla cartella di root del progetto: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Per il momento manteniamo le cose semplici ed eseguiamo solo lo script di test che esegue i test unitari di Truffle. Ma abbiamo un problema, non ci sarà una blockchain disponibile sulla macchina di Travis CI. Una soluzione semplice per ovviare al problema è `npm install ganache-cli`, da eseguire semplicemente prima del test. Puoi farlo aggiungendo uno script di bash con la riga npx `ganache-cli > /dev/null` e prima della chiamata di `npx truffle test`. L'[esempio completo dello script di bash](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Configurare Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) richiede un file di configurazione più lungo. Il comando aggiuntivo [`npm ci`](https://docs.npmjs.com/cli/ci.html) è eseguito automaticamente su Travis. Installa le dipendenze in modo più veloce e sicuro di quanto faccia `npm install`. Usiamo nuovamente lo stesso script dalla versione di Travis per eseguire ganache-cli prima dei test. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Aggiungere il plugin eth-gas-reporter {#adding-the-eth-gas-reporter-plugin} - -Il plugin eth-gas-reporter è piuttosto utile per tenere traccia dei costi del gas delle funzioni del tuo contratto intelligente. Averlo nella tua CI sarà inoltre utile per mostrare le differenze quando si aggiungono le richieste di pull. - -### Fase 1: Installa il plugin eth-gas-reporter e i codecheck {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Fase 2: Aggiungi il plugin alle impostazioni di mocha nel tuo truffle-config.js {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Visualizza le opzioni](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Fase 3: Aggiungi un codechecks.yml alla cartella di root del tuo progetto {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Fase 4: Esegui codechecks dopo il comando di test {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Fase 5: Crea un conto di Codechecks {#step-5-create-a-codechecks-account} - -- Crea un conto con [Codechecks](http://codechecks.io/). -- Aggiungi la repo di GitHub. -- Copia il segreto e aggiungi `CC_SECRET=COPIED SECRET` alla tua CI (vedi qui per [Travis](https://docs.travis-ci.com/user/environment-variables/), qui per [CircleCI](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Ora prosegui e crea una richiesta di pull. - -È tutto. Ora troverai un bel rapporto sulle modifiche ai costi del gas della tua richiesta di pull. - -![Esempio di rapporti del gas](./gas-reports.png) - -## Aggiungere il plugin di solidity-coverage {#adding-the-solidity-coverage-plugin} - -Con il plugin di solidity-coverage puoi controllare in quale misura i percorsi del tuo codice sono coperti dai test. Una volta configurato e aggiunto alla tua CI, è molto pratico da usare. - -### Fase 1: Crea un progetto di metacoin e installa gli strumenti di coverage {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### Fase 2: Aggiungi solidity-coverage all'insieme di plugin in truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Fase 3: Aggiungi i comandi di coverage al .travis.yml o config.yml di Circle CI {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Solidity coverage avvia la propria ganache-cli, quindi non dobbiamo preoccuparcene. Tuttavia, non sostituire il comando di test regolare, la ganache-cli di coverage funziona differentemente e non esiste dunque alcun sostituto per l'esecuzione dei test unitari regolari. - -### Fase 4: Aggiungi la repository a coveralls {#step-4-add-repository-to-coveralls} - -- Crea un conto con [Coveralls](https://coveralls.io/). -- Aggiungi la repo di GitHub. -- Ora prosegui e crea una richiesta di pull. - -![Esempio di coverall](./coverall.png) - -## Ulteriori idee {#further-ideas} - -- [MythX](https://mythx.io/): Con MythX puoi analizzare automaticamente la sicurezza del tuo smart contract. Ha quindi molto senso [aggiungerlo alla tua CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Un buon codice è applicabile in una certa misura con gli strumenti di linting. [Eslint](https://eslint.org/) è ottimo per JavaScript e [facile da configurare](https://eslint.org/docs/user-guide/getting-started), mentre per Solidity si può usare [Solhint](https://protofire.github.io/solhint/). -- Test lunghi: A volte potresti voler aggiungere dei test estremi, ad es. testando un contratto con centinaia di utenti. Ciò richiede molto tempo. Invece di eseguirli a ogni esecuzione del test, aggiungili alla CI. - -Ecco tutto. L'integrazione continua è una strategia molto utile per i tuoi sviluppi. Puoi dare un'occhiata all'esempio completo su [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Basta assicurarti di rimuovere Circle-CI o Travis, ne basta uno! diff --git a/public/content/translations/it/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/it/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index 06f441ce3d4..ad18a610c69 100644 --- a/public/content/translations/it/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/it/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Il manifest è il nostro file di configurazione e definisce: - altri elementi da attendere, come chiamate a funzioni o blocchi - le funzioni di mapping chiamate (vedi `mapping.ts` sotto) -Qui puoi definire più contratti e gestori. Una configurazione tipica avrebbe una cartella subgraph nel progetto Truffle/Hardhat con un proprio repository. A questo punto puoi facilmente fare riferimento all'ABI. +Qui puoi definire più contratti e gestori. Una configurazione tipica avrebbe una cartella subgraph nel progetto Hardhat con un proprio repository. A questo punto puoi facilmente fare riferimento all'ABI. Per motivi di comodità potresti anche usare uno strumento di modelli come mustache. Poi crei un ` subgraph.template.yaml` e inserisci gli indirizzi in base alle distribuzioni più recenti. Per una configurazione più avanzata, vedi ad esempio il [repo del subgraph Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/it/enterprise/index.md b/public/content/translations/it/enterprise/index.md index 9d95f2fbd4b..8d3918bcbfe 100644 --- a/public/content/translations/it/enterprise/index.md +++ b/public/content/translations/it/enterprise/index.md @@ -83,7 +83,6 @@ Sono stati compiuti degli sforzi collaborativi per rendere Ethereum accessibile - [Baseline Project](https://www.baseline-protocol.org/): _Il Protocollo di Baseline è una serie di strumenti e librerie che aiutano le aziende a coordinare processi aziendali e flussi di lavoro complessi e multiparte nel rispetto della privacy, mantenendo i dati nei rispettivi sistemi di registrazione. Lo standard consente a due o più macchine di stato di ottenere e mantenere la coerenza dei dati e la continuità del flusso di lavoro, utilizzando una rete come un quadro di riferimento comune._ - [Chainlens](https://www.chainlens.com/): _Piattaforma analitica e di dati sulla blockchain SaaS e locale da Web3 Labs_ - [Ernst & Young's 'Nightfall'](https://github.com/EYBlockchain/nightfall_3): _un'applcazione per trasferire applcazoni ERC20, ERC721 ed ERC1155 sotto Conoscenza Zero, utilizzando un Rollup Ottimistico_ -- [Truffle Suite](https://trufflesuite.com) _è una suite di sviluppo della blockchain (Truffle, Ganache, Drizzle)_ ### Soluzioni di scalabilità {#scalability-solutions} diff --git a/public/content/translations/ja/community/language-resources/index.md b/public/content/translations/ja/community/language-resources/index.md index a5c8b28a13f..b5e6f6931d9 100644 --- a/public/content/translations/ja/community/language-resources/index.md +++ b/public/content/translations/ja/community/language-resources/index.md @@ -130,4 +130,3 @@ ethereum.orgは、40言語以上のネイティブに翻訳されており、各 - [一般社団法人日本暗号資産ビジネス協会](https://cryptocurrency-association.org/) - [ブロックチェーン開発の概要 - Learn | Microsoft Docs](https://docs.microsoft.com/ja-jp/learn/paths/ethereum-blockchain-development/) - ブロックチェーンとイーサリアムプラットフォームでの開発に関する説明 - [マスタリング・イーサリアム](https://www.oreilly.co.jp/books/9784873118963/) - スマートコントラクトと分散型アプリ(Dapp)の構築 -- [SolidityとEthereumによる実践スマートコントラクト開発](https://www.oreilly.co.jp/books/9784873119342/) - Truffle Suiteを用いた開発の基礎からデプロイまで diff --git a/public/content/translations/ja/community/support/index.md b/public/content/translations/ja/community/support/index.md index 28ef750a49a..575449d1798 100644 --- a/public/content/translations/ja/community/support/index.md +++ b/public/content/translations/ja/community/support/index.md @@ -73,7 +73,6 @@ lang: ja - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/ja/contributing/index.md b/public/content/translations/ja/contributing/index.md index 861294545c4..74029da8ea4 100644 --- a/public/content/translations/ja/contributing/index.md +++ b/public/content/translations/ja/contributing/index.md @@ -68,7 +68,7 @@ ethereum.orgは、オープンソースで運営されているプロジェク - [スタイルガイド](/contributing/style-guide/) - [行動規範](/community/code-of-conduct) - + ## サイトに関する決定 {#how-decisions-about-the-site-are-made} diff --git a/public/content/translations/ja/developers/docs/bridges/index.md b/public/content/translations/ja/developers/docs/bridges/index.md index ca0261a3f85..471d45f8c75 100644 --- a/public/content/translations/ja/developers/docs/bridges/index.md +++ b/public/content/translations/ja/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Dappにブリッジやブリッジアグリゲーターを組み込む場合、 ### 複数のチェーン上でDappをデプロイする {#deploying-a-dapp-on-multiple-chains} -複数のブロックチェーン上でDappをデプロイするには、[Alchemy](https://www.alchemy.com/)、[Hardhat](https://hardhat.org/)、あるいは[Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/)などの開発プラットフォームを利用することができます。 一般にこれらのプラットフォームには、Dappのクロスチェーン化を実現するコンポーザブルなプラグインが含まれています。 例えば、 [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy)で提供される決定論的なデプロイ用プロキシを活用することができます。 +複数のブロックチェーン上でDappをデプロイするには、[Alchemy](https://www.alchemy.com/)、[Hardhat](https://hardhat.org/)、[Moralis](https://moralis.io/)などの開発プラットフォームを利用することができます。 一般にこれらのプラットフォームには、Dappのクロスチェーン化を実現するコンポーザブルなプラグインが含まれています。 例えば、 [hardhat-deploy plugin](https://github.com/wighawag/hardhat-deploy)で提供される決定論的なデプロイ用プロキシを活用することができます。 #### 例: diff --git a/public/content/translations/ja/developers/docs/development-networks/index.md b/public/content/translations/ja/developers/docs/development-networks/index.md index f3ecd0a8f1c..cc77c909598 100644 --- a/public/content/translations/ja/developers/docs/development-networks/index.md +++ b/public/content/translations/ja/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ lang: ja **注**: ほとんどの[開発フレームワーク](/developers/docs/frameworks/)には、組み込みの開発用ネットワークが含まれています。 フレームワークの[ローカル開発環境のセットアップ](/developers/local-environment/)から始めることをお勧めします。 -### Ganache {#ganache} - -テストの実行、コマンドの実行、状態の調査に使用できる専用のイーサリアムブロックチェーンを迅速に起動し、チェーンの動作を制御します。 - -Ganacheは、デスクトップアプリケーション(Ganache UI)とコマンドラインツール(`ganache-cli`)の両方を提供しています。 Truffle Suiteというツールスイートに組み込まれています。 - -- [ウェブサイト](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [ドキュメント](https://www.trufflesuite.com/docs/ganache/overview) - ### Hardhat Network {#hardhat-network} 開発用に設計されたローカルイーサリアムネットワークです。 コントラクトのデプロイ、テストの実行、コードのデバッグを可能にします。 diff --git a/public/content/translations/ja/developers/docs/frameworks/index.md b/public/content/translations/ja/developers/docs/frameworks/index.md index d7267efc065..e71ae804e2e 100644 --- a/public/content/translations/ja/developers/docs/frameworks/index.md +++ b/public/content/translations/ja/developers/docs/frameworks/index.md @@ -105,12 +105,6 @@ lang: ja - [GitHub](https://github.com/eth-brownie/brownie) - **Brownieのメンテナンス終了** -**Truffle -** **_開発環境、テストフレームワーク、ビルドパイプライン、その他のツール。_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **Truffle開発の終了** - [詳細について](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK -** **_究極のスマートコントラクトツールキット。スマートコントラクトの開発、コンパイル、アップグレード、デプロイ、インタラクションを支援するツール群。_** - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/ja/developers/docs/programming-languages/dart/index.md b/public/content/translations/ja/developers/docs/programming-languages/dart/index.md index 73feb8e4445..ae5412be551 100644 --- a/public/content/translations/ja/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/ja/developers/docs/programming-languages/dart/index.md @@ -10,14 +10,12 @@ incomplete: true ## チュートリアル {#tutorials} - [Flutterとブロックチェーン – Hello World dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/)で、開始手順を段階的に説明しています。 - 1. [Truffle開発スイート](https://www.trufflesuite.com/)をインストールする - 2. [Solidity](https://soliditylang.org/)でスマートコントラクトを記述する - 3. Dartでユーザーインターフェースを記述する + 1. [Solidity](https://soliditylang.org/)でスマートコントラクトを記述する + 2. Dartでユーザーインターフェースを記述する - [Flutterを使用したモバイルdappの構築](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a)は、より簡潔な説明となっています。すでに基礎を理解している場合は、こちらを参照することをお勧めします。 - ビデオでの学習をご希望の場合は、[初めてのブロックチェーンFlutterアプリの構築](https://www.youtube.com/watch?v=3Eeh3pJ6PeA)をご覧いただけます。このビデオは約1時間です。 - 時間がない場合は、[イーサリアムでのFlutterとDartを使用したブロックチェーンの分散型アプリの構築](https://www.youtube.com/watch?v=jaMFEOCq_1s)をご覧ください。このビデオはわずか20分です。 - [WalletConnectによるFlutterアプリケーションのMetaMaskとWeb3Modalの統合](https://www.youtube.com/watch?v=v_M2buHCpc4) - この短編ビデオでは、WalletConnectの [Web3Modal](https://pub.dev/packages/web3modal_flutter)ライブラリを使用してMetaMaskをFlutterアプリケーションに統合する手順を説明します。 -- [Flutter Dappシンプルウォレット](https://youtu.be/JMfIBpuAhKA)と[はじめてのFlutter DApp - Solidity、Truffle、Ganache](https://youtu.be/bHw2gQZxJ_s) - これらのビデオは、TruffleとGanacheを使ってFlutterで簡単なDappsを作成する方法を案内します。 - [SolidityとFlutterによるモバイル・ブロックチェーン・デベロッパー・ブートキャンプ・コース](https://youtube.com/playlist?list=PL4V4Unlk5luhQ26ERO6hWEbcUwHDSSmVH) - フルスタック・モバイル・ブロックチェーン・デベロッパー・コースのプレイリスト ## イーサリアムクライアントの操作 {#working-with-ethereum-clients} diff --git a/public/content/translations/ja/developers/docs/programming-languages/golang/index.md b/public/content/translations/ja/developers/docs/programming-languages/golang/index.md index 300acc7eb96..70cdf4ec1dc 100644 --- a/public/content/translations/ja/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/ja/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ incomplete: true ## 初心者向けの記事と書籍 {#beginner-articles-and-books} -- [イーサリアムクライアントの選択](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Geth入門](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Golangを使用してイーサリアムに接続する](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Golangを使用してイーサリアムスマートコントラクトをデプロイする](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/ja/developers/docs/programming-languages/rust/index.md b/public/content/translations/ja/developers/docs/programming-languages/rust/index.md index 3cba1b54119..3dcc324fdbc 100644 --- a/public/content/translations/ja/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/ja/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ incomplete: true ## 初心者向けの記事 {#beginner-articles} -- [イーサリアムクライアントの選択](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Rustイーサリアムクライアント](https://openethereum.github.io/) \* **OpenEthereumは[すでに廃止されており](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd)、現在は維持されていません。** ご利用には注意が必要です。できれば、他のクライアント実装に切り替えてください。 - [Rustを使用してイーサリアムにトランザクションを送信する](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Kovan向けRust Wasmでのコントラクトの記述方法についての段階的なチュートリアル](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/ja/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/ja/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index 1cdf48dc7f1..00000000000 --- a/public/content/translations/ja/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: DeFiアプリを作成してデプロイする -description: スマートコントラクトへERC-20トークンを入金し、Farm Tokenをミントする -author: "strykerin" -tags: - - "Solidity" - - "DeFi" - - "web3.js" - - "Truffle" - - "Ganache" - - "スマートコントラクト" -skill: intermediate -lang: ja -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -このチュートリアルでは、Solidityを使用してDeFiアプリケーションを構築します。このアプリケーションでは、ERC20トークンをスマートコントラクトに入金した上で、Farm Tokenを発行して転送することができます。 ユーザーはその後、スマートコントラクトでFarm TokenをバーンすることでERC-20 トークンを引き出すことができ、ERC-20トークンは再度ユーザーに転送されます。 - -## TruffleとGanacheをインストールする {#install-truffle-and-ganache} - -はじめてスマートコントラクトを作成する場合は、環境設定が必要です。 [Truffle](https://www.trufflesuite.com/)と[Ganache](https://www.trufflesuite.com/ganache)という2つのツールを使用します。 - -Truffleはイーサリアムのスマートコントラクトを開発するための開発環境とテストフレームワークです。 Truffleを使用すると、簡単にスマートコントラクトを構築し、ブロックチェーンでデプロイできます。 Ganacheは、スマートコントラクトをテストするために、ローカルのイーサリアムブロックチェーンを作成することができます。 Ganacheは、実際のネットワークの機能をシミュレートし、最初の10アカウントに対しテスト用の100etherが供給します。 これにより、無料で自由にスマートコントラクトをデプロイし、テストできるようになります。 Ganacheは、デスクトップアプリケーションとコマンドラインツールの両方が提供されています。 この記事では、UIデスクトップアプリケーションを使用します。 - -![Ganache UIデスクトップアプリケーション](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_GanacheのUI デスクトップアプリケーション _ - -プロジェクトを作成するには、次のコマンドを実行します - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -これにより、スマートコントラクトを開発し、デプロイするための空のプロジェクトが作成されます。 作成したプロジェクトの構造は以下のようになります: - -- `contracts`:Solidityで作成したスマートコントラクトのフォルダ - -- `migrations`:デプロイ用スクリプトのフォルダ - -- `test`:スマートコントラクトをテストするためのフォルダ - -- `truffle-config.js`:Truffleの設定ファイル - -## ERC-20トークンを作成する {#create-the-erc20-token} - -最初に、スマートコントラクトにステークするために使用するERC-20トークンを作成する必要があります。 代替可能なトークンを作成するには、まずOpenZeppelinライブラリをインストールする必要があります。 このライブラリには、ERC-20やERC-721のような標準の実装が含まれています。 インストールするには、以下のコマンドを実行します: - -```bash -npm install @openzeppelin/contracts -``` - -OpenZeppelinライブラリを使用して、`contracts/MyToken.sol`に以下のSolidityコードを書き込むことでERC-20トークンを作成できます。 - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -上記のコードでは: - -- 3行目:このトークン標準の実装を含むOpenZeppelinから、ERC20.solコントラクトをインポートします。 - -- 5行目:ERC20.solコントラクトを継承します。 - -- 6行目:ERC20.solコンストラクタを呼び出し、名前とシンボルパラメータを `"MyToken"` と `"MTKN"` として引き渡します。 - -- 7行目:スマートコントラクトをデプロイしているアカウントに、100万トークンを発行して転送します(ERC-20トークンでは、デフォルトである小数点以下18桁を使用します。 つまり、1トークンをミントしたい場合は、1000000000000000000と、1の後に18個の0を付けて表します) 。 - -以下のERC20.solコンストラクタの実装では、 `_decimals`フィールドが18に設定されているのが確認できます: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## ERC-20トークンをコンパイルする {#compile-the-erc20-token} - -スマートコントラクトをコンパイルするには、まずSolidityコンパイラのバージョンを確認してください。 バージョンを確認するには、以下のコマンドを実行します: - -```bash -truffle version -``` - -デフォルトのバージョンは `Solidity v0.5.16` です。 このトークンはSolidityのバージョン `0.6.2` を使って作成されているため、このコマンドを実行してコントラクトをコンパイルしようとするとエラーが発生します。 使用したいSolidityコンパイラのバージョンを指定するには、`truffle-config.js`を開き、以下のように設定します。 - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -以下のコマンドを実行すると、スマートコントラクトがコンパイルされます。 - -```bash -truffle compile -``` - -## ERC-20トークンをデプロイする {#deploy-erc20-token} - -コンパイルが完了すると、トークンをデプロイできるようになります。 - -`migrations`フォルダに、 `2_deploy_Tokens.js`という名前のファイルを作成します。 このファイルでは、ERC-20トークンとFarm Tokenスマートコントラクトの両方をデプロイします。 以下のコードは、MyToken.solコントラクトをデプロイするために使用します: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Ganacheを開いて「QuickStart」のオプションを選択すると、ローカルのイーサリアムブロックチェーンが開始されます。 コントラクトをデプロイするには、以下を実行します: - -```bash -truffle migrate -``` - -コントラクトのデプロイに使用するアドレスは、Ganacheで表示されるアドレスリストの一番上のアドレスです。 これを確認するには、Ganacheのデスクトップアプリケーションを開きます。スマートコントラクトをデプロイするためにコストが発生したため、リストの一番上のアカウントではetherの残高が減少していることを確認してください。 - -![Ganacheデスクトップアプリケーション](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Ganacheデスクトップアプリケーション_ - -デプロイ先アドレスに「MyToken」トークンが100万個送信されたことを確認するには、Truffle Consoleを使ってデプロイ済みのスマートコントラクトと接続します。 - -> [Truffle Consoleは、あらゆるイーサリアムクライアントに接続できる基本的な対話型コンソールです。](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -スマートコントラクトとのやりとりを実行するには、以下のコマンドを実行します: - -```bash -truffle console -``` - -ターミナル上で、以下のコマンドが入力可能になりました: - -- スマートコントラクトの取得: `myToken = await MyToken.deployed()` - -- Ganacheからアカウント情報を取得する:`accounts = await web3.eth.getAccounts()` - -- 一番上のアカウントの残高を取得する: `balance = await myToken.balanceOf(accounts[0])` - -- 残高のフォーマットを、小数点以下18桁に設定する:`web3.utils.fromWei(balance.toString())` - -上記のコマンドを実行すると、最初のアドレスに実際に100万個のMyTokensが含まれていることが確認できます。 - -![一番上のアドレスに、100万MyTokenが含まれています](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_最初のアドレスに、100万MyTokensが含まれています。_ - -## Farm Tokenのスマートコントラクトを作成する {#create-farmtoken-smart-contract} - -Farm Tokenのスマートコントラクトは、以下の3つの機能を持ちます: - -- `balance()`:Farm TokenスマートコントラクトにおけるMyTokenの残高を取得します。 - -- `deposit(uint256 _amount)`:ユーザーを代理してMyTokenをFarm Tokenスマートコントラクトに転送し、Farm Tokenを作成した上でユーザーに返送します。 - -- `withdraw(uint256 _amount)`:ユーザーのFarm Tokenをバーンし、MyToken をユーザーのアドレスに転送します。 - -以下のFarm Tokenコンストラクタを確認してください: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- 3~6行目: OpenZeppelinから、以下のコントラクト(IERC20.sol、Address.sol、SafeERC20.sol、ERC20.sol)をインポートします。 - -- 8行目:このFarm Tokenは、ERC-20コントラクトを継承します。 - -- 14~19行目:Farm Tokenコンストラクタは、MyTokenコントラクトのアドレスをパラメータとして受け取り、このコントラクトに`token`のpublic変数を割り当てます。 - -それでは、`balance()`関数を実装しましょう。 この関数は、パラメータを受け取らず、スマートコントラクトのMyToken残高を返します。 以下のように実装します: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -`deposit(uint256 _amount)`関数は、ユーザーが入金したい金額をパラメータとして受け取り、Farm Tokenを作成した上でユーザーに転送します。 - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -`withdraw(uint256 _amount)` 関数は、ユーザーがバーンしたいFarm Tokenの金額をパラメータして受け取り、同額のMy Tokenをユーザーに転送します。 - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -次に、スマートコントラクトを実装します。 `2_deploy_Tokens.js`ファイルに戻り、デプロイする新しいコントラクトを追加してください: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Farm Tokenをデプロイする時は、デプロイ済みのMyTokenコントラクトのアドレスがパラメータとして提供される点に注意してください。 - -次に、`truffle compile`と `truffle migrate`を実行して、コントラクトをデプロイします。 - -次に、スマートコントラクトのテストを実行します。 スマートコントラクトとのやり取りには、`truffle console`を使用するのではなく、テストプロセスを自動化するスクリプトを作成します。 `scripts`というフォルダを作成し、`getMyTokenBalance.js`ファイルを追加してください。 このファイルで、Farm TokenスマートコントラクトにおけるMyToken残高を確認できます。 - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -このスクリプトを実行するには、以下のcliコマンドを実行します: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -ここでは、予想通り「0」が表示されます。 Farm Tokenがデプロイされていないというエラーが表示された場合、Truffleネットワークに最新バージョンのコントラクトコードが提供されていないことを意味します。 Ganacheを閉じて再度quickstartを実行してから、確実に`truffle migrate`を実行してください。 - -次に、MyTokenをこのスマートコントラクト上でステーキングしましょう。 `deposit(uint256 _amount)` はERC-20の`safeTransferFrom`関数を呼び出す関数ですから、ユーザーはまず、スマートコントラクトがユーザーの代理としてMyTokenを送信するのを承認する必要があります。 このため以下のスクリプトでは、まずこのステップを承認し、その上で関数を呼び出します。 - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -`truffle exec .\scripts\transferMyTokenToFarmToken.js`で、このスクリプトを実行できます。 コンソールには、次のように表示されます。 - -![transferMyTokenToFarmToken.jsの出力](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_transferMyTokenToFarmToken.js の出力_ - -一番上のアカウントにFarm Tokenが入金されたことが確認できるので、スマートコントラクトに MyTokenを入金することができました。 - -出金は、以下の方法で行います: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -`truffle exec .\scripts\drawMyTokenFromTokenFarm.js`で、このスクリプトを実行できます。 以下の出力では、再度My Tokenを取得できており、Farm Tokenがバーンされたことを確認できます。 - -![withdrawMyTokenFromTokenFarm.jsの出力](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_withdrawMyTokenFromTokenFarm.js の出力_ - -## 参考文献 {#references} - -[コントラクト - OpenZeppelin 関連文書](https://docs.openzeppelin.com/contracts/3.x/) - -[スマートコントラクトに最適なツール | Truffle Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[分散型金融(DeFi)とは 初心者向けガイド(2021年更新版)(99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - DeFi Llamaの分散型金融リーダーボード](https://defillama.com/) diff --git a/public/content/translations/ja/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/ja/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index d0182de4825..4b527655e10 100644 --- a/public/content/translations/ja/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/ja/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "Solidity" - "スマートコントラクト" - "ストレージ" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ sourceUrl: https://soliditydeveloper.com/max-contract-size コントラクトコードの固有のサイズ制限が、ブロックのガスリミットとなるため、本来これは問題ではありませんでした。 コントラクトは、コントラクトのバイトコードをすべて含むトランザクション内でデプロイされる必要があることは言うまでもありません。 ブロックに1つのトランザクションのみを含めると、そのガスのすべてを使うことができますが、無限ではありません。 [ロンドンアップグレード](/history/#london)以降、ブロックのガスリミットは、ネットワークの需要に応じて15M~30M間で変えられるようになりました。 -## サイズ制限への対処 {#taking-on-the-fight} - -残念ながら、コントラクトのバイトコードサイズを取得する簡単な方法はありません。 Truffleをご使用の場合は、サイズの取得に役立つ[truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size)プラグインという素晴らしいツールがあります。 - -1. `npm install truffle-contract-size` -2. _truffle-config.js_にプラグインを追加します。`plugins: ["truffle-contract-size"]` -3. `truffle run contract-size`を実行します。 - -これにより、変更内容がコントラクトの合計サイズにどのような影響を与えているかを把握することができます。 - 次に、いくつかの方法を、効果が大きいものから順に見ていきます。 減量の観点から考えてみましょう。 目標体重(この場合は24 KB)を達成するための最良の戦略は、まず効果が大きい方法に集中して取り組むことです。 ほとんどの場合、食生活を改善するだけで解決しますが、もう少し何かが必要な場合もあります。 その場合は、運動(中程度の効果)やサプリメント(小さな効果)を加えるとよいでしょう。 ## サイズ削減効果: 大 {#big-impact} diff --git a/public/content/translations/ja/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/ja/developers/tutorials/secure-development-workflow/index.md index 7b312f73b87..11fe3f32d6e 100644 --- a/public/content/translations/ja/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/ja/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ sourceUrl: https://github.com/crytic/building-secure-contracts/blob/master/devel - コントラクトがアップグレード可能かどうか: [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks)または[Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/)を使って、アップグレード可能性に関するコードに欠陥がないか確認します。 当チームでは、アップグレードの失敗につながる17のケースを文書化しています。 - コントラクトは、ERC準拠を謳っていますか? [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance)で確認してください。 このツールでは、6種類の一般的な仕様に準拠していない場合、ただちに指摘されます。 -- Truffleの単体テストを活用していますか? [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation)を使って、単体テストを含めてください。 あなたが作成したコードに基づき、ERC-20の各機能につき、セキュリティに関する一連の堅牢な属性を自動的に生成します。 - サードパーティのトークンと統合予定ですか? 外部コントラクトを利用する事前に、この[トークン統合チェックリスト](/developers/tutorials/token-integration-checklist/)でレビューしてください。 コードにおける重要なセキュリティ関連の機能を、視覚的にチェックします。 diff --git a/public/content/translations/ja/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/ja/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 6d9b6b25add..00000000000 --- a/public/content/translations/ja/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "SolidityとTruffleを使って、継続的統合を設定する" -description: 有益なプラグインと共にTruffleでテストを行うために、TravisまたはCircle CIを設定する方法 -author: Markus Waas -lang: ja -tags: - - "Solidity" - - "スマートコントラクト" - - "テスト" - - "Truffle" - - "Ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -Truffleを使用した継続的統合(CI)は、基本的なテストセットを実装してあれば、非常に有益な開発環境を提供します。 非常に長期的なテストを実行できるため、[プルリクエスト](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)をマージする事前にすべてのテストに合格したことを確認でき、追加ツールを使って様々な統計を追跡することができます。 - -今回は、[Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin)を使用して継続的統合を設定します。 以下の内容は、Travis CIまたはCircle CIを使って実行できます。 - -## Travis CIの設定 {#setting-up-travis-ci} - -[Travis CI](https://travis-ci.org/)は、簡単に追加できます。 プロジェクトのルートフォルダに、`.travis.yml`設定ファイルを追加するだけです。 - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -ここでは、Truffleで単体テストを実行する場合のみテストスクリプトが実行されるシンプルな状態にしておきましょう。 しかし、Travis CIマシンが利用できるブロックチェーンが存在しないという問題があります。 しかしこれは、テスト前に`npm install ganache-cli`を実行するだけで解決できます。 具体的には、`ganache-cli > /dev/null`のnpxコマンドを含むBashスクリプトを`npx truffle test`の呼び出しの前に追加します。 [こちら](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh)でBashスクリプトの完全な例をご覧ください。 - -## Circle CIの設定 {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/)では、より長い設定ファイルが必要になります。 Travisでは、自動で[`npm ci`](https://docs.npmjs.com/cli/ci.html)コマンドが追加されます。 これにより、`npmのインストール`よりも高速かつセキュアに依存関係をインストールできます。 ここでも、Travisの場合と同じスクリプトを使って、テストの前にganache-cliを実行します。 - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## eth-gas-reporterプラグインを追加する {#adding-the-eth-gas-reporter-plugin} - -eth-gas-reporterプラグインは、スマートコントラクトの関数で発生するガス代を追跡する上でとても役立ちます。 このプラグインをCIに追加しておけば、プルリクエストを追加する際に差分を表示するためにも有益です。 - -### ステップ1:eth-gas-reporterプラグインとcodechecksをインストールする {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### ステップ2:truffle-config.jsのmocha設定で、eth-gas-reporterプラグインを追加する {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[設定のオプションを確認してください。](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### ステップ3:プロジェクトのルートディレクトリに、codechecks.ymlを追加する {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### ステップ4:テストコマンドの後に、codechecksを実行する {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### ステップ5:Codechecksのアカウントを作成する {#step-5-create-a-codechecks-account} - -- [Codechecks](http://codechecks.io/)のアカウントを作成します。 -- GitHubリポジトリに追加します。 -- シークレットをコピーし、`CC_SECRET=COPIED SECRET`をCIに追加します(Travisの場合は[こちら](https://docs.travis-ci.com/user/environment-variables/)、CircleCiの場合は[こちら](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)を参照してください)。 -- プルリクエストの作成に進んでください。 - -以上です。 これで、プルリクエストでガス代の変化に対して素晴らしいレポートが表示されます。 - -![ガスレポートの例](./gas-reports.png) - -## solidity-coverageプラグインを追加する {#adding-the-solidity-coverage-plugin} - -solidity-coverageプラグインを使用すると、コードパスのうちテスト対象に含まれる割合がどの程度か確認できます。 CI上で設定しておくと、非常に便利になります。 - -### ステップ1:メタコインプロジェクトを作成し、カバレッジツールをインストールします。 {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### ステップ2:truffle-config.jsのプラグイン配列に、solidity-coverageを追加します。 {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### ステップ3:.travis.ymlまたはCircle CI config.ymlに、カバレッジコマンドを追加します。 {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Soidityカバレッジは、それ自体でganache-cliを開始しますので、ganache-cliをインストールする必要はありません。 ただし、カバレッジのganache-cliは動作が異なり、通常の単体テスト実行の代替とはならないため、通常のテストコマンドは置き換えないでください。 - -### ステップ4:Coverallsにレポジトリを追加します。 {#step-4-add-repository-to-coveralls} - -- [Coveralls](https://coveralls.io/)のアカウントを作成します。 -- 作成したアカウントをGitHubリポジトリに追加します。 -- プルリクエストの作成に進んでください。 - -![Coverallの例](./coverall.png) - -## 追加のヒント {#further-ideas} - -- [MythX](https://mythx.io/):MythXでは、スマートコントラクトのセキュリティを自動で分析できます。 ですから、[CIに追加する](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/)のはよいアイディアでしょう。 -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29):Lintingツールを活用することで、ある程度まで強制的によいコードを書くことができます。 [Eslint](https://eslint.org/)は、JavaScriptと相性が良く[セットアップが簡単](https://eslint.org/docs/user-guide/getting-started)です。一方[Solhint](https://protofire.github.io/solhint/)は、Solidityで使用できます。 -- 長期テスト:数百人のユーザーを対象としてコントラクトをテストするなど、ストレスが極端に大きいテストを実行したい場合もあるでしょう。 このようなテストは、長時間を要します。 テストごとに実行する代わりに、CIに追加します。 - -これで完了です。 開発環境において非常に有益な戦略であることが理解できたと思います。 完全な実例は、[Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example)で確認してください。 Circle-CIとTravisの両方共必要な訳ではないので、使わない方は確実に削除してください! diff --git a/public/content/translations/ja/enterprise/index.md b/public/content/translations/ja/enterprise/index.md index 20413fd8e15..a978fea4d3d 100644 --- a/public/content/translations/ja/enterprise/index.md +++ b/public/content/translations/ja/enterprise/index.md @@ -83,7 +83,6 @@ Hyperledger、Quorum、Cordaプロジェクトが開始された2016年頃から - [ベースラインプロジェクト](https://www.baseline-protocol.org/) - _ベースラインプロトコルはツールとライブラリのセットで、企業が各システムのデータを維持しつつ、プライバシーを守って複雑でマルチパーティのビジネスプロセスおよびワークフローを調整することを支援。 この標準により、ネットワークを共通の参照フレームとして使うことで、2つ以上の状態マシンがデータの一貫性とワークフローの継続性を実現し、維持することが可能_ - [Chainlens](https://www.chainlens.com/) - _Web3 LabsのSaaSおよびオンプレミスのブロックチェーンデータおよび分析プラットフォーム_ - [アーンスト・アンド・ヤング「Nightfall」](https://github.com/EYBlockchain/nightfall_3) - _オプティミスティック・ロールアップを使って、ERC20、ERC721、ERC1155アプリケーションをゼロ知識で転送するためのアプリケーション_ -- [Truffle Suite](https://trufflesuite.com) - _ブロックチェーン開発スイート (Truffle、Ganache、Drizzle)_ ### スケーラビリティソリューション {#scalability-solutions} diff --git a/public/content/translations/ko/enterprise/index.md b/public/content/translations/ko/enterprise/index.md index f1d7acc59d4..7a7833fbde7 100644 --- a/public/content/translations/ko/enterprise/index.md +++ b/public/content/translations/ko/enterprise/index.md @@ -75,7 +75,6 @@ sidebarDepth: 1 - [Alethio](https://explorer.aleth.io/) _이더리움 데이터 분석 플랫폼_ - [Treum](https://treum.io/) _블록체인 기술을 사용하여 공급망에 투명성, 추적성, 거래성 제공_ -- [Truffle Suite](https://trufflesuite.com) _블록체인 개발 제품군(Truffle, Ganache, Drizzle)_ ## 엔터프라이즈 개발자 커뮤니티 {#enterprise-developer-community} diff --git a/public/content/translations/lt/enterprise/index.md b/public/content/translations/lt/enterprise/index.md index 72836751759..ba69c0b65b2 100644 --- a/public/content/translations/lt/enterprise/index.md +++ b/public/content/translations/lt/enterprise/index.md @@ -75,7 +75,6 @@ Viešiesiems ir privatiems Ethereum tinklams gali prireikti specifinių savybių - [Alethio](https://explorer.aleth.io/) _Ethereum duomenų analizės platforma_ - [Treum](https://treum.io/) _naudojant blokų grandinės technologiją, tiekimo grandinėms suteikiamas skaidrumas, atsekamumas ir galimybė prekiauti _ -- [Truffle Suite](https://trufflesuite.com) _blokų grandinės kūrimo rinkinys (Truffle, Ganache, Drizzle)_ ## Verslo kūrėjų bendruomenė {#enterprise-developer-community} diff --git a/public/content/translations/ml/enterprise/index.md b/public/content/translations/ml/enterprise/index.md index 894dcf78f9d..d4105992a3e 100644 --- a/public/content/translations/ml/enterprise/index.md +++ b/public/content/translations/ml/enterprise/index.md @@ -74,7 +74,6 @@ Ethereum എന്റർപ്രൈസ് സൗഹൃദമാക്കുന - [അലീത്തിയോ](https://explorer.aleth.io/) _Ethereum ഡാറ്റാ അനലിറ്റിക്സ് പ്ലാറ്റ്ഫോം _ - [ട്രീം](https://treum.io/) _ ബ്ലോക്ക്ചെയിൻ സാങ്കേതികവിദ്യ ഉപയോഗിച്ച് ശൃംഖലകൾ വിതരണം ചെയ്യുന്നതിനുള്ള സുതാര്യത, കണ്ടെത്തൽ, വ്യാപാരം എന്നിവ കൊണ്ടുവരുന്നു _ -- [ട്രഫിൾ സ്വീറ്റ്](https://trufflesuite.com) _ ബ്ലോക്ക്‌ചെയിൻ വികസന സ്വീറ്റ് (ട്രഫിൽ, ഗണാഷെ, drizzle) _ ## എന്റർപ്രൈസ് ഡവലപ്പർ കമ്മ്യൂണിറ്റി {#enterprise-developer-community} diff --git a/public/content/translations/nb/enterprise/index.md b/public/content/translations/nb/enterprise/index.md index 1d400acbdae..7b088abae18 100644 --- a/public/content/translations/nb/enterprise/index.md +++ b/public/content/translations/nb/enterprise/index.md @@ -74,7 +74,6 @@ Offentlige og private Ethereum-nettverk kan trenge spesifikke funksjoner som kre - [Alethio](https://explorer.aleth.io/) _Ethereum Data Analyse Platform_ - [Treum](https://treum.io/) _bringer gjennomsiktighet, sporbarhet og evne til å forsyne kjeder, ved bruk av blokkjedeteknologi_ -- [Truffle Suite](https://trufflesuite.com) _blockchain development suite (Truffle, Ganache, Drizzle)_ ## Fellesskap for bedriftsutviklere {#enterprise-developer-community} diff --git a/public/content/translations/nl/community/support/index.md b/public/content/translations/nl/community/support/index.md index c0900c581eb..7b09ff2d278 100644 --- a/public/content/translations/nl/community/support/index.md +++ b/public/content/translations/nl/community/support/index.md @@ -55,7 +55,6 @@ Hier zijn enkele populaire voorbeelden: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/pl/community/support/index.md b/public/content/translations/pl/community/support/index.md index 85ecafed5f5..5a20b4aa743 100644 --- a/public/content/translations/pl/community/support/index.md +++ b/public/content/translations/pl/community/support/index.md @@ -57,7 +57,6 @@ Oto kilka popularnych przykładów: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/pl/developers/docs/development-networks/index.md b/public/content/translations/pl/developers/docs/development-networks/index.md index 884c6a133b8..ac50b0c662c 100644 --- a/public/content/translations/pl/developers/docs/development-networks/index.md +++ b/public/content/translations/pl/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ _Mógłbyś_ [uruchomić węzeł](/developers/docs/nodes-and-clients/#running-yo **Uwaga**: większość [frameworków programistycznych](/developers/docs/frameworks/) zawiera wbudowaną sieć programistyczną. Zalecamy zaczynać od frameworka, aby [skonfigurować lokalne środowisko programistyczne](/developers/local-environment/). -### Ganache {#ganache} - -Szybko odpal osobisty blockchain Ethereum, który możesz wykorzystać do uruchamiania testów, wykonywania poleceń i sprawdzania stanu, kontrolując jednocześnie sposób działania łańcucha. - -Ganache dostarcza zarówno aplikację stacjonarną (Ganache UI), jak i narzędzie wiersza poleceń (`ganache-cli`). Jest to część zestawu narzędzi Truffle. - -- [Strona internetowa](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Dokumentacja](https://www.trufflesuite.com/docs/ganache/overview) - ### Sieć Hardhat {#hardhat-network} Lokalna sieć Ethereum zaprojektowana pod kątem [rac programistycznych. Pozwala na wdrożenie kontraktów, wykonanie testów i debugowanie kodu diff --git a/public/content/translations/pl/developers/docs/frameworks/index.md b/public/content/translations/pl/developers/docs/frameworks/index.md index c1cbaff493f..a6af98822ab 100644 --- a/public/content/translations/pl/developers/docs/frameworks/index.md +++ b/public/content/translations/pl/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Przed zagłębieniem się w frameworki zalecamy przeczytanie naszego wprowadzeni ## Dostępne frameworki {#available-frameworks} -**Truffle —** **_środowisko programistyczne, testowanie frameworka i inne narzędzia._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Epirus —** **_platforma do tworzenia, wdrażania i monitorowania aplikacji blockchain na JVM_** - [Strona główna](https://www.web3labs.com/epirus) diff --git a/public/content/translations/pl/developers/docs/programming-languages/golang/index.md b/public/content/translations/pl/developers/docs/programming-languages/golang/index.md index 672c98f5310..8e7dd6c7ca5 100644 --- a/public/content/translations/pl/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/pl/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Potrzebujesz bardziej podstawowych informacji? Sprawdź na stronach [ethereum.or ## Artykuły i książki dla początkujących {#beginner-articles-and-books} -- [Wybór klienta Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Pierwsze kroki z Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Użycie Golang do połączenia się z Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Wdrażanie kontraktów inteligentnych w Ethereum za pomocą Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/pl/developers/docs/programming-languages/rust/index.md b/public/content/translations/pl/developers/docs/programming-languages/rust/index.md index de960dd7758..2a06e913b9f 100644 --- a/public/content/translations/pl/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/pl/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Potrzebujesz bardziej podstawowych informacji? Sprawdź na [ethereum.org/learn]( ## Artykuły dla początkujących {#beginner-articles} -- [Wybór klienta Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Klient Ethereum Rust](https://wiki.parity.io/Setup) - [Wysyłanie transakcji do Ethereum za pomocą Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Wprowadzenie do inteligentnych kontraktów z klientem Parity Ethereum](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/pl/developers/docs/security/index.md b/public/content/translations/pl/developers/docs/security/index.md index 535b1cef9b8..489da60cd91 100644 --- a/public/content/translations/pl/developers/docs/security/index.md +++ b/public/content/translations/pl/developers/docs/security/index.md @@ -29,7 +29,7 @@ Co najmniej: - Wszystkie kody przechowywane w systemie z kontrolą wersji, takim jak git - Wszystkie modyfikacje kodu dokonane za pośrednictwem Pull Request - Wszystkie Pull Request mają przynajmniej jednego recenzenta. _Jeśli realizujesz projekt jednoosobowo, rozważ znalezienie innego autora pracującego solo i recenzji kodu handlowego!_ -- Pojedyncze polecenie kompiluje, wdraża i uruchamia zestaw testów na Twoim kodzie przy użyciu programistycznego środowiska Ethereum (patrz: Truffle) +- Pojedyncze polecenie kompiluje, wdraża i uruchamia zestaw testów na Twoim kodzie przy użyciu programistycznego środowiska Ethereum - Uruchomiłeś swój kod za pomocą podstawowych narzędzi do analizy kodu, takich jak Mythril i Slither, najlepiej przed scaleniem każdego pull request, porównując różnice w danych wyjściowych - Solidity nie emituje ŻADNYCH ostrzeżeń kompilatora - Twój kod jest dobrze udokumentowany diff --git a/public/content/translations/pl/developers/docs/smart-contracts/testing/index.md b/public/content/translations/pl/developers/docs/smart-contracts/testing/index.md index c7b29760bb1..443036fbbd2 100644 --- a/public/content/translations/pl/developers/docs/smart-contracts/testing/index.md +++ b/public/content/translations/pl/developers/docs/smart-contracts/testing/index.md @@ -34,13 +34,11 @@ incomplete: true ## Powiązane samouczki {#related-tutorials} -- [Solidity and Truffle Continuous Integration Setup](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) _– jak skonfigurować Travis lub Circle CI do testowania Truffle wraz z przydatnymi wtyczkami_ - [Narzędzia testowe](/developers/tutorials/guide-to-smart-contract-security-tools/) _– przegląd i porównanie różnych narzędzi testowych_ - [Echidna – narzędzie do testowania inteligentnych kontraktów](/developers/tutorials/how-to-use-echidna-to-test-smart-contracts/) - [Manticore – narzędzie do znajdowania błędów w inteligentnych kontraktach](/developers/tutorials/how-to-use-manticore-to-find-smart-contract-bugs/) - [Slither – narzędzie do znajdowania błędów w inteligentnych kontraktach](/developers/tutorials/how-to-use-slither-to-find-smart-contract-bugs/) - [Jak tworzyć kontrakty Solidity pod kątem testowania](/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -- [Jak migrować z Truffle Tests do środowiska testowego OpenZeppelin](https://docs.openzeppelin.com/test-environment/0.1/migrating-from-truffle) ## Dalsza lektura {#further-reading} diff --git a/public/content/translations/pl/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/pl/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index 72f162948d6..a42726f0006 100644 --- a/public/content/translations/pl/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/pl/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Manifest jest naszym plikiem konfiguracyjnym i definiuje: - inne rzeczy do słuchania, takie jak wywołania funkcji lub bloki - wywoływane funkcje mapujące (zobacz mapping.ts poniżej) -Tutaj możesz zdefiniować wiele kontraktów i programów obsługi. Typowa konfiguracja miałaby folder podrzędny wewnątrz projektu Truffle/Hardhat z własnym repozytorium. Wtedy możesz łatwo odwołać się do ABI. +Tutaj możesz zdefiniować wiele kontraktów i programów obsługi. Typowa konfiguracja miałaby folder podrzędny wewnątrz projektu Hardhat z własnym repozytorium. Wtedy możesz łatwo odwołać się do ABI. Dla wygody możesz również użyć narzędzia szablonu, takiego jak wąsy. Następnie tworzysz subgraph.template.yaml i wstawiasz adresy oparte na najnowszych wdrożeniach. Aby zapoznać się z bardziej zaawansowaną przykładową konfiguracją, zobacz na przykład [Repozytorium subgrafów Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/pl/enterprise/index.md b/public/content/translations/pl/enterprise/index.md index 0032cc56410..5fcf2c3e11f 100644 --- a/public/content/translations/pl/enterprise/index.md +++ b/public/content/translations/pl/enterprise/index.md @@ -66,7 +66,6 @@ Różne organizacje podjęły pewne wspólne działania, aby uczynić Ethereum p - [Ernst & „Nightfall” firmy Young](https://github.com/EYBlockchain/nightfall) _zestaw narzędzi do prywatnych transakcji_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _aplikacja do podpisywania transakcji do użytku z dostawcą web3_ - [Tenderly](https://tenderly.co/) _platforma danych zapewniająca analizy w czasie rzeczywistym, alerty i monitorowanie z obsługą sieci prywatnych._ -- [Truffle Suite](https://trufflesuite.com) _blockchain development suite (Truffle, Ganache, Drizzle)_ ### Rozwiązania skalowalne {#scalability-solutions} diff --git a/public/content/translations/pt-br/community/support/index.md b/public/content/translations/pt-br/community/support/index.md index 275acd9412a..cb4671e5e20 100644 --- a/public/content/translations/pt-br/community/support/index.md +++ b/public/content/translations/pt-br/community/support/index.md @@ -57,7 +57,6 @@ Aqui estão alguns exemplos populares: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/pt-br/developers/docs/bridges/index.md b/public/content/translations/pt-br/developers/docs/bridges/index.md index 3997d96f8f5..22a4c4c95ea 100644 --- a/public/content/translations/pt-br/developers/docs/bridges/index.md +++ b/public/content/translations/pt-br/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Se um dapp for integrar uma bridge ou um agregador, existem diferentes opções ### Como implantar um dapp em múltiplas cadeias {#deploying-a-dapp-on-multiple-chains} -Para implantar um dapp em várias cadeias, os desenvolvedores podem usar plataformas de desenvolvimento como [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/) etc. Normalmente, essas plataformas vêm com plugins compostos que podem habilitar dapps para cross-chain. Por exemplo, os desenvolvedores podem usar um proxy de implantação determinístico oferecido pelo [plugin hardhat-deploy](https://github.com/wighawag/hardhat-deploy). +Para implantar um dapp em várias cadeias, os desenvolvedores podem usar plataformas de desenvolvimento como [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/) etc. Normalmente, essas plataformas vêm com plugins compostos que podem habilitar dapps para cross-chain. Por exemplo, os desenvolvedores podem usar um proxy de implantação determinístico oferecido pelo [plugin hardhat-deploy](https://github.com/wighawag/hardhat-deploy). #### Exemplos: diff --git a/public/content/translations/pt-br/developers/docs/development-networks/index.md b/public/content/translations/pt-br/developers/docs/development-networks/index.md index 72ea6bd83e1..a2e043d6dfd 100644 --- a/public/content/translations/pt-br/developers/docs/development-networks/index.md +++ b/public/content/translations/pt-br/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Você _poderia_ [executar um nó](/developers/docs/nodes-and-clients/#running-yo **Nota**: [A maioria dos frameworks desenvolvidos](/developers/docs/frameworks/) incluem uma rede de desenvolvimento integrada. Recomendamos começar com um framework para [configurar seu ambiente de desenvolvimento local](/developers/local-environment/). -### Ganache {#ganache} - -Crie uma blockchain Ethereum pessoal que você possa usar para testes, executar comandos e inspecionar seu estado, enquanto controla como a cadeia irá operar. - -Ganache fornece tanto um aplicativo de desktop (Ganache UI), como uma linha de comando (`ganache-cli`). Isso é uma parte da suíte de ferramentas Truffle. - -- [Website](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentação](https://www.trufflesuite.com/docs/ganache/overview) - ### Rede Hardhat {#hardhat-network} Uma rede local Ethereum concebida para desenvolvedores. Isso permite que você implante seus contratos, execute os testes e depure seu código. diff --git a/public/content/translations/pt-br/developers/docs/frameworks/index.md b/public/content/translations/pt-br/developers/docs/frameworks/index.md index beb0882dbd1..fea3950b472 100644 --- a/public/content/translations/pt-br/developers/docs/frameworks/index.md +++ b/public/content/translations/pt-br/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Antes de mergulhar em frameworks, recomendamos que você primeiro leia a nossa i ## Frameworks disponíveis {#available-frameworks} -**Truffle -\*\***_Um ambiente de desenvolvimento, teste de framework, compilação e outras ferramentas._\*\* - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Hardhat -** **_Ambiente de desenvolvimento da Ethereum para profissionais._** - [hardhat.org](https://hardhat.org) diff --git a/public/content/translations/pt-br/developers/docs/programming-languages/dart/index.md b/public/content/translations/pt-br/developers/docs/programming-languages/dart/index.md index 1aa80577876..7c6bbdbb1d2 100644 --- a/public/content/translations/pt-br/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/pt-br/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutoriais {#tutorials} - [Flutter and Blockchain – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) leva você através de todos os passos para iniciar: - 1. Instalando o [Truffle development suite](https://www.trufflesuite.com/) - 2. Escrevendo um contrato inteligente em [Solidity](https://soliditylang.org/) - 3. Escrevendo uma interface de usuário no Dart + 1. Escrevendo um contrato inteligente em [Solidity](https://soliditylang.org/) + 2. Escrevendo uma interface de usuário no Dart - [Construir um dapp para dispositivos móveis com Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) é muito mais curto, o que pode ser melhor - Se você prefere aprender através de vídeos, você pode assistir [Build Your First Blockchain Flutter App](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), que leva aproximadamente uma hora - Se você é impaciente, talvez prefira o [Building a Blockchain Decentralized-app with Flutter and Dart on Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), que leva apenas vinte minutos diff --git a/public/content/translations/pt-br/developers/docs/programming-languages/golang/index.md b/public/content/translations/pt-br/developers/docs/programming-languages/golang/index.md index 1ca9f02b1fd..e14e5475183 100644 --- a/public/content/translations/pt-br/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/pt-br/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Precisa de uma introdução geral? Confira [ethereum.org/learn](/learn/) ou [eth ## Artigos e livros para iniciantes {#beginner-articles-and-books} -- [Escolhendo um Cliente Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Introdução ao Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Use Golang para conectar à Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Implantar Contratos Inteligentes Ethereum Usando Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/pt-br/developers/docs/programming-languages/rust/index.md b/public/content/translations/pt-br/developers/docs/programming-languages/rust/index.md index 25cd09355d7..a4ecf6a72dc 100644 --- a/public/content/translations/pt-br/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/pt-br/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Precisa de uma introdução geral? Confira [ethereum.org/learn](/learn/) ou [eth ## Artigos para Iniciantes {#beginner-articles} -- [Escolhendo um Cliente Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [O cliente Rust Ethereum](https://openethereum.github.io/) /**\*Note que o OpenEthereum [foi descontinuado](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) e não está mais sendo mantido.** Use-o com cuidado e de preferência mude para outra implementação do cliente. - [Enviando uma transação para Ethereum usando Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Uma Introdução aos Contratos Inteligentes com o Cliente Parity Ethereum](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/pt-br/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/pt-br/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index 5b726fa0266..00000000000 --- a/public/content/translations/pt-br/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Criar e promover um Aplicativo DeFi -description: Deposite tokens ERC20 para o contrato inteligente e crie fazenda de tokens -author: "strykerin" -tags: - - "solidity" - - "defi" - - "web3" - - "truffle" - - "ganache" - - "Contratos Inteligentes" -skill: intermediate -lang: pt-br -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -Neste tutorial, construiremos um aplicativo DeFi com Solidity onde os usuários podem depositar um token ERC20 no contrato inteligente e ele cunhará e transferirá os Tokens Farm para eles. Os usuários podem posteriormente retirar seus tokens ERC20 queimando seu Farm Token em contrato inteligente e os tokens ERC20 serão transferidos de volta para eles. - -## Instale o Truffle e o Ganache {#install-truffle-and-ganache} - -Se esta for a primeira vez que você está escrevendo um contrato inteligente, você precisará configurar seu ambiente primeiro. Vamos usar duas ferramentas:[Truffle](https://www.trufflesuite.com/) and [Ganache](https://www.trufflesuite.com/ganache). - -O Truffle é um ambiente de desenvolvimento e estrutura de teste para o desenvolvimento de contratos inteligentes para o Ethereum. Com o Truffle, é fácil construir e implantar contratos inteligentes na blockchain. O Ganache nos permite criar uma blockchain Ethereum local para testar contratos inteligentes. Ele simula os recursos da rede real e as primeiras 10 contas são financiadas com 100 ether de teste, tornando a implantação e o teste do contrato inteligente gratuitos e fáceis. O Ganache está disponível como um aplicativo de desktop e uma ferramenta de linha de comandos. Para este artigo, usaremos o aplicativo de desktop de interface do usuário. - -![Aplicativo de área de trabalho Ganache UI](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Aplicativo de desktop Ganache UI_ - -Para criar o projeto, execute os seguintes passos - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Isso criará um projeto em branco para o desenvolvimento e implantação de nossos contratos inteligentes. A estrutura do projeto criada é a seguinte: - -- A Pasta para os contratos inteligentes de solidez: `contracts` - -- `migrações`: Pasta para os scripts de implantação - -- `test`: Pasta para testar nossos contratos inteligentes - -- `truffle-config.js`: Arquivo de configuração do Truffle - -## Criar o token ERC20 {#create-the-erc20-token} - -Primeiro, precisamos criar seu token ERC20 que usaremos para apostar no contrato inteligente. Para criar nosso token fungível, primeiro precisamos instalar a biblioteca OpenZeppelin. Esta biblioteca contém as implementações de padrões como o ERC20 e o ERC721. Para instalá-lo, execute os passos: - -```bash -npm install @openzeppelin/contracts -``` - -Usando a biblioteca OpenZeppelin, podemos criar nosso token ERC20 gravando em `contracts/MyToken.sol` com o seguinte código solidity: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -No código acima em: - -- Linha 3: Importamos o contrato ERC20.sol do openzeppelin que contém a implementação para este padrão de token. - -- Linha 5: Herdamos do contrato ERC20.sol. - -- Linha 6: Estamos chamando o construtor ERC20.sol e passando os parâmetros name e symbol como `"MyToken"` e `"MTKN"` respectivamente. - -- Linha 7: Estamos cunhando e transferindo 1 milhão de tokens para a conta que está implantando o contrato inteligente (estamos usando os 18 decimais padrão para o token ERC20, o que significa que, se quisermos cunhar 1 token, você o representará como 1000000000000000000, 1 com 18 zeros). - -Podemos ver abaixo a implementação do construtor ERC20.sol onde o campo `_decimals` está definido como 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compilar o token ERC20 {#compile-the-erc20-token} - -Para compilar nosso contrato inteligente, devemos primeiro verificar nossa versão do compilador de solidez. Você pode verificar isso executando o comando: - -```bash -truffle version -``` - -A versão padrão é a `Solidity v0.5.16`. Como nosso token é escrito usando a versão solidity `0.6.2`, se executarmos o comando para compilar nossos contratos, obteremos um erro do compilador. Para especificar qual versão do compilador de solidez será usada, acesse o arquivo `truffle-config. s` e são definidos para a versão desejada do compilador como vistos abaixo: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Agora podemos compilar nosso contrato inteligente executando o seguinte comando: - -```bash -truffle compile -``` - -## Instalar Token ERC20 {#deploy-erc20-token} - -Depois de compilado, podemos publicar nosso token. - -Na pasta de `migrations`, crie um arquivo chamado `2_deploy_Tokens.js`. Este arquivo é onde implantaremos nosso token ERC20 e nosso contrato inteligente FarmToken. O código abaixo é usado para publicar nosso contrato MyToken.sol: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Abra o Ganache e selecione a opção "Quickstart" para iniciar uma blockchain local de Ethereum. Para publicar nosso contrato, execute: - -```bash -truffle migrate -``` - -O endereço usado para implantar nossos contratos é o primeiro da lista de endereços que o Ganache nos mostra. Para verificar isso, podemos abrir o aplicativo de trabalho Ganache e podemos verificar se o saldo de ether para a primeira conta foi reduzido devido ao custo de ether para a implantação dos nossos contratos inteligentes: - -![Aplicativo de desktop Ganache Ui](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Aplicativo de desktop Ganache Ui_ - -Para verificar que 1 milhão de tokens MyToken foram enviados para o endereço de deploy, podemos utilizar o Truffle Console para interagir com o nosso contrato inteligente que foi publicado. - -> [Truffle Console é um console básico interativo conectando-se a qualquer cliente Ethereum.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Para interagir com nosso contrato inteligente, execute o seguinte comando: - -```bash -truffle console -``` - -Agora podemos escrever os seguintes comandos no terminal: - -- Obter o contrato inteligente: `meuToken = await MyToken.deployed()` - -- Obter o array de contas de Ganache: `contas = aguardar web3.eth.getAccounts()` - -- Obter o saldo para a primeira conta: `balance = await myToken.balanceOf(contas[0])` - -- Formate o saldo de 18 decimals: `web3.utils.fromWei(balance.toString())` - -Executando os comandos acima, vamos ver que o primeiro endereço tem na verdade 1 milhão de MyTokens: - -![Primeiro endereço tem 1000000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_Primeiro endereço tem 1000000 MyTokens_ - -## Criando FarmToken Smart Contract {#create-farmtoken-smart-contract} - -O contrato inteligente FarmToken terá 3 funções: - -- `balance()`: Obter o balanço do MyToken no contrato inteligente FarmToken. - -- `deposit(uint256 _amount)`: Transfira MyToken em nome do usuário para o contrato inteligente FarmToken e então importe FarmToken para o usuário. - -- `withdraw(uint256 _amount)`: Queimar FarmTokens do usuário e transferir MyTokens para o endereço do usuário. - -Vamos dar uma olhada no construtor do FarmToken: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Linhas 3-6: Estamos importando os seguintes contratos do openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol e ERC20.sol. - -- Linha 8: O FarmToken vai herdar do contrato ERC20. - -- Linhas 14-19: O construtor FarmToken receberá como parâmetro o endereço do contrato MyToken e atribuiremos seu contrato à nossa variável pública chamada `token`. - -Vamos implementar a função `balance()`. Ele não receberá parâmetros e retornará o saldo do MyToken neste contrato inteligente. Ela está implementada como mostrado abaixo: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -Para a função `deposit(uint256 _amount)`, ele receberá como parâmetro a quantia que o usuário deseja depositar e irá fazer a cunhagem e transferir FarmTokens para o usuário: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -Para a função `withdraw(uint256 _amount)`, nós vamos receber como parâmetro a quantidade de FarmTokens que o usuário deseja queimar e então vamos transferir a mesma quantidade de MyTokens de volta para o usuário: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Como implantar um contrato inteligente. Para fazer isso, vamos voltar para o arquivo `2_deploy_Tokens.js` e adicionar o novo contrato a ser implantado: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -Note que ao implantar o FarmToken, passamos como parâmetro o endereço do contrato MyToken implantado. - -Agora, rode `truffle compilar` e `truffle migrar` para implantar nossos contratos. - -Vamos testar o nosso contrato inteligente. Em vez de usar o `truffle console` para interagir com o nosso contrato inteligente, criaremos um script para automatizar esse processo. Crie uma pasta chamada `scripts` e adicione o seguinte arquivo `getMyTokenBalance.js`. Ele irá verificar o saldo dos MyTokens no contrato inteligente do Farmtoken: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Para executar esse script, execute o seguinte comando na linha de comando: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Vamos obter o resultado esperado que é 0. Se você receber um erro sobre o FarmToken ainda não foi implantado, a rede truffle não recebeu a versão mais recente do seu código de contratos. Apenas feche o ganache, reinicie o programa rapidamente e certifique-se de executar `a migração de um truffle`. - -Agora, vamos fazer o staking do MyToken para o contrato inteligente. Desde a função `deposit(uint256 _amount)` chama a função `safeTransferFrom` do ERC20, primeiro o usuário deve aprovar o contrato inteligente para transferir MyToken em nome do usuário. Então, no script abaixo, primeiro aprovaremos esta etapa e então chamaremos a função: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Para rodar esse script: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Você deve ver no seu console: - -![output do transferMyTokenToFarmToken.js](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_output do transferMyTokenToFarmToken.js_ - -Como podemos ver, depositamos MyTokens com sucesso no contrato inteligente já que a primeira conta agora tem FarmTokens. - -Para retirar: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Para rodar esse script: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Como podemos ver no output abaixo, nós conseguimos de volta os MyTokens com sucesso e acabamos com os FarmTokens: - -![output do withdrawMyTokenFromTokenFarm.js](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_output do withdrawMyTokenFromTokenFarm.js_ - -## Referências {#references} - -[Contratos - OpenZeppelin Docs](https://docs.openzeppelin.com/contracts/3.x/) - -[Ferramentas Suplentes para Contratos Inteligentes Common Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[O que é DeFi? Um guia para iniciantes (atualizado em 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - A classificação da finança descentraliza no DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/pt-br/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/pt-br/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index ed91278fc09..639ca104e83 100644 --- a/public/content/translations/pt-br/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/pt-br/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidez" - "smart contracts" - "armazenamento" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Este limite foi introduzido para impedir ataques de negação de serviço (DOS). Originalmente, tratava-se de um problema menor, porque um limite de tamanho natural do contrato é o limite de gas por bloco. Obviamente, um contrato precisa ser implementado dentro de uma transação que tenha todo o bytecode do contrato. Se você incluir apenas essa transação em um bloco, você pode usar todo esse gas, mas não é infinito. Desde a [London Upgrade](/history/#london), o limite de gas de bloco tem sido capaz de variar entre 15M e 30M de unidades, de acordo com a demanda da rede. -## Começando a luta {#taking-on-the-fight} - -Infelizmente, não há maneira fácil de obter o tamanho do bytecode dos seus contratos. Uma ótima ferramenta para ajudá-lo é o plugin [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) se você estiver usando o Truffle. - -1. `npm install truffle-contract-size` -2. Adicione o plugin ao _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Execute `truffle rodando contract-size` - -Isso irá ajudá-lo a descobrir como suas mudanças estão afetando o tamanho total do contrato. - A seguir, analisaremos alguns métodos ordenados pelo seu potencial impacto. Pense nisso em termos de perda de peso. A melhor estratégia para alguém atingir o seu peso alvo (no nosso caso 24kb) é concentrar-se primeiro nos grandes métodos de impacto. Na maioria dos casos, só de ajustar a sua dieta já ajudará, mas às vezes é necessário de um pouco mais. Então você pode adicionar algum exercício (impacto médio) ou até suplementos (impacto pequeno). ## Grande impacto {#big-impact} diff --git a/public/content/translations/pt-br/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/pt-br/developers/tutorials/secure-development-workflow/index.md index 4a20bad7f85..9491de81926 100644 --- a/public/content/translations/pt-br/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/pt-br/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Considere as características especiais do seu contrato: - Os seus contratos são atualizáveis? Verifique se há defeitos em seu código de capacidade de atualização com o [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) ou [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). Documentamos 17 situações em que as atualizações podem correr mal. - Seus contratos pretendem estar em conformidade com os ERCs? Verifique com [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). Esta ferramenta identifica instantaneamente desvios de seis especificações comuns. -- Você tem testes de unidade no Truffle? Verifique com [`slither-check-erc`](https://github.com/crytic/slither/wiki/Property-generation). Ele gera automaticamente um robusto conjunto de propriedades de segurança para recursos do ERC20 com base no seu código específico. - Você faz integrações com tokens de outras empresas? Revise nossa [lista de verificação de integração de tokens](/developers/tutorials/token-integration-checklist/) antes de confiar em contratos externos. Visualmente inspecione recursos críticos de segurança com seu código: diff --git a/public/content/translations/pt-br/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/pt-br/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index df50e1e3c93..00000000000 --- a/public/content/translations/pt-br/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Configuração contínua de integração Solidity e Truffle" -description: Como configurar o Travis ou Circle CI para testes deTruffle, juntamente com plugins úteis -author: Markus Waas -lang: pt-br -tags: - - "solidez" - - "contratos inteligentes" - - "testando" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -A integração contínua (CI) com o Truffle é excelente para desenvolvimento assim que você tiver um conjunto básico de testes implementados. Isso permite que você execute testes muito longos, garantir que todos os testes passem antes de mesclar um [pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) e para manter o controle de várias estatísticas usando ferramentas adicionais. - -Usaremos o [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) para configurar nossa integração contínua. Você pode escolher o Travis CI ou o Circle CI. - -## Configurando Travis CI {#setting-up-travis-ci} - -Adicionando [Travis CI](https://travis-ci.org/) é reta. Você só precisará adicionar um arquivo de configuração `.travis.yml` na pasta raiz do projeto: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Nós estamos mantendo tudo simples por enquanto e estamos executando apenas o script de teste que executa os testes de unidade Truffle. Mas temos um problema, não haverá uma blockchain disponível na máquina Travis CI. Uma correção simples para isso é `npm install ganache-cli` e simplesmente executá-lo antes do teste. Você pode fazer isso adicionando um bash script com a linha npx `ganache-cli > /dev/null` e antes da chamada `npx truffle`. O [script bash completo de exemplo](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Configurando o Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) requer um arquivo de configuração mais longo. O comando adicional [`npm ci`](https://docs.npmjs.com/cli/ci.html) é feito automaticamente no Travis. Ele instala as dependências mais rápido e mais seguro do que o `npm install` faz. Nós usamos novamente o mesmo script da versão de Travis para rodar ganache-cli antes dos testes. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Adicionando o plugin eth-gas-reportter {#adding-the-eth-gas-reporter-plugin} - -O plugin eth-gas-reportter é bastante útil para manter o controle dos custos de gas de suas funções de contrato inteligente. Tê-lo em seu CI será mais útil para mostrar diffs ao adicionar pull requests. - -### Passo 1: Instale o plugin eth-gas-reportter e as verificações de código {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### Etapa 2: Adicione o plugin nas configurações do mocha dentro do arquivo truffle-config.js {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Ver opções](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Passo 3: Adicione um codechecks.yml ao diretório raiz do seu projeto {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Passo 4: Execute verificações de código após o comando de teste {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Passo 5: Crie uma conta no Codechecks {#step-5-create-a-codechecks-account} - -- Crie uma conta com [Codechecks](http://codechecks.io/). -- Adicionar o repositório do Github a ele. -- Copie o segredo e adicione o `CC_SECRET=SEGRET COPIADO` ao seu CI (veja aqui para [Travis](https://docs.travis-ci.com/user/environment-variables/),, aqui para [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Agora vá em frente e crie um pull request. - -É isso. Agora você vai encontrar um bom relatório sobre mudanças nos custos de gas do seu pull request. - -![Exemplos de relatórios de gas](./gas-reports.png) - -## Adicionando o plugin Solidity-coverage {#adding-the-solidity-coverage-plugin} - -Com o plugin Solidity-coverage, você pode verificar a quantidade de caminhos de seu código cobertos por seus testes. Adicionar isto à sua criação de CI é muito conveniente quando for criado. - -### Passo 1: Crie um projeto metacoin e instale ferramentas de cobertura {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### Etapa 2: Adicionar solidity-coverage para o array de plugins em truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Passo 3: Adicione os comandos de cobertura ao arquivo .travis.yml ou Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -A cobertura da Solidity começa seu próprio ganache-cli, então não precisamos nos preocupar com isso. Não substitua o comando de teste regular, porém, a cobertura de ganache-cli funciona de forma diferente e, portanto, não é substituto para a execução de testes de unidade regulares. - -### Passo 4: Adicionar repositório às coberturas {#step-4-add-repository-to-coveralls} - -- Crie uma conta com [Codechecks](https://coveralls.io/). -- Adicionar o repositório do Github a ele. -- Agora vá em frente e crie um pull request. - -![Exemplo de cobertura](./coverall.png) - -## Mais idéias {#further-ideas} - -- [MitX](https://mythx.io/): Com MythX você pode analisar automaticamente a segurança de seu contrato inteligente. Então faz muito sentido [adicionar isto ao seu CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Um bom código pode ser aplicado até certo ponto com ferramentas de linting. [Eslint](https://eslint.org/) funciona muito bem para JavaScript, é [ fácil de configurar](https://eslint.org/docs/user-guide/getting-started), enquanto [Solhint](https://protofire.github.io/solhint/) pode ser usado para Solidity. -- Testes longos: Às vezes, você pode querer adicionar testes extremos, por exemplo, testar contratos com centenas de usuários. Isto leva muito tempo. Em vez de executar aqueles em cada execução de teste, adicione-os ao CI. - -Aí está o que tem. A integração contínua é uma estratégia muito útil para os seus desenvolvimentos. Você pode conferir um exemplo completo em [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Basta remover o Circle-CI ou Travis, um é suficiente! diff --git a/public/content/translations/pt-br/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/pt-br/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index d87753ec150..5fc117503d7 100644 --- a/public/content/translations/pt-br/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/pt-br/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ O manifesto é nosso arquivo de configuração e define: - outras coisas para ouvir como chamadas de função ou blocos - as fnções de mapping sendo chamadas (conferir `mapping.ts` below) -Aqui você pode definir vários contratos e manipuladores. Uma configuração típica teria uma pasta de subgráfico dentro do projeto Truffle/Hardhat com seu próprio repositório. Então você pode facilmente se referir ao ABI. +Aqui você pode definir vários contratos e manipuladores. Uma configuração típica teria uma pasta de subgráfico dentro do projeto Hardhat com seu próprio repositório. Então você pode facilmente se referir ao ABI. Por conveniência você também pode querer usar uma ferramenta modelo tipo um bigode. Em seguida, você cria um `subgraph.template.yaml` e insere os endereços com base nas mais recentes implantações. Para uma configuração de exemplo mais avançada, veja, por exemplo, o [repositório de subgráfico Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/pt-br/enterprise/index.md b/public/content/translations/pt-br/enterprise/index.md index 1e3004c2919..00c4bda4c2a 100644 --- a/public/content/translations/pt-br/enterprise/index.md +++ b/public/content/translations/pt-br/enterprise/index.md @@ -72,7 +72,6 @@ Diversas organizações trabalharam juntas para tornar o Ethereum amigável para - [Ernst & Young ‘Nightfall’](https://github.com/EYBlockchain/nightfall) _é um conjunto de ferramentas para transações privadas_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _é um aplicativo de assinatura de transações para ser usado com um provedor web3_ - [Tenderly](https://tenderly.co/) _é uma plataforma de dados que fornece análise em tempo real, alertando e monitorando com suporte a redes privadas_ -- [Truffle Suite](https://trufflesuite.com) _pacote de desenvolvimento da blockchain (Truffle, Ganache, Drizzle)_ ### Soluções de escalabilidade {#scalability-solutions} diff --git a/public/content/translations/ro/community/support/index.md b/public/content/translations/ro/community/support/index.md index 74501afe722..7aa75176481 100644 --- a/public/content/translations/ro/community/support/index.md +++ b/public/content/translations/ro/community/support/index.md @@ -55,7 +55,6 @@ Iată doar câteva exemple populare: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) ## Rularea unui nod {#node-support} diff --git a/public/content/translations/ro/developers/docs/development-networks/index.md b/public/content/translations/ro/developers/docs/development-networks/index.md index 396df63f9eb..32322b0d91f 100644 --- a/public/content/translations/ro/developers/docs/development-networks/index.md +++ b/public/content/translations/ro/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Ați _putea_ [executa un nod](/developers/docs/nodes-and-clients/#running-your-o **Observaţie**: Majoritatea [framework-urilor de dezvoltare](/developers/docs/frameworks/) includ o rețea de dezvoltare integrată. Vă recomandăm să începeţi cu un framework pentru a vă [configura mediul de dezvoltare local](/developers/local-environment/). -### Ganache {#ganache} - -Lansează rapid un blockchain personal Ethereum pe care îl puteţi folosi pentru a rula teste, a executa comenzi și a inspecta starea în timp ce controlaţi modul în care funcționează lanțul. - -Ganache oferă atât o aplicație desktop (Ganache UI), cât și un instrument de linie de comandă (`ganache-cli`). Face parte din suita de unelte Truffle. - -- [Site web](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Documentație](https://www.trufflesuite.com/docs/ganache/overview) - ### Rețeaua Hardhat {#hardhat-network} O rețea locală Ethereum concepută pentru dezvoltare. Vă permite să vă implementaţi contractele, să vă execuți testele și să eliminaţi bug-urile din cod. diff --git a/public/content/translations/ro/developers/docs/frameworks/index.md b/public/content/translations/ro/developers/docs/frameworks/index.md index 9b0fcabc254..11bc8bdee0d 100644 --- a/public/content/translations/ro/developers/docs/frameworks/index.md +++ b/public/content/translations/ro/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Framework-urile sunt prevăzute cu numeroase funcționalități predefinite, cum ## Framework-uri disponibile {#available-frameworks} -**Truffle - ** **_un mediu de dezvoltare, un framework de testare, de construire de pipeline și alte instrumente._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Hardhat -** **_Ethereum development environment for professionals._** - [hardhat.org](https://hardhat.org) diff --git a/public/content/translations/ro/developers/docs/programming-languages/dart/index.md b/public/content/translations/ro/developers/docs/programming-languages/dart/index.md index 3fda4aa22e8..d1b1adcab2f 100644 --- a/public/content/translations/ro/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/ro/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Tutoriale {#tutorials} - [Flutter și Blockchain – Aplicația dapp „Hello World”](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) vă conduce prin toate etapele, pentru început: - 1. Instalarea [suitei de dezvoltare Truffle](https://www.trufflesuite.com/) - 2. Scrierea unui contract inteligent în [Solidity](https://soliditylang.org/) - 3. Scrierea unei interfețe cu utilizatorul în Dart + 1. Scrierea unui contract inteligent în [Solidity](https://soliditylang.org/) + 2. Scrierea unei interfețe cu utilizatorul în Dart - [Construirea unei aplicaţii dApp mobile cu Flutter](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) este mult mai scurtă, de aceea ar fi mai bine să cunoaşteţi deja elementele de bază. - Dacă preferați să învățați vizionând un videoclip, puteți viziona [Construiți-vă prima aplicație Blockchain cu Flutter](https://www.youtube.com/watch?v=3Eeh3pJ6PeA), care durează circa o oră - Dacă sunteți nerăbdător, probabil preferați [Construirea unei aplicații blockchain descentralizate cu Flutter și Dart pe Ethereum](https://www.youtube.com/watch?v=jaMFEOCq_1s), care durează doar circa douăzeci de minute diff --git a/public/content/translations/ro/developers/docs/programming-languages/golang/index.md b/public/content/translations/ro/developers/docs/programming-languages/golang/index.md index 1252a5eba70..e421f5bdcd8 100644 --- a/public/content/translations/ro/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/ro/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Aveţi nevoie de o scurtă introducere? Accesaţi [ethereum.org/learn](/learn/) ## Articole și cărți pentru începători {#beginner-articles-and-books} -- [Alegerea unui client Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Primii pași cu Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Utilizați Golang pentru a vă conecta la Ethereum](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Implementarea contractelor smart Ethereum cu Golang](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/ro/developers/docs/programming-languages/rust/index.md b/public/content/translations/ro/developers/docs/programming-languages/rust/index.md index 831beacb2be..87068f97cde 100644 --- a/public/content/translations/ro/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/ro/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Aveţi nevoie de o scurtă introducere? Accesaţi [ethereum.org/learn](/learn/) ## Articole pentru începători {#beginner-articles} -- [Alegerea unui client Ethereum](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Clientul Rust Ethereum](https://openethereum.github.io/) \* **Țineţi cont că OpenEthereum [nu mai este întreținut](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd).** Folosiţi-l cu precauție și este de preferat să treceţi la implementarea unui alt client. - [Trimiterea tranzacțiilor în Ethereum cu clientul Rust](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Introducere despre contractele inteligente cu clientul Parity pentru Ethereum](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/ro/developers/docs/security/index.md b/public/content/translations/ro/developers/docs/security/index.md index f40eabb1178..ae265c4a39e 100644 --- a/public/content/translations/ro/developers/docs/security/index.md +++ b/public/content/translations/ro/developers/docs/security/index.md @@ -29,7 +29,7 @@ Cel puțin: - Toate codurile stocate într-un sistem de control al versiunii, cum ar fi Git - Toate modificările de cod efectuate prin Solicitări Pull - Toate Solicitările Pull au cel puțin un examinator. _Dacă ești într-un proiect solo, ia în considerare găsirea unui alt autor solo și negociază cu el recenzii de coduri!_ -- O singură comandă compilează, implementează și rulează o suită de teste împotriva codului tău utilizând un mediu Ethereum de dezvoltare (vezi: Truffle) +- O singură comandă compilează, implementează și rulează o suită de teste împotriva codului tău utilizând un mediu Ethereum de dezvoltare - Ai rulat codul prin instrumente de analiză a codului de bază, cum ar fi Mythril și Slither, în mod ideal înainte ca fiecare solicitare de extragere să fie îmbinată, comparând diferențele de ieșire - Solidity nu emite NICIUN avertisment al compilatorului - Codul tău este bine documentat diff --git a/public/content/translations/ro/developers/docs/smart-contracts/deploying/index.md b/public/content/translations/ro/developers/docs/smart-contracts/deploying/index.md index c6733389b46..bf9826f3835 100644 --- a/public/content/translations/ro/developers/docs/smart-contracts/deploying/index.md +++ b/public/content/translations/ro/developers/docs/smart-contracts/deploying/index.md @@ -27,7 +27,7 @@ Implementarea unui contract costă de asemenea ether (ETH), deci ar trebui să v ### Etapele de implementare a un contract inteligent {#steps-to-deploy} -Etapele specificie implicate vor depinde de instrumentele pe care le folosiţi. De exemplu, consultaţi [documentația Hardhat pentru implementarea contractelor dvs.](https://hardhat.org/guides/deploying.html) sau [documentația Truffle despre rețele și implementarea aplicațiilor](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment). Acestea sunt două dintre cele mai populare instrumente pentru implementarea contractelor inteligente, care implică redactarea unui script pentru a gestiona etapele de implementare. +Etapele specificie implicate vor depinde de instrumentele pe care le folosiţi. De exemplu, consultaţi [documentația Hardhat pentru implementarea contractelor dvs.](https://hardhat.org/guides/deploying.html). Acestea sunt două dintre cele mai populare instrumente pentru implementarea contractelor inteligente, care implică redactarea unui script pentru a gestiona etapele de implementare. Odată implementat, contractul dvs. va avea o adresă Ethereum ca și alte [conturi](/developers/docs/accounts/). @@ -51,12 +51,6 @@ Odată implementat, contractul dvs. va avea o adresă Ethereum ca și alte [cont - [GitHub](https://github.com/nomiclabs/hardhat) - [Discord](https://discord.com/invite/TETZs2KK4k) -**Truffle - ** **_Un mediu de dezvoltare, un framework de testare, de construire de pipeline-uri și alte instrumente._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [Documentație despre rețele și implementarea aplicațiilor](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) -- [GitHub](https://github.com/trufflesuite/truffle) - ## Tutoriale corelate {#related-tutorials} - [Implementarea primului dvs. contract inteligent](/developers/tutorials/deploying-your-first-smart-contract/) _– O introducere despre implementarea primului dvs. contract inteligent într-o rețea de testare Ethereum._ diff --git a/public/content/translations/ro/developers/docs/smart-contracts/security/index.md b/public/content/translations/ro/developers/docs/smart-contracts/security/index.md index bbc500a0537..6a9c33b8ef7 100644 --- a/public/content/translations/ro/developers/docs/smart-contracts/security/index.md +++ b/public/content/translations/ro/developers/docs/smart-contracts/security/index.md @@ -29,7 +29,7 @@ Cerințe minime: - Toate codurile să fie stocate într-un sistem de control al versiunii, cum ar fi Git - Toate modificările de cod să fie efectuate prin Pull Request-uri - Toate Solicitările Pull să aibă cel puțin un examinator. _Dacă aveţi un proiect solo, gândiţi-vă să găsiţi un alt autor solo și negociaţi cu el recenzii de coduri!_ -- Să existe o singură comandă care să compileze, să implementeze și să rulează o suită de teste cu codul dvs. utilizând un mediu Ethereum de dezvoltare (vedeţi: Truffle) +- Să existe o singură comandă care să compileze, să implementeze și să rulează o suită de teste cu codul dvs. utilizând un mediu Ethereum de dezvoltare - Să rulaţi codul prin instrumente de analiză a codului de bază, cum ar fi Mythril și Slither, în mod ideal înainte ca fiecare Pull Request să fie acceptat, comparând diferențele rezultatelor - Solidity să nu emită NICIUN avertisment al compilatorului - Codul dvs. să fie bine documentat diff --git a/public/content/translations/ro/developers/docs/smart-contracts/testing/index.md b/public/content/translations/ro/developers/docs/smart-contracts/testing/index.md index 2097c4979cb..3e4cdc7c09e 100644 --- a/public/content/translations/ro/developers/docs/smart-contracts/testing/index.md +++ b/public/content/translations/ro/developers/docs/smart-contracts/testing/index.md @@ -39,13 +39,11 @@ incomplete: true ## Tutoriale corelate {#related-tutorials} -- [Configurare de integrare continuă cu Solidity și Truffle](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) _– Cum se configurează Travis sau Circle CI pentru testare Truffle împreună cu plugin-uri utile._ - [Prezentare generală a produselor de testare](/developers/tutorials/guide-to-smart-contract-security-tools/) _– O prezentare generală și o comparație a diferitelor produse de testare._ - [Cum se folosește Echidna pentru a testa contractele inteligente](/developers/tutorials/how-to-use-echidna-to-test-smart-contracts/) - [Cum se folosește Manticore pentru a depista bug-uri în contractele inteligente](/developers/tutorials/how-to-use-manticore-to-find-smart-contract-bugs/) - [Cum se folosește Slither pentru a depista bug-uri în contractele inteligente](/developers/tutorials/how-to-use-slither-to-find-smart-contract-bugs/) - [Cum să simulaţi contracte Solidity pentru testare](/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -- [Cum să migraţi de la Testele Truffle la mediul de testare OpenZeppelin](https://docs.openzeppelin.com/test-environment/0.1/migrating-from-truffle) - [Cum să testaţi contractele după ce acestea au fost implementate într-o rețea](https://fulldecent.blogspot.com/2019/04/testing-deployed-ethereum-contracts.html) ## Referințe suplimentare {#further-reading} diff --git a/public/content/translations/ro/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/ro/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index 74f6726249c..00000000000 --- a/public/content/translations/ro/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Creați și implementați o aplicație DeFi -description: Depuneți tokenuri ERC20 în contractul inteligent „FarmToken” și emiteţi tokenuri „Farm Token” -author: "strykerin" -tags: - - "solidity" - - "defi" - - "web3.js" - - "truffle" - - "ganache" - - "contracte inteligente" -skill: intermediate -lang: ro -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -În acest tutorial vom construi o aplicație DeFi cu Solidity în care utilizatorii pot depune un token ERC20 în contractul inteligent „FarmToken”, iar acesta va emite și va transfera tokenuri „Farm Token” către utilizatori. Utilizatorii își pot retrage ulterior tokenurile ERC20 prin arderea de tokenuri„Farm Token” de pe contractul inteligent „FarmToken”, iar tokenurile ERC20 le vor fi transferate înapoi. - -## Instalați Truffle și Ganache {#install-truffle-and-ganache} - -Dacă aceasta este prima dată când scrieți un contract inteligent, va trebui să vă configurați mediul. Vom folosi două instrumente: [Truffle](https://www.trufflesuite.com/) și [Ganache](https://www.trufflesuite.com/ganache). - -Truffle este un mediu de dezvoltare și un framework de testare pentru dezvoltarea de contracte inteligente pentru Ethereum. Cu Truffle este ușor să construiți și să implementați contracte inteligente în blockchain. Ganache ne permite să creăm un blockchain Ethereum local pentru a testa contractele inteligente. Acesta simulează funcționalitățile rețelei reale, iar primele 10 conturi sunt finanțate cu 100 de ether de test, făcând astfel ca implementarea și testarea contractelor inteligente să fie gratuită și simplă. Ganache este disponibil ca aplicație pentru desktop și ca instrument de linie de comandă. Pentru acest articol vom folosi aplicația pentru desktop UI. - -![Aplicația pentru desktop Ganache UI](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Aplicația pentru desktop Ganache UI_ - -Pentru a crea proiectul, executați următoarele comenzi - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Acestea vor crea un proiect gol pentru dezvoltarea și implementarea contractelor noastre inteligente. Structura proiectului creat este următoarea: - -- `contracts`: Dosar pentru contractele inteligente solidity - -- `migrations`: Dosar pentru scripturile de implementare - -- `test`: Dosar pentru testarea contractelor noastre inteligente - -- `truffle-config.js`: Fișier de configurare Truffle - -## Creați tokenul ERC20 {#create-the-erc20-token} - -Mai întâi trebuie să creăm tokenul ERC20 pe care îl vom folosi pentru a miza în contractul inteligent. Pentru a ne crea tokenul fungibil, va trebui mai întâi să instalăm biblioteca OpenZeppelin. Această bibliotecă include implementări ale unor standarde precum ERC20 și ERC721. Pentru a o instala, executați comanda: - -```bash -npm install @openzeppelin/contracts -``` - -Utilizând biblioteca OpenZeppelin, ne putem crea tokenul ERC20 scriind în `contracts/MyToken.sol` cu următorul cod solidity: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -În codul de mai sus, pe: - -- Linia 3: Importăm contractul ERC20.sol din openzeppelin care conține implementarea acestui standard de token. - -- Linia 5: Moștenim din contractul ERC20.sol. - -- Linia 6: Apelăm constructorul ERC20.sol și trecem parametrii „nume” și „simbol” ca fiind `”MyToken”` și, respectiv, `”MTKN”`. - -- Linia 7: Vom emite și transfera 1 milion de tokenuri pentru contul care implementează contractul inteligent (folosim cele 18 zecimale implicite pentru tokenul ERC20, ceea ce înseamnă că, dacă vrem să emitem 1 token, îl vom reprezenta ca 10000000000000000000000, 1 cu 18 zerouri). - -Putem vedea mai jos implementarea constructorului ERC20.sol, în care câmpul `_decimals` este setat la 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## Compilați tokenul ERC20 {#compile-the-erc20-token} - -Pentru a ne compila contractul inteligent, trebuie mai întâi să verificăm versiunea compilatorului Solidity. Puteți verifica aceasta executând comanda: - -```bash -truffle version -``` - -Versiunea implicită este `Solidity v0.5.16`. Deoarece tokenul nostru este scris folosind versiunea solidity `0.6.2`, dacă executăm comanda de compilare a contractelor noastre, vom primi o eroare de compilare. Pentru a specifica ce versiune de compilator solidity să folosiți, accesați fișierul `truffle-config.js` și setați versiunea de compilator dorită, așa cum se arată mai jos: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Acum ne putem compila contractul inteligent prin rularea următoarei comenzi: - -```bash -truffle compile -``` - -## Implementați tokenul ERC20 {#deploy-erc20-token} - -Abia acum, după compilare, ne putem implementa tokenul. - -În folderul `migration`s, creați un fișier numit `2_deploy_Tokens.js`. Acest fișier este locul în care ne vom implementa atât tokenul ERC20, cât și contractul inteligent „FarmToken”. Codul de mai jos este utilizat pentru a implementa contractul MyToken.sol: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Deschideți Ganache și selectați opțiunea „Quickstart” („Pornire rapidă”) pentru a porni un blockchain Ethereum local. Pentru a ne implementa contractul, executați: - -```bash -truffle migrate -``` - -Adresa utilizată pentru implementarea contractelor noastre este prima din lista de adrese pe care ne-o arată Ganache. Pentru a verifica aceasta, putem să deschidem aplicația Ganache pentru desktop și să verificăm că soldul de ether pentru primul cont s-a micșorat din cauza costului etherului necesar pentru implementarea contractelor noastre inteligente: - -![Aplicația Ganache pentru desktop](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Aplicația Ganache pentru desktop_ - -Pentru a verifica dacă 1 milion de tokenuri „MyToken” au fost trimise la adresa de implementare, putem folosi Consola Truffle pentru a interacționa cu contractul nostru inteligent implementat. - -> [Truffle Console este o consolă interactivă de bază care se conectează la orice client Ethereum.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Pentru a interacționa cu contractul nostru inteligent, rulați următoarea comandă: - -```bash -truffle console -``` - -Acum putem scrie următoarele comenzi în terminal: - -- Obținerea contractului inteligent: `myToken = await MyToken.deployed()` - -- Obținerea matricii de conturi din Ganache: `accounts = await web3.eth.getAccounts()` - -- Obținerea soldului pentru primul cont: `balance = await myToken.balanceOf(accounts[0])` - -- Formatați soldul din 18 zecimale: `web3.utils.fromWei(balance.toString())` - -Executând comenzile de mai sus, vom vedea că prima adresă are de fapt 1 milion de tokenuri „MyTokens”: - -![Prima adresă are 1000000 MyTokens](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_Prima adresă are 1000000 de tokenuri „MyTokens”_ - -## Creați contractul inteligent „FarmToken” {#create-farmtoken-smart-contract} - -Contractul inteligent „FarmToken” va avea 3 funcții: - -- `balance()`: Obțineţi soldul de tokenuri „MyToken” pe contractul inteligent „FarmToken”. - -- `deposit(uint256 _amount)`: Transferaţi tokenurile „MyToken” în numele utilizatorului către contractul inteligent „FarmToken”, apoi emiteţi și transferaţi tokenurile „FarmToken” către utilizator. - -- `withdraw(uint256 _amount)`: Ardeţi tokenurile „FarmToken” ale utilizatorului, apoi transferaţi tokenurile „MyToken” la adresa utilizatorului. - -Să examinăm constructorul contractului inteligent "FarmToken": - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- Liniile 3-6: Importăm următoarele contracte din openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol și ERC20.sol. - -- Linia 8: „FarmToken” va moșteni din contractul ERC20. - -- Liniile 14-19: Constructorul „FarmToken” va primi ca parametru adresa contractului „MyToken” și vom atribui contractul său variabilei noastre publice numite `token`. - -Haideți să implementăm funcția `balance()`. Acesta nu va primi niciun parametru și va returna soldul de tokenuri „MyToken” pe acest contract inteligent. Este implementat după cum se arată mai jos: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -În ce privește funcția `depozit(uint256 _amount)`, aceasta va primi ca parametru suma pe care utilizatorul dorește să o depună, apoi va emite și va transfera tokenuri „FarmTokens” către utilizator: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -În ce privește funcția `withdraw(uint256 _amount)`, vom primi ca parametru suma de tokenuri „FarmTokens” pe care utilizatorul dorește să le ardă și apoi vom transfera aceeași sumă de tokenuri „MyTokens” înapoi către utilizator: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -În continuare ne vom implementa contractul inteligent. Pentru aceasta, ne vom întoarce la fișierul `2_deploy_Tokens.js` și vom adăuga noul contract care urmează să fie implementat: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -De reținut că, la implementarea contractului inteligent „FarmToken”, trecem ca parametru adresa contractului MyToken implementat. - -Iar acum rulați `truffle compile` și `truffle migrate` pentru a ne implementa contractele. - -Acum să ne testăm contractul inteligent. Pentru aceasta, în loc să folosim `truffle console` ca să interacționăm cu contractul nostru inteligent, vom crea un script pentru a automatiza acest proces. Creați un dosar numit `scripts` și adăugați următorul fișier `getMyTokenBalance.js`. Acesta va verifica soldul de tokenuri „MyTokens” din contractul inteligent "FarmToken": - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Pentru a executa acest script, executați comanda „cli” de mai jos: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -Vom obține rezultatul preconizat, care este 0. Atunci când primiți o eroare care precizează că implementarea contractului dvs. inteligent „FarmToken” nu s-a efectuat încă, înseamnă că rețeaua Truffle nu a primit cea mai recentă versiune a codului contractului dvs. În acest acaz, închideți Ganache, reporniți-l și nu uitați să rulați `truffle migrate`. - -Mai departe vom miza tokenurile „MyToken" pe contractul inteligent. Pentru că funcția `depozit(uint256 _amount)` apelează funcția `safeTransferFrom` din ERC20, utilizatorul trebuie întâi să autorizeze contractul inteligent să transfere tokenurile „MyToken” în numele său. De aceea, în scriptul de mai jos, vom autoriza întâi acest pas și apoi vom apela funcția: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Pentru a rula acest script, introduceţi comanda:`truffle exec .\scripts\transferMyTokenToFarmToken.js`. Veți vedea pe consolă: - -![rezultatul comenzii „transferMyTokenToFarmToken.js”](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_rezultatul comenzii „transferMyTokenToFarmToken.js”_ - -După cum se vede, am reuşit să depunem tokenuri "MyTokens" în contractul inteligent "FarmToken", deoarece acest cont are acum tokenuri "FarmTokens". - -Pentru a retrage: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Pentru a rula scriptul, introduceţi comanda: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. După cum vedem din rezultatul de mai jos, am recuperat cu succes tokenurile „MyTokens” și am ars tokenurile „FarmTokens”: - -![rezultatul comenzii „withdrawMyTokenFromTokenFarm.js”](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_rezultatul comenzii „withdrawMyTokenFromTokenFarm.js”_ - -## Referințe {#references} - -[Contracte - Documente OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/) - -[Instrumente simpatice pentru contractele inteligente | Suita Truffle](https://www.trufflesuite.com/) - -[Ganache | Suita Truffle](https://www.trufflesuite.com/ganache) - -[Ce este DeFi? Un ghid pentru începători (actualizat în 2021) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - Clasamentul finanțelor descentralizate la DeFi Llama](https://defillama.com/) diff --git a/public/content/translations/ro/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/ro/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index 7b7dec6cb67..718ec210a72 100644 --- a/public/content/translations/ro/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/ro/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "contracte inteligente" - "stocare" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Această limită a fost introdusă pentru a preveni atacurile prin refuzul-servi Inițial aceasta era o problemă mai puțin serioasă, pentru că o limită naturală a mărimii contractului este limita de gaz pe bloc. În mod evident, un contract trebuie să fie implementat în cadrul unei tranzacții care conține tot bytecode-ul contractului. Dar dacă includeți doar acea tranzacție într-un bloc, puteți utiliza tot gazul, care însă nu este infinit. Problema în acest caz este însă că limita de gaz pe bloc se modifică în timp și este teoretic nemărginită. În momentul introducerii EIP-170, limita de gaz pe bloc era de numai 4,7 milioane. Acum limita de gaz pe bloc tocmai [a crescut din nou](https://etherscan.io/chart/gaslimit) luna trecută la 11,9 milioane. -## Cum să contracarăm {#taking-on-the-fight} - -Din nefericire, nu există o modalitate ușoară de a obține dimensiunea bytecode-ului contractelor dvs. Dacă utilizați Truffle, un instrument excelent pentru a vă ajuta în acest sens este plugin-ul [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size). - -1. `npm install truffle-contract-size` -2. Adăugați plugin-ul la _truffle-config.js_: `plugins: ["truffle-contract-size"]` -3. Rulați `truffle run contract-size` - -Aceasta vă va ajuta să înțelegeți cum afectează modificările dvs. dimensiunea totală a contractului. - În cele ce urmează vom examina câteva metode în ordinea impactului lor potențial. Considerați-le din perspectiva pierderii în greutate. Strategia cea mai bună pentru ca cineva să-și atingă greutatea propusă (în cazul nostru 24kB) este să se axeze întâi pe metodele cu impact mare. În cele mai multe cazuri va fi suficient să vă modificați regimul alimentar ca să vă atingeți scopul, dar uneori mai este necesar și altceva. Apoi ați mai putea face niște exerciții fizice (impact mediu) sau chiar lua suplimente (impact mic). ## Impact mare {#big-impact} diff --git a/public/content/translations/ro/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/ro/developers/tutorials/secure-development-workflow/index.md index 026a2592c59..93b7ae3c524 100644 --- a/public/content/translations/ro/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/ro/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Gândiți-vă să includeți funcționalități speciale contractul dvs: - Pot fi actualizate contractele dvs.? Revizuiți-vă codul posibilității de actualizare contra deficiențelor cu [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) sau [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/). Am documentat 17 moduri în care actualizările pot merge prost. - Este în intenția contractelor dvs. să se conformeze cu ERC-urile? Verificați-le cu [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance). Acest instrument identifică instantaneu abaterile de la șase specificații comune. -- Aveți teste de unitate în Truffle? Îmbogățiți-le cu [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation). Acesta generează automat o suită robustă de proprietăți de securitate pentru funcționalitățile ERC20 pe baza codului dvs. specific. - Puteți să integrați tokenuri de la terți? Revizuiți [lista noastră de verificare pentru integrarea cu tokenurile](/developers/tutorials/token-integration-checklist/) înainte de a vă baza pe contracte externe. Inspectați vizual funcționalitățile de securitate de importață majoră ale codului dvs: diff --git a/public/content/translations/ro/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/ro/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 748dbcb7e46..00000000000 --- a/public/content/translations/ro/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: "Configurarea integrării continue cu Solidity și Truffle" -description: Cum să configurați „Travis” sau „Circle CI” pentru testarea „Truffle” și plugin-uri utile -author: Markus Waas -lang: ro -tags: - - "solidity" - - "contracte inteligente" - - "testare" - - "truffle" - - "integrare continuă" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -Integrarea continuă (CI) cu Truffle este excelentă pentru dezvoltare, odată ce aveți implementat un set de bază de teste. Vă permite să executați teste foarte lungi, să vă asigurați că toate testele reușesc înainte de a fuziona un [pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) și să țineți evidența diferitelor statistici folosind instrumente suplimentare. - -Vom folosi [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) pentru a ne configura integrarea continuă. Puteți să alegeți fie Travis CI, fie Circle CI. - -## Configurarea Travis CI {#setting-up-travis-ci} - -Adăugarea [Travis CI](https://travis-ci.org/) este simplă. Va trebui doar să adăugați un fișier de configurare `.travis.yml` în directorul rădăcină al proiectului: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Ne vom limita pentru moment la lucrurile simple și vom executa doar scriptul de testare care execută testele unitare Truffle. Dar avem o problemă, și anume că pe mașina Travis CI nu va fi disponibil un blockchain. Soluția cea mai simplă este de a `npm instala ganache-cli` și de a-l executa pur și simplu înainte de test. Puteți face acest lucru adăugând un script „bash” cu linia npx `ganache-cli > /dev/null` înainte de apelarea `npx truffle test`. Iată [exemplul complet de script bash](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Configurarea Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) necesită un fișier mai lung de configurare. Comanda suplimentară [`npm ci`](https://docs.npmjs.com/cli/ci.html) este efectuată automat în Travis. Aceasta instalează dependențele mai rapid și mai securizat decât o face `npm install`. Vom folosi din nou același script din versiunea Travis pentru a executa ganache-cli înainte de teste. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Adăugarea plugin-ului „eth-gas-reporter” {#adding-the-eth-gas-reporter-plugin} - -Plugin-ul „eth-gas-reporter” este foarte util pentru a ține evidența costurilor de gaz ale funcțiilor contractului dvs. inteligent. Dacă aveți acest plugin în CI, se va dovedi și mai util pentru a afișa „diff-urile” atunci când adăugați „pull request-uri". - -### Etapa 1: Instalarea plugin-ului „eth-gas-reporter” și „codechecks” {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -$ npm install --save-dev eth-gas-reporter -$ npm install --save-dev @codechecks/client -``` - -### Etapa 2: Adăugați plugin-ul la setările „mocha” în interiorul fișierului „truffle-config.js” {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Iată opțiunile](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### Etapa 3: Adăugați „codechecks.yml” în directorul rădăcină al proiectului dvs. {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### Etapa 4: Executați „codechecks” după comanda „test” {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### Etapa 5: Creați un cont „Codechecks” {#step-5-create-a-codechecks-account} - -- Creați un cont cu [Codechecks](http://codechecks.io/). -- Add the GitHub repo to it. -- Copiați secretul și adăugați `CC_SECRET=COPIED SECRET` la CI-ul dvs. (uitați aici pentru [Travis](https://docs.travis-ci.com/user/environment-variables/) și aici pentru [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project)). -- Acum continuați creând un „pull request”. - -Asta e tot. Iar acum veți găsi un raport atractiv despre schimbările costurilor de gaz ale „pull request-ului” dvs. - -![Exemple de rapoarte de gaz](./gas-reports.png) - -## Adăugarea plugin-ului „solidity-coverage” {#adding-the-solidity-coverage-plugin} - -Cu plugin-ul „solidity-coverage” puteți să verificați la câte dintre căile de cod se referă testele dumneavoastră. Dacă îl adăugați la CI, va fi foarte comod de utilizat, odată configurat. - -### Etapa 1: Creați un proiect „metacoin” și instalați instrumentele „coverage” {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle -npm install --save-dev coveralls -npm install --save-dev solidity-coverage -``` - -### Etapa 2: Adăugați „solidity-coverage” la matricea plugin-urilor din truffle-config.js {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### Etapa 3: Adăugați comenzile „coverage” la fișierul „.travis.yml” sau la „config.yml" al Circle CI {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Plugin-ul „coverage” al Solidity își pornește propriul „ganache-cli”, de aceea nu trebuie să ne facem griji în această privință. Totuși, nu înlocuiți comanda de testare obișnuită, întrucât „coverage” al „ganache-cli” funcționează diferit și nu înlocuiește deci rularea testelor unitare obișnuite. - -### Etapa 4: Adăugați un „repository” la „coveralls” {#step-4-add-repository-to-coveralls} - -- Creați un cont cu [Coveralls](https://coveralls.io/). -- Add the GitHub repo to it. -- Acum continuați creând un „pull request”. - -![Exemplu de „coverall”](./coverall.png) - -## Sugestii suplimentare {#further-ideas} - -- [MythX](https://mythx.io/): Cu „MythX” puteți analiza securitatea contractului dvs. inteligent în mod automat. Prin urmare, este foarte logic să îl [adăugați la CI-ul dvs](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/). -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): Good code can be enforced to some degree with linting tools. [Eslint](https://eslint.org/) works great for JavaScript, is [easy to setup](https://eslint.org/docs/user-guide/getting-started), while [Solhint](https://protofire.github.io/solhint/) can be used for Solidity. -- Teste lungi: Uneori este necesar să adăugați teste extreme, de exemplu, testarea unui contract cu sute de utilizatori. Aceasta durează foarte mult timp. În loc să le executați la fiecare testare, adăugați-le la CI. - -Și asta e tot. Integrarea continuă este o strategie foarte utilă pentru dezvoltările dvs. Puteți vedea un exemplu complet la [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example). Doar aveți grijă să eliminați „Circle-CI” sau „Travis”, unul este suficient! diff --git a/public/content/translations/ro/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/ro/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index d2b12963a4b..119f1150a44 100644 --- a/public/content/translations/ro/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/ro/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Manifestul este fișierul nostru de configurare și definește: - alte lucruri de ascultat, cum ar fi apeluri de funcții sau blocuri - the mapping functions being called (see `mapping.ts` below) -Aici puteți defini mai multe contracte și manipulatoare. O configurare tipică ar fi cu un folder subgraph în proiectul Truffle/Hardhat, cu propriul depozitar. Puteți apoi face referire la ABI cu ușurință. +Aici puteți defini mai multe contracte și manipulatoare. O configurare tipică ar fi cu un folder subgraph în proiectul Hardhat, cu propriul depozitar. Puteți apoi face referire la ABI cu ușurință. Din comoditate, ați dori probabil să utilizați un instrument șablon, cum ar fi „mustache”. Then you create a `subgraph.template.yaml` and insert the addresses based on the latest deployments. Pentru a vedea un exemplu de configurare mai avansată, puteți consulta, de exemplu, [depozitarul subgraph-ului Aave](https://github.com/aave/aave-protocol/tree/master/thegraph). diff --git a/public/content/translations/ro/enterprise/index.md b/public/content/translations/ro/enterprise/index.md index a9c4da1bd23..3489c9b0ddb 100644 --- a/public/content/translations/ro/enterprise/index.md +++ b/public/content/translations/ro/enterprise/index.md @@ -67,7 +67,6 @@ Diverse organizații au depus eforturi comune pentru a creşte uşurinţa de uti - [Ernst & Young's „Nightfall”](https://github.com/EYBlockchain/nightfall) _un set de instrumente pentru tranzacții private_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _o aplicație de semnare a tranzacțiilor de utilizat cu un furnizor web3_ - [Tenderly](https://tenderly.co/) _o platformă de date care oferă analize, alerte și monitorizare în timp real, ce acceptă rețelele private._ -- [Truffle Suite](https://trufflesuite.com) _ suită de blockchain-uri pentru dezvoltare (Truffle, Ganache, Drizzle)_ ### Soluții de scalabilitate {#scalability-solutions} diff --git a/public/content/translations/ru/community/support/index.md b/public/content/translations/ru/community/support/index.md index 127d8c64f94..23e2c743d5e 100644 --- a/public/content/translations/ru/community/support/index.md +++ b/public/content/translations/ru/community/support/index.md @@ -73,7 +73,6 @@ lang: ru - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/se/enterprise/index.md b/public/content/translations/se/enterprise/index.md index af3613ce1f8..55db98169ec 100644 --- a/public/content/translations/se/enterprise/index.md +++ b/public/content/translations/se/enterprise/index.md @@ -74,7 +74,6 @@ Offentliga och privata Ethereum-nätverk kan behöva specifika funktioner som kr - [Alethio](https://explorer.aleth.io/) _Ethereum Data Analytics Platform_ - [Treum](https://treum.io/) _ger transparens, spårbarhet och handelsförmåga till försörjningskedjor, med hjälp av blockchain-teknik_ -- [Truffle Suite](https://trufflesuite.com) _en utvecklingssvit för blockchain (Truffle, Ganache, Drizzle)_ ## Enterprise utvecklargemenskap {#enterprise-developer-community} diff --git a/public/content/translations/sk/enterprise/index.md b/public/content/translations/sk/enterprise/index.md index 8d18a83d5d8..0a7cf2e426f 100644 --- a/public/content/translations/sk/enterprise/index.md +++ b/public/content/translations/sk/enterprise/index.md @@ -74,7 +74,6 @@ Verejné a súkromné ​​siete Etherea môžu potrebovať špecifické vlastn - [Alethio](https://explorer.aleth.io/) _platforma na analýzu údajov Etherea_ - [Treum](https://treum.io/) _prináša transparentnosť, sledovateľnosť a obchodovateľnosť pre dodávateľské reťazce pomocou technológie blockchain_ -- [Truffle Suite](https://trufflesuite.com) _balík vývojárskych nástrojov pre blockchain (Truffle, Ganache, Drizzle)_ ## Komunita vývojárov pre podniky {#enterprise-developer-community} diff --git a/public/content/translations/sw/community/support/index.md b/public/content/translations/sw/community/support/index.md index 46499da5bfc..bd5a123f0f2 100644 --- a/public/content/translations/sw/community/support/index.md +++ b/public/content/translations/sw/community/support/index.md @@ -55,7 +55,6 @@ Hii ni baadhi ya mifano maalum: - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) ## Endesha nodi {#node-support} diff --git a/public/content/translations/tr/community/support/index.md b/public/content/translations/tr/community/support/index.md index 9bdbafbf904..bf07a0ec0bc 100644 --- a/public/content/translations/tr/community/support/index.md +++ b/public/content/translations/tr/community/support/index.md @@ -57,7 +57,6 @@ Sorunuz belirli bir araç, proje veya kütüphane ile mi ilgili? Çoğu projede - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/tr/developers/docs/bridges/index.md b/public/content/translations/tr/developers/docs/bridges/index.md index d2a2c2f6a4f..75380d0bca9 100644 --- a/public/content/translations/tr/developers/docs/bridges/index.md +++ b/public/content/translations/tr/developers/docs/bridges/index.md @@ -103,7 +103,7 @@ Bir merkeziyetsiz uygulama, bir köprü veya birleştirici entegrasyonu yolunu s ### Bir merkeziyetsiz uygulamayı birden fazla zincire dağıtma {#deploying-a-dapp-on-multiple-chains} -Geliştiriciler, bir merkeziyetsiz uygulamayı birden fazla zincire dağıtmak için [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Truffle](https://trufflesuite.com/), [Moralis](https://moralis.io/) gibi geliştirme platformlarından yararlanabilir. Genellikle bu platformlar, merkeziyetsiz uygulamaların zincirler arası işlem yapmasını sağlayabilecek birleştirilebilir eklentilere sahiptir. Örneğin, geliştiriciler [hardhat-dağıtım eklentisi](https://github.com/wighawag/hardhat-deploy) tarafından sunulan belirleyici dağıtım vekilini kullanabilir. +Geliştiriciler, bir merkeziyetsiz uygulamayı birden fazla zincire dağıtmak için [Alchemy](https://www.alchemy.com/), [Hardhat](https://hardhat.org/), [Moralis](https://moralis.io/) gibi geliştirme platformlarından yararlanabilir. Genellikle bu platformlar, merkeziyetsiz uygulamaların zincirler arası işlem yapmasını sağlayabilecek birleştirilebilir eklentilere sahiptir. Örneğin, geliştiriciler [hardhat-dağıtım eklentisi](https://github.com/wighawag/hardhat-deploy) tarafından sunulan belirleyici dağıtım vekilini kullanabilir. #### Örnekler: diff --git a/public/content/translations/tr/developers/docs/development-networks/index.md b/public/content/translations/tr/developers/docs/development-networks/index.md index bb7ddf82dd7..d879ebc7b84 100644 --- a/public/content/translations/tr/developers/docs/development-networks/index.md +++ b/public/content/translations/tr/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ Siz [bir düğüm](/developers/docs/nodes-and-clients/#running-your-own-node) _ **Not**: Çoğu [geliştirme çerçevesi](/developers/docs/frameworks/) yerleşik bir geliştirme ağı içerir. [Yerel geliştirme ortamınızı kurmak](/developers/local-environment/) için bir çerçeve ile başlamanızı öneririz. -### Ganache {#ganache} - -Test yapmak, komutları yürütmek ve zincirin nasıl çalıştığını kontrol ederken durumu incelemek için kullanabileceğiniz kişisel bir Ethereum blok zincirini hızla çalıştırın. - -Ganache, hem bir masaüstü uygulaması (Ganache UI) hem de bir komut satırı aracı (`ganache-cli`) sağlar. Truffle araç takımının bir parçasıdır. - -- [Web sitesi](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [Belgeler](https://www.trufflesuite.com/docs/ganache/overview) - ### Hardhat Ağı {#hardhat-network} Geliştirme için tasarlanmış yerel bir Ethereum ağı. Sözleşmelerinizi dağıtmanıza, testlerinizi çalıştırmanıza ve kodunuzda hata ayıklamanıza olanak tanır. diff --git a/public/content/translations/tr/developers/docs/frameworks/index.md b/public/content/translations/tr/developers/docs/frameworks/index.md index 347cbe89bd7..9a7c71389cf 100644 --- a/public/content/translations/tr/developers/docs/frameworks/index.md +++ b/public/content/translations/tr/developers/docs/frameworks/index.md @@ -22,11 +22,6 @@ Tam teşekküllü bir dapp inşa etmek teknolojinin farklı parçalarını gerek ## Mevcut çerçeveler {#available-frameworks} -**Truffle -** **_Bir geliştirme ortamı, test çerçevesi, yapı hattı ve diğer araçlar._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) - **Hardhat -** **_Profesyoneller için Ethereum geliştirme platformu._** - [hardhat.org](https://hardhat.org) diff --git a/public/content/translations/tr/developers/docs/programming-languages/dart/index.md b/public/content/translations/tr/developers/docs/programming-languages/dart/index.md index d1d32393c99..30f2311c19a 100644 --- a/public/content/translations/tr/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/tr/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## Öğreticiler {#tutorials} - [Flutter ve Blok Zinciri – Hello World Dapp](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/) başlamanız için tüm adımlarda size yol gösterir: - 1. [Truffle geliştirme paketini](https://www.trufflesuite.com/) yükleme - 2. [Solidity](https://soliditylang.org/)'de akıllı sözleşme yazma - 3. Dart'ta bir kullanıcı arayüzü yazma + 1. [Solidity](https://soliditylang.org/)'de akıllı sözleşme yazma + 2. Dart'ta bir kullanıcı arayüzü yazma - Temel bilgileri hali hazırda biliyorsanız, [daha kısa olan Flutter ile Mobil bir dapp inşa etmek](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a) daha iyi olabilir - Video izleyerek öğrenmeyi tercih ediyorsanız yaklaşık bir saat uzunluğundaki [İlk Blok Zinciri Flutter Uygulamanızı Oluşturun](https://www.youtube.com/watch?v=3Eeh3pJ6PeA) videosunu izleyebilirsiniz - Sabırsızsanız, yaklaşık yirmi dakika uzunluğundaki [Flutter ve Dart ile Ethereum Üzerinde bir Blok Zinciri Merkeziyetsiz Uygulaması Oluşturma](https://www.youtube.com/watch?v=jaMFEOCq_1s) videosunu tercih edebilirsiniz diff --git a/public/content/translations/tr/developers/docs/programming-languages/golang/index.md b/public/content/translations/tr/developers/docs/programming-languages/golang/index.md index 7785eb6b14e..19c57f799a8 100644 --- a/public/content/translations/tr/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/tr/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ Başlamadan önce temel bilgilere mi ihtiyacınız var? [ethereum.org/learn](/le ## Başlangıç Seviyesi Makaleler ve Kitaplar {#beginner-articles-and-books} -- [Ethereum İstemcinizi Seçmek](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Geth ile Başlarken](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [Ethereum'a bağlanmak için Golang kullanmak](https://www.youtube.com/watch?v=-7uChuO_VzM) - [Golang Kullanarak Ethereum Akıllı Sözleşmeleri Dağıtmak](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/tr/developers/docs/programming-languages/rust/index.md b/public/content/translations/tr/developers/docs/programming-languages/rust/index.md index 97b212cfb01..29bced93611 100644 --- a/public/content/translations/tr/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/tr/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ Başlamadan önce temel bilgilere mi ihtiyacınız var? [ethereum.org/learn](/le ## Başlangıç seviyesi makaleler {#beginner-articles} -- [Ethereum İstemcisi Seçimi](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [The Rust Ethereum Client](https://openethereum.github.io/) \* **OpenEthereum'un [kullanımdan kaldırıldığını](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd) ve artık bakıma tabi olmadığını unutmayın.** Dikkatli kullanın ve tercihen başka bir istemci uygulamasına geçin. - [Rust Kullanarak Ethereum'a İşlem Göndermek](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [Parity Ethereum İstemcisiyle Akıllı Sözleşmelere Giriş](https://wiki.parity.io/Smart-Contracts) diff --git a/public/content/translations/tr/developers/docs/smart-contracts/deploying/index.md b/public/content/translations/tr/developers/docs/smart-contracts/deploying/index.md index ff4e0d738f7..048f5b366e9 100644 --- a/public/content/translations/tr/developers/docs/smart-contracts/deploying/index.md +++ b/public/content/translations/tr/developers/docs/smart-contracts/deploying/index.md @@ -27,7 +27,7 @@ Son olarak, sözleşmenizi dağıtmadan önce onu derlemeniz gerekir, bu yüzden ### Bir akıllı sözleşme dağıtmanın aşamaları {#steps-to-deploy} -Belirli aşamalar kullandığınız araçlara göre değişecektir. Örnek olarak, [sözleşmelerinizin dağıtımı hakkında Hardhat belgeleri](https://hardhat.org/guides/deploying.html) veya [Ağlar ve uygulama dağıtımı üzerine Truffle belgelerine](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) göz atın. Bu ikisi de dağıtım aşamalarını idare etmek için bir komut dosyası yazımını gerektiren ve akıllı sözleşme geliştirme için en popüler araçlardır. +Belirli aşamalar kullandığınız araçlara göre değişecektir. Örnek olarak, [sözleşmelerinizin dağıtımı hakkında Hardhat belgeleri](https://hardhat.org/guides/deploying.html). Bu ikisi de dağıtım aşamalarını idare etmek için bir komut dosyası yazımını gerektiren ve akıllı sözleşme geliştirme için en popüler araçlardır. Dağıtıldığında, sözleşmeniz diğer [hesaplar](/developers/docs/accounts/) gibi bir Ethereum adresine sahip olacaktır. @@ -51,12 +51,6 @@ Dağıtıldığında, sözleşmeniz diğer [hesaplar](/developers/docs/accounts/ - [GitHub](https://github.com/nomiclabs/hardhat) - [Discord](https://discord.com/invite/TETZs2KK4k) -**Truffle -** **_Bir geliştirme ortamı, test çerçevesi, yapı hattı ve diğer araçlar._** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [Ağlar ve uygulama geliştirme üzerine belgeler](https://www.trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment) -- [GitHub](https://github.com/trufflesuite/truffle) - **thirdweb - _Tek bir komut kullanarak herhangi bir sözleşmeyi Ethereum Sanal Makinesi uyumlu herhangi bir zincire kolayca dağıtın_** - [Dokümanlar](https://portal.thirdweb.com/deploy/) diff --git a/public/content/translations/tr/developers/docs/smart-contracts/testing/index.md b/public/content/translations/tr/developers/docs/smart-contracts/testing/index.md index 256b04016b3..7473f629c4f 100644 --- a/public/content/translations/tr/developers/docs/smart-contracts/testing/index.md +++ b/public/content/translations/tr/developers/docs/smart-contracts/testing/index.md @@ -138,7 +138,6 @@ Akıllı sözleşmeniz için birim testleri çalıştırmada kullanılan araçla Solidity akıllı sözleşmeleri için birim testi çerçeveleri farklı dillerde (çoğunlukla JavaScript, Python ve Rust) sunulur. Farklı test çerçeveleri ile birim testleri çalıştırmaya başlamak hakkında bilgi almak için aşağıdaki rehberlere başvurun: -- **[Truffle ile birim testleri çalıştırma](https://trufflesuite.com/docs/truffle/testing/testing-your-contracts/)** - **[Brownie ile birim testleri çalıştırma](https://eth-brownie.readthedocs.io/en/v1.0.0_a/tests.html)** - **[Foundry ile birim testleri çalıştırma](https://book.getfoundry.sh/forge/writing-tests)** - **[Waffle ile birim testleri çalıştırma](https://ethereum-waffle.readthedocs.io/en/latest/getting-started.html#writing-tests)** @@ -150,7 +149,7 @@ Solidity akıllı sözleşmeleri için birim testi çerçeveleri farklı dillerd Birim testi izole edilmiş sözleşme işlevlerinde hata ayıklarken, entegrasyon testleri bir akıllı sözleşmenin tüm bileşenlerini bir bütün olarak değerlendirir. Entegrasyon testi, sözleşmeler arası çağrılardan veya aynı akıllı sözleşmedeki farklı işlevler arasındaki etkileşimlerden kaynaklanan sorunları tespit edebilir. Örneğin, entegrasyon testleri [kalıtım](https://docs.soliditylang.org/en/v0.8.12/contracts.html#inheritance) ve bağımlılık enjeksiyonu gibi şeylerin doğru çalışıp çalışmadığını kontrol etmeye yardımcı olabilir. -Entegrasyon testi, sözleşmenizin modüler bir mimariyi benimsemesi ya da yürütülmesi sırasında diğer zincir içi sözleşmelerle arayüz oluşturması açısından kullanışlıdır. Entegrasyon testlerini yürütmenin bir yolu, blok zincirini belirli bir yükseklikte ([Ganache](https://trufflesuite.com/docs/ganache/) veya [Hardhat](https://hardhat.org/hardhat-network/docs/guides/forking-other-networks) gibi bir araç kullanarak) [çatallamak](/glossary/#fork) ve sözleşmeniz ile dağıtılmış sözleşmeler arasındaki etkileşimleri simüle etmektir. +Entegrasyon testi, sözleşmenizin modüler bir mimariyi benimsemesi ya da yürütülmesi sırasında diğer zincir içi sözleşmelerle arayüz oluşturması açısından kullanışlıdır. Entegrasyon testlerini yürütmenin bir yolu, blok zincirini belirli bir yükseklikte veya [Hardhat](https://hardhat.org/hardhat-network/docs/guides/forking-other-networks) gibi bir araç kullanarak) [çatallamak](/glossary/#fork) ve sözleşmeniz ile dağıtılmış sözleşmeler arasındaki etkileşimleri simüle etmektir. Çatallanmış blokzincir, ana ağa benzer şekilde davranır ve ilişkili durumları ve bakiyeleri bulunan hesaplara sahiptir. Ancak yalnızca ayrıştırılmış bir yerel geliştirme ortamı olarak işlev görür, yani işlemler için gerçek Ether'e ihtiyacınız olmaz ve yaptığınız değişiklikler gerçek Ethereum ağını etkilemez. @@ -255,8 +254,6 @@ En önemli fark, hata ödül programlarının daha geniş bir geliştirici/hacke - **[OpenZeppelin Test Yardımcıları](https://github.com/OpenZeppelin/openzeppelin-test-helpers)** - _Ethereum akıllı sözleşme testi için sav kütüphanesi. Sözleşmelerinizin beklendiği gibi davrandığından emin olun!_ -- **[Truffle Testleri](https://hardhat.org/hardhat-runner/docs/guides/test-contracts#testing-contracts)** - _Sözleşmelerinizi test etmeyi kolaylaştıran, otomatikleştirilmiş bir test çerçevesi._ - - **[Brownie birim test çerçevesi](https://eth-brownie.readthedocs.io/en/v1.0.0_a/tests.html)** - _Brownie, minimum kodla küçük testler yazmanıza olanak tanıyan, büyük projeler için iyi ölçeklenen ve oldukça genişletilebilir, zengin özelliklere sahip bir test çerçevesi olan Pytest'i kullanır._ - **[Foundry Testleri](https://github.com/foundry-rs/foundry/tree/master/forge)** - _Foundry, basit birim testleri, gaz optimizasyon kontrolleri ve sözleşme bulanıklaştırma gerçekleştirebilen hızlı ve esnek bir Ethereum test çerçevesi olan Forge'u barındırır._ @@ -287,13 +284,11 @@ En önemli fark, hata ödül programlarının daha geniş bir geliştirici/hacke ## İlgili öğreticiler {#related-tutorials} -- [Truffle testleri için Travis veya Circle Continuous Integration (CI) nasıl kurulur?](/developers/tutorials/solidity-and-truffle-continuous-integration-setup/) - [Farklı test ürünlerine genel bakış ve ürünlerin karşılaştırılması](/developers/tutorials/guide-to-smart-contract-security-tools/) \_ - [Akıllı sözleşmeleri test etmek için Echidna nasıl kullanılır](/developers/tutorials/how-to-use-echidna-to-test-smart-contracts/) - [Manticore kullanarak akıllı sözleşme hataları nasıl bulunur?](/developers/tutorials/how-to-use-manticore-to-find-smart-contract-bugs/) - [Akıllı sözleşme hatalarını bulmak için Slither nasıl kullanılır](/developers/tutorials/how-to-use-slither-to-find-smart-contract-bugs/) - [Solidity sözleşmeleri test etmek için nasıl taklit edilir?](/developers/tutorials/how-to-mock-solidity-contracts-for-testing/) -- [Truffle Testlerinden OpenZeppelin Test Ortamı'na nasıl geçiş yapılır?](https://docs.openzeppelin.com/test-environment/0.1/migrating-from-truffle) - [Sözleşmeler ağa dağıtıldıktan sonra nasıl test edilir?](https://fulldecent.blogspot.com/2019/04/testing-deployed-ethereum-contracts.html) ## Daha fazla bilgi {#further-reading} diff --git a/public/content/translations/tr/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/tr/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index a9102740864..00000000000 --- a/public/content/translations/tr/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: Bir DeFi uygulaması oluşturun ve dağıtın -description: ERC20 token'larını akıllı sözleşmeye yatırın ve Farm Token'ları basın -author: "strykerin" -tags: - - "solidity" - - "defi" - - "web3.js" - - "truffle" - - "ganache" - - "akıllı sözleşmeler" -skill: intermediate -lang: tr -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -Bu öğreticide, kullanıcıların akıllı sözleşmeye bir ERC20 token'ı yatırabilecekleri ve Farm Token'larını basıp onlara aktarabilecekleri, Solidity ile bir DeFi Uygulaması oluşturacağız. Kullanıcılar daha sonra Farm Token'larını akıllı sözleşmede yakarak ERC20 token'larını geri çekebilirler ve ERC20 token'ları kendilerine geri aktarılır. - -## Truffle ve Ganache kurun {#install-truffle-and-ganache} - -İlk kez bir akıllı sözleşme yazıyorsanız, ortamınızı ayarlamanız gerekecektir. İki araç kullanacağız: [Truffle](https://www.trufflesuite.com/) ve [Ganache](https://www.trufflesuite.com/ganache). - -Truffle, Ethereum için akıllı sözleşmeler geliştirmek için bir geliştirme ortamı ve test çerçevesidir. Truffle ile akıllı sözleşmeler oluşturmak ve blok zincirine yerleştirmek kolaydır. Ganache, akıllı sözleşmeleri test etmek için yerel bir Ethereum blok zinciri oluşturmamıza izin veriyor. Gerçek ağın özelliklerini simüle eder ve ilk 10 hesap 100 test ether'ı ile finanse edilir, böylece akıllı sözleşme dağıtımını ve testini ücretsiz ve kolay hâle getirir. Ganache, bir masaüstü uygulaması ve bir komut satırı aracı olarak mevcuttur. Bu makale için UI masaüstü uygulamasını kullanacağız. - -![Ganache UI masaüstü uygulaması](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Ganache UI masaüstü uygulaması_ - -Projeyi oluşturmak için aşağıdaki komutları çalıştırın - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -Bu, akıllı sözleşmelerimizin geliştirilmesi ve uygulanması için boş bir proje oluşturacaktır. Oluşturulan proje yapısı aşağıdaki gibidir: - -- `contracts`: Solidity akıllı sözleşmeleri için klasör - -- `migrations`: Dağıtım komut dosyaları için klasör - -- `test`: Akıllı sözleşmelerimizin testi için klasör - -- `truffle-config.js`: Truffle yapılandırma dosyası - -## ERC20 Token'ını Oluşturun {#create-the-erc20-token} - -Öncelikle akıllı sözleşmede stake etmek için kullanacağımız ERC20 token'ımızı oluşturmamız gerekiyor. Değiştirilebilir simgemizi oluşturmak için önce OpenZeppelin kütüphanesini kurmamız gerekecek. Bu kütüphane, ERC20 ve ERC721 gibi standartların uygulamalarını içerir. Onu kurmak için, şu komutu çalıştırın: - -```bash -npm install @openzeppelin/contracts -``` - -OpenZeppelin kütüphanesini kullanarak, aşağıdaki solidity koduyla `contracts/MyToken.sol`'a yazarak ERC20 token'ımızı oluşturabiliriz: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -Yukarıdaki kodda: - -- 3. Satır: openzeppelin'den bu token standardının uygulamasını içeren ERC20.sol sözleşmesini içe aktarıyoruz. - -- 5. Satır: ERC20.sol sözleşmesinden kalıtıma uğruyoruz. - -- Satır 6: ERC20.sol yapıcısını çağırıp ad ve sembol parametrelerini sırasıyla `"MyToken"` ve `"MTKN"` olarak geçiyoruz. - -- 7. Satır: Akıllı sözleşmeyi dağıtan hesap için 1 milyon token basıyor ve aktarıyoruz (ERC20 token'ı için varsayılan 18 ondalık basamağı kullanıyoruz. Bu, 1 token basmak istiyorsak, onu 10000000000000000000, 1'den sonra 18 sıfır, olarak temsil edeceğiniz anlamına gelir). - -`_decimals` alanının 18 olarak ayarlandığı ERC20.sol yapıcı uygulamasını aşağıda görebiliriz: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## ERC20 Token'ını Derleyin {#compile-the-erc20-token} - -Akıllı sözleşmemizi derlemek için önce solidity derleyici versiyonumuzu kontrol etmeliyiz. Bunu şu komutu çalıştırarak kontrol edebilirsiniz: - -```bash -truffle version -``` - -Varsayılan versiyon `Solidity v0.5.16`'dır. Token'ımız `0.6.2` solidity versiyonu kullanılarak yazıldığından, sözleşmelerimizi derlemek için komutu çalıştırırsak bir derleyici hatası alırız. Hangi solidity derleyici sürümünün kullanılacağını belirlemek için `truffle-config.js` dosyasına gidin ve aşağıda görüldüğü gibi istediğiniz derleyici sürümüne ayarlayın: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -Şimdi aşağıdaki komutu çalıştırarak akıllı sözleşmemizi derleyebiliriz: - -```bash -truffle compile -``` - -## ERC20 Token'ını Dağıtın {#deploy-erc20-token} - -Derlemeden sonra artık token'ımızı dağıtabiliriz. - -`migrations` klasöründe, `2_deploy_Tokens.js` isimli bir dosya oluşturun. Bu dosya, hem ERC20 Token'ımızı hem de FarmToken akıllı sözleşmemizi dağıtacağımız yerdir. Aşağıdaki kod, MyToken.sol sözleşmemizi dağıtmak için kullanılır: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -Ganache'yi açın ve yerel bir Ethereum blok zinciri başlatmak için "Quickstart" (Hızlı Başlangıç) seçeneğini seçin. Sözleşmemizi dağıtmak için, şunu çalıştırın: - -```bash -truffle migrate -``` - -Sözleşmelerimizi dağıtmak için kullanılan adres, Ganache'nin bize gösterdiği adresler listesinden ilkidir. Bunu doğrulamak için Ganache masaüstü uygulamasını açabiliriz ve akıllı sözleşmelerimizi dağıtmak için ether maliyeti nedeniyle ilk hesap için ether bakiyesinin düştüğünü doğrulayabiliriz: - -![Ganache masaüstü uygulaması](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Ganache masaüstü uygulaması_ - -Dağıtıcı adresine 1 milyon MyToken token'ının gönderildiğini doğrulamak amacıyla, dağıtılan akıllı sözleşmemizle etkileşim kurmak için Truffle Konsolunu kullanabiliriz. - -> [Truffle Konsolu, tüm Ethereum istemcilerine bağlanan temel bir etkileşimli konsoldur.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -Akıllı sözleşmemizle etkileşim kurmak için aşağıdaki komutu çalıştırın: - -```bash -truffle console -``` - -Artık sıradaki komutları terminale yazabiliriz: - -- Akıllı sözleşmeyi alın: `myToken = await MyToken.deployed()` - -- Ganache'dan hesap dizisini alın: `accounts = await web3.eth.getAccounts()` - -- İlk hesabın bakiyesini alın: `balance = await myToken.balanceOf(accounts[0])` - -- Bakiyeyi 18 ondalık basamak olarak biçimlendirin: `web3.utils.fromWei(balance.toString())` - -Yukarıdaki komutları çalıştırarak, ilk adreste gerçekten de 1 milyon MyTokens olduğunu göreceğiz: - -![İlk adreste 1000000 MyToken var](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_İlk adreste 1000000 MyToken var_ - -## FarmToken Akıllı Sözleşmesini Oluşturun {#create-farmtoken-smart-contract} - -FarmToken akıllı sözleşmesinin 3 fonksiyonu olacaktır: - -- `balance()`: FarmToken akıllı sözleşmesindeki MyToken bakiyesini alın. - -- `deposit(uint256 _amount)`: MyToken'ı kullanıcı adına FarmToken akıllı sözleşmesine aktarın ve ardından FarmToken'ı kullanıcıya aktarın. - -- `withdraw(uint256 _amount)`: Kullanıcının FarmToken token'larını yakın ve MyToken token'larını kullanıcının adresine aktarın. - -FarmToken yapıcısına bakalım: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- 3.-6. Satır: Openzeppelin'den şu sözleşmeleri içe aktarıyoruz: IERC20.sol, Address.sol, SafeERC20.sol ve ERC20.sol. - -- Satır 8: FarmToken, ERC20 sözleşmesinden kalıtıma uğrar. - -- 14.-19. Satır: FarmToken yapıcısı parametre olarak MyToken sözleşmesinin adresini alacak ve onun sözleşmesini `token` adlı genel değişkenimize atayacağız. - -Hadi `balance()` fonksiyonunu uygulayalım. Hiçbir parametre almayacak ve bu akıllı sözleşmedeki MyToken bakiyesini iade edecek. Aşağıda gösterildiği gibi uygulanır: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -`deposit(uint256 _amount)` fonksiyonu için, kullanıcının yatırmak istediği miktarı parametre olarak alacak ve FarmToken token'larını basıp kullanıcıya aktaracak: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -`withdraw(uint256 _amount)` fonksiyonu için, kullanıcının yakmak istediği FarmToken miktarını parametre olarak alacağız ve ardından aynı miktarda MyToken'ı kullanıcıya geri aktaracağız: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -Şimdi akıllı sözleşmemizi dağıtacağız. Bunu yapmak için `2_deploy_Tokens.js` dosyasına geri döneceğiz ve dağıtılacak yeni sözleşmeyi ekleyeceğiz: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -FarmToken'ı dağıtırken, dağıtılmış MyToken sözleşmesinin adresini parametre olarak ilettiğimizi unutmayın. - -Şimdi, sözleşmelerimizi dağıtmak için, `truffle compile` ve `truffle migrate` komutlarını çalıştırın. - -Akıllı sözleşmemizi test edelim. Akıllı sözleşmemizle etkileşim kurmak için `truffle console` kullanmak yerine, bu işlemi otomatikleştirmek için bir komut dosyası oluşturacağız. `scripts` isimli bir klasör oluşturun ve aşağıdaki `getMyTokenBalance.js` dosyasını ekleyin. FarmToken akıllı sözleşmesindeki MyToken bakiyesini kontrol edecek: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -Bu komut dosyasını çalıştırmak için aşağıdaki cli komutunu çalıştırın: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -0 olan beklenen sonucu alacağız. FarmToken'ın henüz dağıtılmadığına dair bir hata alırsanız truffle ağı, sözleşme kodunuzun en son sürümünü almamıştır. Ganache'yi kapatın, yeniden hızlı bir şekilde başlatın ve `truffle migrate`'i çalıştırdığınızdan emin olun. - -Şimdi, akıllı sözleşmeye MyToken stake edelim. `deposit(uint256 _amount)` fonksiyonu ERC20'den `safeTransferFrom` fonksiyonunu çağırdığından, kullanıcının MyToken'ı kullanıcı adına aktarmak için önce akıllı sözleşmeyi onaylaması gerekir. Yani aşağıdaki komut dosyasında önce bu adımı onaylayacağız, sonra fonksiyonu çağıracağız: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Bu komut dosyasını çalıştırmak için: `truffle exec .\scripts\transferMyTokenToFarmToken.js`. Konsolunuzda şunu görmelisiniz: - -![transferMyTokenToFarmToken.js çıktısı](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_transferMyTokenToFarmToken.js çıktısı_ - -Gördüğümüz gibi, ilk hesapta FarmToken'ları olduğu için MyToken'ları akıllı sözleşmeye başarıyla yatırdık. - -Çekmek için: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -Bu komut dosyasını çalıştırmak için: `truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`. Aşağıdaki çıktıda görebileceğimiz gibi, MyTokens'i başarıyla geri aldık ve FarmTokens'i yaktık: - -![withdrawMyTokenFromTokenFarm.js çıktısı](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_withdrawMyTokenFromTokenFarm.js çıktısı_ - -## Referanslar {#references} - -[Sözleşmeler - OpenZeppelin Belgeleri](https://docs.openzeppelin.com/contracts/3.x/) - -[Akıllı Sözleşmeler için Güzel Araçlar | Truffle Suite](https://www.trufflesuite.com/) - -[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache) - -[DeFi nedir? Başlangıç Rehberi (2021 Güncellendi) (99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[DeFi - DeFi Llama'da Merkeziyetsiz Finans Lider Tablosu](https://defillama.com/) diff --git a/public/content/translations/tr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/tr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index 31bea9844ac..21bbf97a01b 100644 --- a/public/content/translations/tr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/tr/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "akıllı kontratlar" - "depolama" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ Bu sınır, hizmet reddi (DOS) saldırılarını önlemek için getirildi. Bir s Bir doğal sözleşme boyutu limiti, blok gaz limiti olduğu için başlangıçta bu çok da büyük bir problem değildi. Açıkça görülüyor ki bir sözleşmenin, sözleşmenin tüm bit kodunu tutan bir işlem içinde dağıtılması gerekir. Bir bloğa yalnızca bir işlemi dahil ederseniz bu gazın tamamını kullanabilirsiniz, ancak bu sonsuz değildir. [Londra Yükseltmesi](/history/#london)'nden bu yana blok gaz limiti, ağ talebine bağlı olarak 15 milyon ile 30 milyon birim arasında değişti. -## Mücadeleye girişmek {#taking-on-the-fight} - -Ne yazık ki, sözleşmelerinizin bayt kodu boyutunu almanın kolay bir yolu yok. Truffle kullanıyorsanız [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) eklentisi size yardımcı olacak iyi bir araçtır. - -1. `npm install truffle-contract-size` -2. Eklentiyi _truffle-config.js_ öğesine ekleyin: `plugins: ["truffle-contract-size"]` -3. `truffle run contract-size` komutunu çalıştırın - -Bu, değişikliklerinizin toplam sözleşme boyutlarını nasıl etkilediğini anlamanıza yardımcı olacaktır. - Aşağıda, potansiyel etkilerine göre sıralanan bazı yöntemlere bakacağız. Bunu, kilo verme gibi düşünün. Birinin hedef kilosuna (bizim durumumuzda 24 kb) ulaşması için en iyi strateji, önce büyük etkiye sahip yöntemlere odaklanmaktır. Çoğu zaman sadece diyeti düzeltmek amaca ulaştırır ancak bazen biraz daha fazlası gerekir. Sonra biraz egzersiz (orta etki) veya hatta takviye besinler (küçük etki) ekleyebilirsiniz. ## Büyük etki {#big-impact} diff --git a/public/content/translations/tr/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/tr/developers/tutorials/secure-development-workflow/index.md index 30a8e18f408..28d5a302d47 100644 --- a/public/content/translations/tr/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/tr/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ Sözleşmenizin özel özelliklerini göz önünde bulundurun: - Sözleşmeleriniz yükseltilebilir mi? Açıkları bulunan yükseltilebilirlik kodunuzu [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) veya [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/) ile gözden geçirin. Yükseltmenin sıkıntı çıkarabileceği 17 yolu belgeledik. - Sözleşmeleriniz ERC'lere uygun olduğunu iddia ediyor mu? Onları [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance) ile kontrol edin. Bu araç, altı ortak özellikten sapmaları anında tanımlar. -- Truffle'da birim testleriniz var mı? Onları [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation) ile zenginleştirin. Özel kodunuza dayalı olarak ERC20'nin özellikleri için otomatik olarak sağlam bir güvenlik özellikleri paketi oluşturur. - 3. taraf token'ları ile entegre oluyor musunuz? Harici sözleşmelere bağlı kalmadan önce [token entegrasyon kontrol listemizi](/developers/tutorials/token-integration-checklist/) gözden geçirin. Kodunuzun kritik güvenlik özelliklerini görsel olarak inceleyin: diff --git a/public/content/translations/tr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/tr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 577f901671a..00000000000 --- a/public/content/translations/tr/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Solidity ve Truffle sürekli entegrasyon kurulumu" -description: Yararlı eklentilerle birlikte Truffle testi için Travis veya Circle CI nasıl kurulur -author: Markus Waas -lang: tr -tags: - - "solidity" - - "akıllı kontratlar" - - "test etmek" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -Truffle ile sürekli entegrasyon (CI), temel bir test setini uyguladıktan sonra geliştirme yapmak için harikadır. Bir [çekme talebini](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) birleştirmeden önce oldukça uzun testler yapmanızı ve ek araçlar kullanarak çeşitli istatistikleri takip etmenizi sağlar. - -Sürekli entegrasyonumuzu kurmak için [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) kullanacağız. Travis CI veya Circle CI'yi seçebilirsiniz. - -## Travis CI kurulumu {#setting-up-travis-ci} - -[Travis CI](https://travis-ci.org/) eklemek basittir. Projenin kök dizinine yalnızca bir `.travis.yml` yapılandırma dosyası eklemeniz gerekecek: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -Şimdilik çok karmaşıklaştırmıyoruz ve yalnızca Truffle birim testlerini yürüten test komut dosyasını çalıştırıyoruz. Ancak bir sorunumuz var, Travis CI makinesinde kullanılabilir bir blok zinciri olmayacak. Bunun için basit bir düzeltme, `npm install ganache-cli` ve bunu testten önce çalıştırmaktır. Bunu npx `ganache-cli > /dev/null` satırıyla bir bash komut dosyası ekleyerek `npx truffle test` çağrısından önce yapabilirsiniz. [Tam örnek bash komut dosyası](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh). - -## Circle CI kurulumu {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) daha uzun bir yapılandırma dosyası gerektirir. Ek [`npm ci`](https://docs.npmjs.com/cli/ci.html) komutu Travis'te otomatik olarak yapılır. Bağımlılıkları `npm install`'dan daha hızlı ve daha güvenli kurar. Testlerden önce ganache-cli'yi çalıştırmak için yine Travis versiyonundaki aynı komut dosyasını kullanıyoruz. - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## Eth-gas-reporter eklentisini ekleme {#adding-the-eth-gas-reporter-plugin} - -Eth-gas-reporter eklentisi, akıllı sözleşme fonksiyonlarınızın gaz maliyetlerini takip etmek için oldukça kullanışlıdır. CI'nizde bulundurmak, çekme talepleri eklerken farkları göstermek için ayrıca yararlı olacaktır. - -### 1. Adım: Eth-gas-reporter eklentisini ve kod kontrollerini kurun {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### 2. Adım: Eklentiyi truffle-config.js içindeki mocha ayarlarına ekleyin {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[Seçeneklere bakın](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### 3. Adım: Projenizin kök dizinine bir codechecks.yml ekleyin {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### 4. Adım: Test komutundan sonra kod kontrollerini çalıştırın {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### 5. Adım: Bir Codechecks hesabı oluşturun {#step-5-create-a-codechecks-account} - -- [Codechecks](http://codechecks.io/) ile bir hesap oluşturun. -- GitHub deposunu buna ekleyin. -- Secret'ı kopyalayın ve CI'nize `CC_SECRET=COPIED SECRET` ekleyin ([Travis](https://docs.travis-ci.com/user/environment-variables/) için buraya, [CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project) için buraya bakın). -- Şimdi devam edin ve bir çekme talebi oluşturun. - -Bu kadar. Artık çekme talebinizin gaz maliyetlerindeki değişiklikler hakkında güzel bir rapor bulacaksınız. - -![Örnek gaz raporu](./gas-reports.png) - -## Solidity-coverage eklentisini ekleme {#adding-the-solidity-coverage-plugin} - -solidity-coverage eklentisi ile, testlerinizin kod yollarınızın ne kadarını kapsadığını kontrol edebilirsiniz. Bunu CI'ınıza eklemek, kurulduktan sonra kullanımını çok kolay hâle getirir. - -### 1. Adım: Bir metacoin projesi oluşturun ve kapsama araçlarını kurun {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### 2. Adım: truffle-config.js'deki eklentiler dizisine solidity-coverage ekleyin {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### 3. Adım: Coverage komutlarını .travis.yml veya Circle CI config.yml dosyasına ekleyin {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Solidity coverage, kendi ganache-cli'sini başlatır, bu yüzden bu konuda endişelenmemize gerek yok. Yine de normal test komutunu değiştirmeyin, coverage'ın ganache-cli'si farklı şekilde çalışır ve bu nedenle düzenli birim testleri çalıştırmanın yerini alamaz. - -### 4. Adım: Depoyu coveralls'a ekleyin {#step-4-add-repository-to-coveralls} - -- [Coveralls](https://coveralls.io/) ile bir hesap oluşturun. -- GitHub deposunu buna ekleyin. -- Şimdi devam edin ve bir çekme talebi oluşturun. - -![Örnek coverall](./coverall.png) - -## Diğer fikirler {#further-ideas} - -- [MythX](https://mythx.io/): MythX ile akıllı sözleşme güvenliğinizi otomatik olarak analiz edebilirsiniz. Yani [bunu CI'nize eklemek](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/) gayet mantıklıdır. -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29): İyi kod, linting araçlarıyla bir dereceye kadar zorlanabilir. [Eslint](https://eslint.org/) JavaScript ile harika çalışır ve [ kurulumu kolaydır](https://eslint.org/docs/user-guide/getting-started). [Solhint](https://protofire.github.io/solhint/) ise Solidity için kullanılabilir. -- Uzun testler: Bazen, örneğin yüzlerce kullanıcıyla bir sözleşmeyi test etmek gibi ekstrem testler eklemek isteyebilirsiniz. Bu, uzun bir süre alır. Bunları her test çalışmasında çalıştırmak yerine CI'a ekleyin. - -İşte oldu. Sürekli entegrasyon, geliştirmeleriniz için çok faydalı bir stratejidir. [Truffle-CI-Example](https://github.com/gorgos/Truffle-CI-Example)'da tam bir örneğe göz atabilirsiniz. Sadece Circle-CI veya Travis'i çıkardığınızdan emin olun, bir tane yeterlidir! diff --git a/public/content/translations/tr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/tr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index 45c9024c78d..ab775c5f18e 100644 --- a/public/content/translations/tr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/tr/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ Manifesto, yapılandırma dosyamızdır ve şunları tanımlar: - fonksiyon çağrıları veya bloklar gibi dinlenecek diğer şeyler - çağrılan eşleştirme fonksiyonları (aşağıdaki `mapping.ts`'e bakın) -Burada birden fazla sözleşme ve işleyici tanımlayabilirsiniz. Tipik bir kurulum, Truffle/Hardhat projesinin içinde kendi deposuna sahip bir alt grafik klasörüne sahip olacaktır. Ardından ABI'ye kolayca başvurabilirsiniz. +Burada birden fazla sözleşme ve işleyici tanımlayabilirsiniz. Tipik bir kurulum, Hardhat projesinin içinde kendi deposuna sahip bir alt grafik klasörüne sahip olacaktır. Ardından ABI'ye kolayca başvurabilirsiniz. Kolaylık sağlamak için mustache gibi bir şablon aracı da kullanmak isteyebilirsiniz. Ardından bir `subgraph.template.yaml` oluşturur ve en son dağıtımlara göre adresleri eklersiniz. Daha gelişmiş örnek bir kurulum için, örnek olarak [Aave alt grafik deposuna](https://github.com/aave/aave-protocol/tree/master/thegraph) bakınız. diff --git a/public/content/translations/tr/enterprise/index.md b/public/content/translations/tr/enterprise/index.md index 41da8b57eec..afe4d24060a 100644 --- a/public/content/translations/tr/enterprise/index.md +++ b/public/content/translations/tr/enterprise/index.md @@ -72,7 +72,6 @@ Ethereum'u işletme dostu hâle getirmek için farklı kuruluşlar tarafından b - [Ernst & Young'ın "Nightfall"u](https://github.com/EYBlockchain/nightfall) _özel işlemler için bir araç takımı_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _bir web3 sağlayıcısıyla kullanılacak bir işlem imzalama uygulaması_ - [Tenderly](https://tenderly.co/)_gerçek zamanlı analizler sağlayan, özel ağlar için destek sunarak uyarılarda bulunan ve izleme gerçekleştiren bir Veri Platformudur_ -- [Truffle Suite](https://trufflesuite.com) _blok zinciri geliştirme paketi (Truffle, Ganache, Drizzle)_ ### Ölçeklenebilirlik çözümleri {#scalability-solutions} diff --git a/public/content/translations/uk/community/support/index.md b/public/content/translations/uk/community/support/index.md index 08651c95d78..1b16a7cdba4 100644 --- a/public/content/translations/uk/community/support/index.md +++ b/public/content/translations/uk/community/support/index.md @@ -56,7 +56,6 @@ _Це не вичерпний список. Потрібна допомога в - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [Hardhat](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/uk/enterprise/index.md b/public/content/translations/uk/enterprise/index.md index cda5586aa8c..2a5f16adf1d 100644 --- a/public/content/translations/uk/enterprise/index.md +++ b/public/content/translations/uk/enterprise/index.md @@ -75,7 +75,6 @@ sidebarDepth: 1 - [Alethio](https://explorer.aleth.io/) _— платформа для аналізу даних Ethereum_ - [Treum](https://treum.io/) _забезпечує прозорість, можливості відстеження та реалізації ланцюгів поставок з використанням технології блокчейну_ -- [Truffle Suite](https://trufflesuite.com) _— набір для розробки блокчейну (Truffle, Ganache, Drizzle)_ ## Спільнота розробників для корпоративного сектора {#enterprise-developer-community} diff --git a/public/content/translations/vi/enterprise/index.md b/public/content/translations/vi/enterprise/index.md index 41e090dec88..ac654ea89b8 100644 --- a/public/content/translations/vi/enterprise/index.md +++ b/public/content/translations/vi/enterprise/index.md @@ -75,7 +75,6 @@ Mạng Ethereum công cộng và riêng tư có thể cần các tính năng c - [Alethio -](https://explorer.aleth.io/) _Nền tảng phân tích dữ liệu Ethereum_ - [Treum](https://treum.io/) _mang lại tính minh bạch, truy xuất nguồn gốc và tính truyền thống cho chuỗi cung ứng, sử dụng công nghệ chuỗi khối_ -- [Truffle Suite](https://trufflesuite.com) _bộ phát triển chuỗi khối (Truffle, Ganache, Drizzle)_ ## Cộng đồng nhà phát triển doanh nghiệp {#enterprise-developer-community} diff --git a/public/content/translations/zh-tw/community/support/index.md b/public/content/translations/zh-tw/community/support/index.md index bd5916f9308..e02dc8007b6 100644 --- a/public/content/translations/zh-tw/community/support/index.md +++ b/public/content/translations/zh-tw/community/support/index.md @@ -73,7 +73,6 @@ lang: zh-tw - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [安全帽](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/zh-tw/contributing/index.md b/public/content/translations/zh-tw/contributing/index.md index eaf36252a59..05e04a5b221 100644 --- a/public/content/translations/zh-tw/contributing/index.md +++ b/public/content/translations/zh-tw/contributing/index.md @@ -68,7 +68,7 @@ Ethereum.org 是一個開源專案,擁有超過 **12000 名**貢獻者,幫 - 我們的[風格指南](/contributing/style-guide/) - 我們的[行為準則](/community/code-of-conduct) - + ## 如何做出有關網站的決定 {#how-decisions-about-the-site-are-made} diff --git a/public/content/translations/zh-tw/enterprise/index.md b/public/content/translations/zh-tw/enterprise/index.md index facecc42143..6172480e80e 100644 --- a/public/content/translations/zh-tw/enterprise/index.md +++ b/public/content/translations/zh-tw/enterprise/index.md @@ -75,7 +75,6 @@ lang: zh-tw - [Alathio](https://explorer.aleth.io/) _以太坊數據分析平台_ - [Treum](https://treum.io/) _使用區塊鏈技術為供應鏈帶來透明度、可追溯性和可交易性_ -- [Truffle Suite](https://trufflesuite.com) _區塊鏈開發套件(Truffle、Ganache、Drizzle)_ ## 企業開發社群 {#enterprise-developer-community} diff --git a/public/content/translations/zh/community/support/index.md b/public/content/translations/zh/community/support/index.md index 530324c0525..5d6f5a3ee8f 100644 --- a/public/content/translations/zh/community/support/index.md +++ b/public/content/translations/zh/community/support/index.md @@ -57,7 +57,6 @@ _这并不是完整的列表。 需要帮助寻找特定钱包的支持? 加 - [ethers.js](https://discord.gg/6jyGVDK6Jx) - [web3.js](https://discord.gg/GsABYQu4sC) - [安全帽](https://discord.gg/xtrMGhmbfZ) -- [Truffle](https://discord.gg/8uKcsccEYE) - [Alchemy](http://alchemy.com/discord) - [Tenderly](https://discord.gg/fBvDJYR) diff --git a/public/content/translations/zh/developers/docs/bridges/index.md b/public/content/translations/zh/developers/docs/bridges/index.md index a06a1b4a9c4..80fbc8e72b3 100644 --- a/public/content/translations/zh/developers/docs/bridges/index.md +++ b/public/content/translations/zh/developers/docs/bridges/index.md @@ -104,7 +104,7 @@ lang: zh ### 在多条链上部署去中心化应用程序 {#deploying-a-dapp-on-multiple-chains} -要在多条链上部署去中心化应用程序,开发者可以使用 [Alchemy](https://www.alchemy.com/)、[安全帽](https://hardhat.org/)、[Truffle](https://trufflesuite.com/)、[Moralis](https://moralis.io/) 等开发平台。 这些平台通常提供可组合的插件,能够支持去中心化应用程序跨链。 例如,开发者可以使用[安全帽部署插件](https://github.com/wighawag/hardhat-deploy)提供的确定性部署代理。 +要在多条链上部署去中心化应用程序,开发者可以使用 [Alchemy](https://www.alchemy.com/)、[安全帽](https://hardhat.org/)、[Moralis](https://moralis.io/) 等开发平台。 这些平台通常提供可组合的插件,能够支持去中心化应用程序跨链。 例如,开发者可以使用[安全帽部署插件](https://github.com/wighawag/hardhat-deploy)提供的确定性部署代理。 #### 例子: diff --git a/public/content/translations/zh/developers/docs/development-networks/index.md b/public/content/translations/zh/developers/docs/development-networks/index.md index fd7f039903b..011bb9247de 100644 --- a/public/content/translations/zh/developers/docs/development-networks/index.md +++ b/public/content/translations/zh/developers/docs/development-networks/index.md @@ -28,16 +28,6 @@ lang: zh **注意**:大多数[开发框架](/developers/docs/frameworks/)包含一个内置的开发网络。 我们建议从一个框架开始[设置你的本地开发环境](/developers/local-environment/)。 -### Ganache {#ganache} - -快速构建一个个人的以太坊区块链,你可以用它来运行测试,执行命令,并在控制链的运行方式时检查状态。 - -Ganache提供了一个桌面应用程序 (Ganache UI) 以及一个命令行工具 (`ganache-cli`)。 它是 Truffle 工具套装的一部分。 - -- [网站](https://www.trufflesuite.com/ganache) -- [GitHub](https://github.com/trufflesuite/ganache) -- [相关文档](https://www.trufflesuite.com/docs/ganache/overview) - ### 安全帽网络 {#hardhat-network} 一个专门用于开发的本地以太坊网络。 该网络允许你部署合约,运行测试并调试代码。 diff --git a/public/content/translations/zh/developers/docs/frameworks/index.md b/public/content/translations/zh/developers/docs/frameworks/index.md index 1ef7b46f05a..8202491c95b 100644 --- a/public/content/translations/zh/developers/docs/frameworks/index.md +++ b/public/content/translations/zh/developers/docs/frameworks/index.md @@ -93,12 +93,6 @@ lang: zh - [GitHub](https://github.com/eth-brownie/brownie) - **Brownie 当前未维护** -**Truffle -** **_开发环境、测试框架、构建管道及其他工具。_** - -- [trufflesuite.com](https://www.trufflesuite.com/) -- [GitHub](https://github.com/trufflesuite/truffle) -- **Truffle 开发已结束** - [了解更多](https://twitter.com/trufflesuite/status/1704946902393860589?t=NlIWeLTbBSAaJmS5uUAhSA&s=19) - **OpenZeppelin SDK -** **_终极智能合约工具包:一套帮助你开发、编译、升级、部署智能合约并与之交互的工具。_** - [OpenZeppelin SDK](https://openzeppelin.com/sdk/) diff --git a/public/content/translations/zh/developers/docs/programming-languages/dart/index.md b/public/content/translations/zh/developers/docs/programming-languages/dart/index.md index 0f7cd12edcf..d617542f94a 100644 --- a/public/content/translations/zh/developers/docs/programming-languages/dart/index.md +++ b/public/content/translations/zh/developers/docs/programming-languages/dart/index.md @@ -10,9 +10,8 @@ incomplete: true ## 教程 {#tutorials} - [Flutter 和区块链 – Hello World 去中心化应用程序](https://www.geeksforgeeks.org/flutter-and-blockchain-hello-world-dapp/)带你了解所有步骤,内容包括: - 1. 安装 [Truffle 开发套件](https://www.trufflesuite.com/) - 2. 使用 [Solidity](https://soliditylang.org/) 编写一个智能合约 - 3. 使用 Dart 编写一个用户界面 + 1. 使用 [Solidity](https://soliditylang.org/) 编写一个智能合约 + 2. 使用 Dart 编写一个用户界面 - 如果你已经了解基础知识,[使用 Flutter 构建移动去中心化应用程序](https://medium.com/dash-community/building-a-mobile-dapp-with-flutter-be945c80315a)的篇幅要短得多,效果可能更好 - 如果你喜欢通过观看视频来学习,可以观看[构建你的第一个区块链 Flutter 应用程序](https://www.youtube.com/watch?v=3Eeh3pJ6PeA),时长大约一个小时 - 如果你不想花这么多时间,你可能喜欢[在以太坊上使用 Flutter 和 Dart 创建去中心化的区块链应用](https://www.youtube.com/watch?v=jaMFEOCq_1s),时长仅约 20 分钟 diff --git a/public/content/translations/zh/developers/docs/programming-languages/golang/index.md b/public/content/translations/zh/developers/docs/programming-languages/golang/index.md index 875cb55ac17..ac7fdfaefad 100644 --- a/public/content/translations/zh/developers/docs/programming-languages/golang/index.md +++ b/public/content/translations/zh/developers/docs/programming-languages/golang/index.md @@ -23,7 +23,6 @@ incomplete: true ## 初学者文章和书籍 {#beginner-articles-and-books} -- [选择以太坊客户端](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [开始使用 Geth](https://medium.com/@tzhenghao/getting-started-with-geth-c1a30b8d6458) - [使用 Golang 连接到以太坊](https://www.youtube.com/watch?v=-7uChuO_VzM) - [使用 Golang 部署以太坊智能合约](https://www.youtube.com/watch?v=pytGqQmDslE) diff --git a/public/content/translations/zh/developers/docs/programming-languages/rust/index.md b/public/content/translations/zh/developers/docs/programming-languages/rust/index.md index 3ed0519eb72..d041b78b04e 100644 --- a/public/content/translations/zh/developers/docs/programming-languages/rust/index.md +++ b/public/content/translations/zh/developers/docs/programming-languages/rust/index.md @@ -22,7 +22,6 @@ incomplete: true ## 初学者文章 {#beginner-articles} -- [选择以太坊客户端](https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client) - [Rust 以太坊客户端](https://openethereum.github.io/) \* **注意 OpenEthereum [已被废弃](https://medium.com/openethereum/gnosis-joins-erigon-formerly-turbo-geth-to-release-next-gen-ethereum-client-c6708dd06dd)并已停止维护。** 请谨慎使用,最好切换至其他客户端实现。 - [使用 Rust 向以太坊发送交易](https://kauri.io/#collections/A%20Hackathon%20Survival%20Guide/sending-ethereum-transactions-with-rust/) - [如何用 Rust Wasm 为 Kovan 编写合约的分步教程](https://github.com/paritytech/pwasm-tutorial) diff --git a/public/content/translations/zh/developers/docs/security/index.md b/public/content/translations/zh/developers/docs/security/index.md index 9d3fa49ce0e..cab9ca97ced 100644 --- a/public/content/translations/zh/developers/docs/security/index.md +++ b/public/content/translations/zh/developers/docs/security/index.md @@ -29,7 +29,7 @@ lang: zh - 所有代码应该被存在于一个版本控制系统当中,例如 git - 所有的代码修改都应该通过拉取请求来进行 - 所有的拉取请求都应该有至少一个审核员。 _如果这是一个个人项目,请考虑寻找另一位个人作者和一个交易代码审核员。_ -- 使用开发以太坊环境(请参阅:Truffle),只需一个命令就可以编译、部署和运行一套针对你的代码的测试 +- 使用开发以太坊环境,只需一个命令就可以编译、部署和运行一套针对你的代码的测试 - 已经通过 Mythril 和 Sliter 等基本代码分析工具运行了代码,最好是在合并每个拉取请求之前,比较输出中的差异。 - Solidity 代码编辑器不会发出任何警告 - 你的代码有据可查 diff --git a/public/content/translations/zh/developers/tutorials/create-and-deploy-a-defi-app/index.md b/public/content/translations/zh/developers/tutorials/create-and-deploy-a-defi-app/index.md deleted file mode 100644 index ea8b266ebdf..00000000000 --- a/public/content/translations/zh/developers/tutorials/create-and-deploy-a-defi-app/index.md +++ /dev/null @@ -1,481 +0,0 @@ ---- -title: 创建并部署一个去中心化金融应用程序 -description: 将 ERC20 代币存入智能合约,铸造流动性矿池代币 -author: "strykerin" -tags: - - "solidity" - - "deFi" - - "web3.js" - - "truffle" - - "ganache" - - "智能合约" -skill: intermediate -lang: zh -published: 2020-12-31 -source: github.com -sourceUrl: https://github.com/strykerin/DeFi-Token-Farm ---- - -在本教程中,我们将使用 Solidity 构建一个去中心化金融应用程序。用户可以将 ERC20 代币存入智能合约,然后铸造流动性矿池代币并将这些代币转给他们。 用户之后可以通过消耗智能合约上的流动性矿池代币来赎回他们的 ERC20 代币,然后 ERC20 代币将会转回给他们。 - -## 安装 Truffle 和 Ganache {#install-truffle-and-ganache} - -如果这是你第一次编写智能合约,你需要搭建你的环境。 我们将使用两个工具:[Truffle](https://www.trufflesuite.com/) 和 [Ganache](https://www.trufflesuite.com/ganache)。 - -Truffle 是用于开发以太坊智能合约的开发环境和测试框架。 使用 Truffle 可以很容易地在区块链中创建和部署智能合约。 Ganache 可以帮助我们创建一个本地以太坊区块链,用以测试智能合约。 它模拟真实的网络功能,前 10 个帐户存入了 100 个测试以太币,如此可以随意部署和测试智能合约。 Ganache 可提供桌面应用程序和命令行工具。 在本文中,我们将使用有图形界面的桌面应用程序。 - -![Ganache 图形界面桌面应用程序](https://cdn-images-1.medium.com/max/2360/1*V1iQ5onbLbT5Ib2QaiOSyg.png)_Ganache UI desktop application_ - -要创建项目,请运行以下命令: - -```bash -mkdir your-project-name -cd your-project-name -truffle init -``` - -这将为智能合约的开发和部署创建一个空白项目, 创建的项目结构如下: - -- `contracts`:存放 solidity 智能合约的文件夹 - -- `migrations`:存放部署脚本的文件夹 - -- `test`:存放智能合约测试文件的文件夹 - -- `truffle-config.js`:Truffle 配置文件 - -## 创建ERC20 代币 {#create-the-erc20-token} - -首先,我们需要创建 ERC20 代币,用于在智能合约上质押。 要创建同质化代币,我们首先需要安装 OpenZeppelin 库。 该库包含 ERC20 和 ERC721 等标准的实现。 如需安装,请运行以下命令: - -```bash -npm install @openzeppelin/contracts -``` - -使用 OpenZepelin 库,我们可以通过写入 `contracts/MyToken.sol` 创建我们的 ERC20 代币,需用到以下 solidity 代码: - -```solidity -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract MyToken is ERC20 { - constructor() public ERC20("MyToken", "MTKN"){ - _mint(msg.sender, 1000000000000000000000000); - } -} -``` - -在上述代码中: - -- 第 3 行:我们从包含此代币标准实现的 openzepelin 导入 ERC20.sol 合约。 - -- 第 5 行:我们继承了 ERC20.sol 合约。 - -- 第 6 行:我们要调用 ERC20.sol 构造函数,并将名称和符号参数分别设为 `"MyToken"` 和 `"MTKN"`。 - -- 第 7 行:我们为正在部署智能合约的帐户铸造和转移 100 万代币(我们默认为 ERC20 代币使用 18 位小数)。这意味着,如果我们想要铸造 1 个代币,则需将其表示为 1000000000000000000,即 1 和 18 个零)。 - -我们可以看到,ERC20.sol 构造函数实现下方,`_decimals` 字段设置为 18: - -```solidity -string private _name; -string private _symbol; -uint8 private _decimals; - -constructor (string memory name_, string memory symbol_) public { - _name = name_; - _symbol = symbol_; - _decimals = 18; -} -``` - -## 编译 ERC20 代币 {#compile-the-erc20-token} - -要编译我们的智能合约,我们必须首先检查我们的 solidity 编译器版本。 可以通过运行以下命令来检查: - -```bash -truffle version -``` - -默认版本是 `Solidity v0.5.16`。 由于我们的代币基于 solidity 版本 `0.6.2` 编写,如果我们运行命令来编译合约,我们会遇到编译器错误。 要使用指定的 solidity 编译器版本,请转到文件 `truffle-config.js`,设为所需的编译器版本,如下所示: - -```javascript -// Configure your compilers -compilers: { - solc: { - version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version) - // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) - // settings: { // See the solidity docs for advice about optimization and evmVersion - // optimizer: { - // enabled: false, - // runs: 200 - // }, - // evmVersion: "byzantium" - // } - } -} -``` - -现在,我们可以通过运行以下命令来编译智能合约: - -```bash -truffle compile -``` - -## 部署 ERC20 代币 {#deploy-erc20-token} - -编译后,我们现在便可以部署代币了。 - -在 `migrations` 文件夹中,创建一个名为 `2_deploy_Tokens.js` 的文件。 我们将在该文件中部署 ERC20 代币和 FarmToken 智能合约。 以下代码用于部署我们的 MyToken.sol 合约: - -```javascript -const MyToken = artifacts.require("MyToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() -} -``` - -打开 Ganache 并选择“快速启动”选项,启动本地以太坊区块链。 要部署合约,请运行: - -```bash -truffle migrate -``` - -用于部署合同的地址是 Ganache 显示的地址列表中的第一个地址。 为核实这一点,我们可以打开 Ganache 桌面应用程序,然后可以核实第一个帐户的以太币余额已经减少,这是我们部署智能合约的以太币成本: - -![Ganache 桌面应用程序](https://cdn-images-1.medium.com/max/2346/1*1iJ9VRlyLuza58HL3DLfpg.png)_Ganache desktop application_ - -为了验证 100 万 MyToken 代币是否已发送到部署者地址,我们可以使用 Truffle 控制台与我们部署的智能合约进行交互。 - -> [Truffle 控制台是一个基础型交互式控制台,可连接到任何以太坊客户端。](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console) - -要与智能合约交互,请运行以下命令: - -```bash -truffle console -``` - -现在,我们可以在终端写入以下命令: - -- 获取智能合约:`myToken = await MyToken.depolyed()` - -- 从 Ganache 获取帐户组:`accounts = await web3.eth.getAccounts()` - -- 获取第一个帐户的余额:`balance = await myToken.balance Of(accounts[0])` - -- 格式化具有 18 位小数的余额:`web3.utils.fromWei(balance.toString())` - -通过运行上述命令,我们会看到第一个地址实际上有 100 万 MyToken: - -![第一个地址有 1000000 MyToken](https://cdn-images-1.medium.com/max/2000/1*AQlj9A7dw-qtY4QAD3Bpxw.png) - -_第一个地址有 1000000 MyToken_ - -## 创建 FarmToken 智能合约 {#create-farmtoken-smart-contract} - -FarmToken 智能合约将包含 3 个函数: - -- `balance()`:获取 FarmToken 智能合约上的 MyToken 余额。 - -- `deposit(uint256 _amount)`:代表用户将 MyToken 转移到 FarmToken 智能合约,然后铸造 FarmToken 并转账给用户。 - -- `withdraw(uint256 _amount)`:消耗用户的 FarmToken 并将 MyToken 转到用户的地址。 - -我们来看看 FarmToken 构造函数: - -```solidity -pragma solidity ^0.6.2; - -import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "@openzeppelin/contracts/utils/Address.sol"; -import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - -contract FarmToken is ERC20 { - using Address for address; - using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath - using SafeERC20 for IERC20; - - IERC20 public token; - - constructor(address _token) - public - ERC20("FarmToken", "FRM") - { - token = IERC20(_token); - } -``` - -- 第 3-6 行:我们要从 openzepelin 导入下列合约:IERC20.sol、Address.sol、SafeERC20.sol 和ERC20.sol。 - -- 第 8 行:FarmToken 将继承 ERC20 合约。 - -- 14-19 行:FarmToken 构造函数将接收 MyToken 合约地址作为参数,我们将把此地址分配给我们名为 `token` 的公共变量。 - -我们来实现 `balance()` 函数。 它将不会收到任何参数,将返回此智能合约上的 MyToken 余额。 可按如下所示实现: - -```solidity -function balance() public view returns (uint256) { - return token.balanceOf(address(this)); -} -``` - -对于 `deposit(uint256 _amount)` 函数,将接收用户想要存入的金额作为参数,铸造 FarmTokens 并转给用户: - -```solidity -function deposit(uint256 _amount) public { - // Amount must be greater than zero - require(_amount > 0, "amount cannot be 0"); - - // Transfer MyToken to smart contract - token.safeTransferFrom(msg.sender, address(this), _amount); - - // Mint FarmToken to msg sender - _mint(msg.sender, _amount); -} -``` - -对于 `withdraw(uint256 _amount)` 函数,将接收用户想要消耗的 FarmTokens 数额作为参数,然后将相同数额的 MyToken 返还给用户: - -```solidity -function withdraw(uint256 _amount) public { - // Burn FarmTokens from msg sender - _burn(msg.sender, _amount); - - // Transfer MyTokens from this smart contract to msg sender - token.safeTransfer(msg.sender, _amount); -} -``` - -现在我们将部署我们的智能合约。 为此,我们将返回文件 `2_deploy_Tokens.js` 并添加要部署的新合约: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (deployer, network, accounts) { - // Deploy MyToken - await deployer.deploy(MyToken) - const myToken = await MyToken.deployed() - - // Deploy Farm Token - await deployer.deploy(FarmToken, myToken.address) - const farmToken = await FarmToken.deployed() -} -``` - -请注意,在部署 FarmToken 时,我们将已部署的 MyToken 合约的地址作为参数传递。 - -现在,运行 `truffle compile` 和 `truffle migrate` 来部署我们的合约。 - -我们来测试一下我们的智能合约。 不要使用 `truffle console` 与我们的智能合约交互,我们将创建一个脚本来自动执行此过程。 创建一个名为 `scripts` 的文件夹,并添加以下文件 `getMyTokenBalance.js`。 该文件将核查 FarmToken 智能合约中的 MyToken 余额: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - myToken = await MyToken.deployed() - farmToken = await FarmToken.deployed() - balance = await myToken.balanceOf(farmToken.address) - console.log(web3.utils.fromWei(balance.toString())) - callback() -} -``` - -要执行此脚本,请运行以下 cli 命令: - -```bash -truffle exec .\scripts\getMyTokenBalance.js -``` - -我们将得到预期结果 0。 如果你收到尚未部署 FarmToken 的错误,则表明 truffle 网络尚未收到最新版本的合约代码。 只需关闭 ganache,然后再快速启动,并确保运行 `truffle migrate`。 - -现在,让我们把 MyToken 押在智能合约上。 由于 `deposit(uint256 _amount)` 函数调用了来自 ERC20 的 `safeTransferFrom` 函数,用户必须首先批准智能合约,才能以用户的名义转账 MyToken。 因此,在下面的脚本中,我们将首先批准此步骤,然后调用函数: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner through transferFrom. - // This is zero by default. - const allowanceBefore = await myToken.allowance( - accounts[0], - farmToken.address - ) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf Before: " + - allowanceBefore.toString() - ) - - // In order to allow the Smart Contract to transfer to MyToken (ERC-20) on the accounts[0] behalf, - // we must explicitly allow it. - // We allow farmToken to transfer x amount of MyToken on our behalf - await myToken.approve(farmToken.address, web3.utils.toWei("100", "ether")) - - // Validate that the farmToken can now move x amount of MyToken on our behalf - const allowanceAfter = await myToken.allowance(accounts[0], farmToken.address) - console.log( - "Amount of MyToken FarmToken is allowed to transfer on our behalf After: " + - allowanceAfter.toString() - ) - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - // Call Deposit function from FarmToken - console.log("Call Deposit Function") - await farmToken.deposit(web3.utils.toWei("100", "ether")) - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -要运行此脚本:`truffle exec .\script\transferMyTokenToFarmToken.js`。 你将在控制台上看到如下输出: - -![transferMyTokenToFarmToken.js 的输出](https://cdn-images-1.medium.com/max/2000/1*MoekE2QCw7vB98u5dl7ang.png) - -_transferMyTokenToFarmToken.js 的输出_ - -正如我们所见,我们已成功将 MyToken 存入智能合约,因为第一个帐户现在已经有了 FarmToken。 - -要取款: - -```javascript -const MyToken = artifacts.require("MyToken") -const FarmToken = artifacts.require("FarmToken") - -module.exports = async function (callback) { - const accounts = await new web3.eth.getAccounts() - const myToken = await MyToken.deployed() - const farmToken = await FarmToken.deployed() - - // Verify accounts[0] and farmToken balance of MyToken before and after the transfer - balanceMyTokenBeforeAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenBeforeFarmToken = await myToken.balanceOf(farmToken.address) - console.log("*** My Token ***") - console.log( - "Balance MyToken Before accounts[0] " + - web3.utils.fromWei(balanceMyTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance MyToken Before TokenFarm " + - web3.utils.fromWei(balanceMyTokenBeforeFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenBeforeAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenBeforeFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken Before accounts[0] " + - web3.utils.fromWei(balanceFarmTokenBeforeAccounts0.toString()) - ) - console.log( - "Balance FarmToken Before TokenFarm " + - web3.utils.fromWei(balanceFarmTokenBeforeFarmToken.toString()) - ) - - // Call Deposit function from FarmToken - console.log("Call Withdraw Function") - await farmToken.withdraw(web3.utils.toWei("100", "ether")) - - console.log("*** My Token ***") - balanceMyTokenAfterAccounts0 = await myToken.balanceOf(accounts[0]) - balanceMyTokenAfterFarmToken = await myToken.balanceOf(farmToken.address) - console.log( - "Balance MyToken After accounts[0] " + - web3.utils.fromWei(balanceMyTokenAfterAccounts0.toString()) - ) - console.log( - "Balance MyToken After TokenFarm " + - web3.utils.fromWei(balanceMyTokenAfterFarmToken.toString()) - ) - - console.log("*** Farm Token ***") - balanceFarmTokenAfterAccounts0 = await farmToken.balanceOf(accounts[0]) - balanceFarmTokenAfterFarmToken = await farmToken.balanceOf(farmToken.address) - console.log( - "Balance FarmToken After accounts[0] " + - web3.utils.fromWei(balanceFarmTokenAfterAccounts0.toString()) - ) - console.log( - "Balance FarmToken After TokenFarm " + - web3.utils.fromWei(balanceFarmTokenAfterFarmToken.toString()) - ) - - // End function - callback() -} -``` - -要运行此脚本:`truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js`。 正如我们在下面的输出中所看到的,我们已经成功地取回了 MyToken,并消耗掉了 FarmToken: - -![withdrawMyTokenFromTokenFarm.js 的输出](https://cdn-images-1.medium.com/max/2000/1*jHYlTFg0NgGbhASpsRvc0w.png) - -_withdrawMyTokenFromTokenFarm.js 的输出_ - -## 参考文献 {#references} - -[合约 - OpenZepelin 文档](https://docs.openzeppelin.com/contracts/3.x/) - -[智能合约的适用工具 | Truffle 套装](https://www.trufflesuite.com/) - -[Ganache | Truffle 套装](https://www.trufflesuite.com/ganache) - -[什么是去中心化金融? 初学者指南(2021 年更新)(99bitcoins.com)](https://99bitcoins.com/what-is-defi/) - -[去中心化金融 - DeFi Llama 的去中心化金融排行榜](https://defillama.com/) diff --git a/public/content/translations/zh/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md b/public/content/translations/zh/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md index 2f5ea42febc..44210872c43 100644 --- a/public/content/translations/zh/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md +++ b/public/content/translations/zh/developers/tutorials/downsizing-contracts-to-fight-the-contract-size-limit/index.md @@ -7,7 +7,6 @@ tags: - "solidity" - "智能合约" - "存储" - - "truffle" skill: intermediate published: 2020-06-26 source: soliditydeveloper.com @@ -24,16 +23,6 @@ sourceUrl: https://soliditydeveloper.com/max-contract-size 最初,这不是什么大问题,因为一个自然合约大小限制是区块燃料限制。 显然,合约必须和其所有字节码一起部署在交易内。 如果只将单个交易添加到区块中,可能会用完所有燃料,而燃料并非无限。 [伦敦升级](/history/#london)后,区块燃料限制已能够根据网络需求在 15M 和 30M 单位之间变动。 -## 开始战斗吧! {#taking-on-the-fight} - -不幸的是,没有简单的方法来获得合约的字节码大小。 如果您使用 Truffle,有一个很好的工具可以帮助您:那就是 [truffle-contract-size](https://github.com/IoBuilders/truffle-contract-size) 插件。 - -1. `npm install truffle-contract-size` -2. 将插件添加到 _truffle-config.js_:`plugins: ["truffle-contract-size"]` -3. 运行 `truffle run contract-size` - -这将帮助您了解您的更改对合约总大小有何影响。 - 在下文中,我们将根据其潜在的影响顺序来研究一些方法。 从减肥的角度来谈一谈。 对于一个人来说,要达到他们的目标体重(在我们的例子中是 24 kb),最好的策略是首先关注影响较大的方法。 在大多数情况下,只要调整您的饮食就能达到目标,但有时您需要做得更多一些。 然后您可以增加一些锻炼(中等影响)或甚至补充剂(小影响)。 ## 较大影响 {#big-impact} diff --git a/public/content/translations/zh/developers/tutorials/secure-development-workflow/index.md b/public/content/translations/zh/developers/tutorials/secure-development-workflow/index.md index 737456713af..2adc0b1246f 100644 --- a/public/content/translations/zh/developers/tutorials/secure-development-workflow/index.md +++ b/public/content/translations/zh/developers/tutorials/secure-development-workflow/index.md @@ -26,7 +26,6 @@ sourceUrl: https://github.com/crytic/building-secure-contracts/blob/master/devel - 你的合约是否可以升级? 使用 [`slither-check-upgradeability`](https://github.com/crytic/slither/wiki/Upgradeability-Checks) 或 [Crytic](https://blog.trailofbits.com/2020/06/12/upgradeable-contracts-made-safer-with-crytic/) 检查你的可升级代码是否有缺陷。 我们记录了 17 种升级可能出现的问题。 - 你的合约是否声明符合 ERC 的要求? 使用 [`slither-check-erc`](https://github.com/crytic/slither/wiki/ERC-Conformance) 对它们进行审核。 这个工具能立即识别出六个常见规范的偏差。 -- 你在 Truffle 中设有单元测试吗? 将它们添加到 [`slither-prop`](https://github.com/crytic/slither/wiki/Property-generation)。 它可以根据你的具体代码自动生成一套强大的安全属性,用于 ERC20 功能。 - 你是否与第三方代币集成? 在依赖外部合约之前,请先查看我们的[代币集成清单](/developers/tutorials/token-integration-checklist/)。 目视检查代码的关键安全功能。 diff --git a/public/content/translations/zh/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md b/public/content/translations/zh/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md deleted file mode 100644 index 52b9111dedf..00000000000 --- a/public/content/translations/zh/developers/tutorials/solidity-and-truffle-continuous-integration-setup/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: "Solidity 和 Truffle 持续集成设置" -description: 如何为 Truffle 测试设置 Travis 或 Circle CI 以及有用的插件 -author: Markus Waas -lang: zh -tags: - - "solidity" - - "智能合约" - - "测试" - - "truffle" - - "ganache" -skill: intermediate -published: 2020-06-05 -source: soliditydeveloper.com -sourceUrl: https://soliditydeveloper.com/continuous-integration ---- - -与 Truffle 的持续集成 (CI) 非常适合在实施一组基本测试后进行开发。 它允许你运行非常长的测试。在合并[拉取请求](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)之前确保所有测试通过,并使用其他工具跟踪各种统计数据。 - -我们将使用 [Truffle Metacoin Box](https://www.trufflesuite.com/boxes/metacoin) 来设置我们的持续集成。 你可以选择 Travis CI 或 Circle CI。 - -## 设置 Travis CI {#setting-up-travis-ci} - -添加 [Travis CI](https://travis-ci.org/) 很简单。 你只需要将 `.travis.yml` 配置文件添加到项目的根目录: - -```yml -language: node_js -node_js: - - 10 - -cache: npm - -before_script: - - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p - -script: - - npm test -``` - -我们现在保持简单,只运行执行 Truffle 单元测试的测试脚本。 但我们有一个问题,在 Travis CI 机器上没有区块链。 一个简单的解决方法是使用命令 `npm install ganache-cli` 安装 ganache-cli,并在测试前运行它。 你可以通过在 `npx truffle test` 调用前添加一个带有 npx `ganache-cli > /dev/null` 行的 bash 脚本来实现这一点。 [完整示例 bash 脚本](https://github.com/gorgos/Truffle-CI-Example/blob/master/scripts/run_tests.sh)。 - -## 设置 Circle CI {#setting-up-circle-ci} - -[CircleCi](https://circleci.com/) 需要更长的配置文件。 额外的 [`npm ci`](https://docs.npmjs.com/cli/ci.html) 命令在 Travis 中自动完成。 它安装依赖项比 `npm install` 更快和更安全。 在测试之前,我们再次使用 Travis 版本中的同一个脚本来运行 ganache-cli。 - -```yml -version: 2 - -aliases: - - &defaults - docker: - - image: circleci/node:10 - - - &cache_key_node_modules - key: v1-node_modules-{{ checksum "package-lock.json" }} - -jobs: - dependencies: - <<: *defaults - steps: - - checkout - - restore_cache: - <<: *cache_key_node_modules - - run: - name: Install npm dependencies - command: | - if [ ! -d node_modules ]; then - npm ci - fi - - persist_to_workspace: - root: . - paths: - - node_modules - - build - - save_cache: - paths: - - node_modules - <<: *cache_key_node_modules - - test: - <<: *defaults - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Unit tests - command: npm test - -workflows: - version: 2 - everything: - jobs: - - dependencies - - test: - requires: - - dependencies -``` - -## 添加 eth-gas-reporter 插件 {#adding-the-eth-gas-reporter-plugin} - -Eth-gas-reporter 插件对于记录你的智能合约函数的燃料成本相当有用。 在你的 CI 中使用它,将进一步有助于在添加拉取请求时显示差异。 - -### 第 1 步:安装 eth-gas-reporter 插件和 {#step-1-install-the-eth-gas-reporter-plugin-and-codechecks} - -```bash -npm install --save-dev eth-gas-reporter -npm install --save-dev @codechecks/client -``` - -### 第 2 步:在你的 truffle-config.js 内的 mocha 设置中加入该插件 {#step-2-add-the-plugin-to-the-mocha-settings-inside-your-truffle-configjs} - -[查看选项](https://github.com/cgewecke/eth-gas-reporter#options) - -```js -module.exports = { - networks: { ... }, - mocha: { - reporter: 'eth-gas-reporter', - reporterOptions: { - excludeContracts: ['Migrations'] - } - } -}; -``` - -### 第 3 步:在你的项目的根目录中添加一个 codechecks.yml {#step-3-add-a-codechecksyml-to-your-projects-root-directory} - -```yml -checks: - - name: eth-gas-reporter/codechecks -``` - -### 第 4 步:在 test 命令后运行 codechecks {#step-4-run-codechecks-after-the-test-command} - -```bash -- npm test -- npx codechecks -``` - -### 第 5 步:创建一个 Codechecks 帐户 {#step-5-create-a-codechecks-account} - -- 使用 [Codechecks](http://codechecks.io/) 创建一个帐户。 -- 将 GitHub 存储库添加到其中。 -- 复制密钥并将 `CC_SECRET=COPIED SECRET` 添加到你的 CI( [Travis](https://docs.travis-ci.com/user/environment-variables/) 参见这里,[CircleCi](https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-project) 参见这里)。 -- 现在继续创建拉取请求。 - -这就完成了。 现在,你将看到一份关于你的拉取请求的燃料成本变化的报告。 - -![Gas 成本报告示例](./gas-reports.png) - -## 添加 solidity-coverage 插件 {#adding-the-solidity-coverage-plugin} - -通过 solidity-coverage 插件,你可以检查你的代码路径有多少被你的测试所覆盖。 将此插件添加到你的 CI,设置好后,使用非常方便。 - -### 第 1 步:创建一个 metacoin 项目并安装覆盖工具 {#step-1-create-a-metacoin-project-and-install-coverage-tools} - -```bash -npm install --save-dev truffle coveralls solidity-coverage -``` - -### 第 2 步:将 solidity-coverage 添加到 truffle-config.js 的插件数组中。 {#step-2-add-solidity-coverage-to-the-plugins-array-in-truffle-configjs} - -```js -module.exports = { - networks: {...}, - plugins: ["solidity-coverage"] -} -``` - -### 第 3 步:将 coverage 命令添加到 .travis.yml 或 Circle CI config.yml {#step-3-add-the-coverage-commands-to-the-travisyml-or-circle-ci-configyml} - -```bash -- npx truffle run coverage -- cat coverage/lcov.info | npx coveralls -``` - -Solidity coverage 启动了它自己的 ganache-cli,所以我们不必担心这个问题。 但不要替换常规测试命令,coverage 的 ganache-cli 工作方式不同,因此不能代替运行正常的单位测试。 - -### 第 4 步:将 repository 添加到 Coveralls {#step-4-add-repository-to-coveralls} - -- 使用 [Coveralls](https://coveralls.io/) 创建一个帐户 -- 将 GitHub 存储库添加到其中。 -- 现在继续创建拉取请求。 - -![Coverall 示例](./coverall.png) - -## 进一步的想法 {#further-ideas} - -- [MythX](https://mythx.io/):使用 MythX,你可以自动分析智能合约的安全性。 因此, [将其添加到你的 CI](https://blog.mythx.io/howto/mythx-and-continuous-integration-part-1-circleci/) 是非常有意义的。 -- [Linting](https://wikipedia.org/wiki/Lint_%28software%29):好代码可以在一定程度上通过 linting 工具强制执行。 [Eslint](https://eslint.org/) 非常适合 JavaScript 并且[便于设置](https://eslint.org/docs/user-guide/getting-started),而 [Solhint](https://protofire.github.io/solhint/) 可用于 Solidity。 -- 长测试:有时你可能想要添加极端测试,例如使用数百名用户测试一个合约。 这需要很长时间。 不要在每次测试运行中都运行它们,而是将它们添加到 CI 中。 - -这是全部内容了。 持续集成是你开发中非常有用的战略。 你可以在 [Truffle-CI-example](https://github.com/gorgos/Truffle-CI-Example) 查看完整的示例。 请务必移除 Circle-CI 或 Travis,只使用一个就够了! diff --git a/public/content/translations/zh/developers/tutorials/the-graph-fixing-web3-data-querying/index.md b/public/content/translations/zh/developers/tutorials/the-graph-fixing-web3-data-querying/index.md index da58585919e..cb73a2493ff 100644 --- a/public/content/translations/zh/developers/tutorials/the-graph-fixing-web3-data-querying/index.md +++ b/public/content/translations/zh/developers/tutorials/the-graph-fixing-web3-data-querying/index.md @@ -120,7 +120,7 @@ GameContract.events.BetPlaced({ - 其他要侦听的东西,如函数调用或区块 - 被调用的映射函数(参见下面的 `mapping.ts`) -您可以在此处定义多个智能合约和处理程序。 典型的设置在 Truffle/Hardhat 项目中会有一个子图文件夹,它有自己的存储库。 然后您可以轻松引用 ABI。 +您可以在此处定义多个智能合约和处理程序。 典型的设置在 Hardhat 项目中会有一个子图文件夹,它有自己的存储库。 然后您可以轻松引用 ABI。 为方便起见,您可能还想使用像 mustache 这样的模板工具。 然后创建一个 `subgraph.template.yaml` 并根据最新部署插入地址。 有关更高级的示例设置,请参阅这个 [Aave subgraph repo](https://github.com/aave/aave-protocol/tree/master/thegraph) 示例。 diff --git a/public/content/translations/zh/enterprise/index.md b/public/content/translations/zh/enterprise/index.md index 381b23408db..9037944aa30 100644 --- a/public/content/translations/zh/enterprise/index.md +++ b/public/content/translations/zh/enterprise/index.md @@ -72,7 +72,6 @@ lang: zh - [Ernst & Young 的“Nightfall”](https://github.com/EYBlockchain/nightfall) _私有的交易工具包_ - [EthSigner](https://github.com/ConsenSys/ethsigner) _与 Web3 应用提供商一起使用的交易签名应用程序_ - [Tenderly](https://tenderly.co/)_,一个提供实时分析、告警和监控,并为专用网络提供支持的数据平台_ -- [Truffle Suite](https://trufflesuite.com) _区块链开发套件(Truffle、Ganache、Drizzle)_ ### 可扩展性解决方案 {#scalability-solutions} diff --git a/public/images/0xparc-logo.svg b/public/images/0xparc-logo.svg new file mode 100644 index 00000000000..dcb9b050a1f --- /dev/null +++ b/public/images/0xparc-logo.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/public/images/attestant-logo.svg b/public/images/attestant-logo.svg new file mode 100644 index 00000000000..9a6ca3dcde6 --- /dev/null +++ b/public/images/attestant-logo.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/images/events/event-placeholder.png b/public/images/events/event-placeholder.png index 4a15165452a..a94614605d5 100644 Binary files a/public/images/events/event-placeholder.png and b/public/images/events/event-placeholder.png differ diff --git a/public/images/man-and-dog-playing.png b/public/images/man-and-dog-playing.png new file mode 100644 index 00000000000..14e75d2156e Binary files /dev/null and b/public/images/man-and-dog-playing.png differ diff --git a/public/images/man-baby-woman.png b/public/images/man-baby-woman.png new file mode 100644 index 00000000000..92ce90dcd26 Binary files /dev/null and b/public/images/man-baby-woman.png differ diff --git a/public/images/panda-ops-banner.png b/public/images/panda-ops-banner.png new file mode 100644 index 00000000000..6f80160d92e Binary files /dev/null and b/public/images/panda-ops-banner.png differ diff --git a/public/images/robot-help-bar.png b/public/images/robot-help-bar.png new file mode 100644 index 00000000000..4e698736a19 Binary files /dev/null and b/public/images/robot-help-bar.png differ diff --git a/public/images/solidity-banner.png b/public/images/solidity-banner.png new file mode 100644 index 00000000000..3fd5a37c62e Binary files /dev/null and b/public/images/solidity-banner.png differ diff --git a/public/images/vitalik-blog-banner.svg b/public/images/vitalik-blog-banner.svg new file mode 100644 index 00000000000..cea992081c9 --- /dev/null +++ b/public/images/vitalik-blog-banner.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/sentry.client.config.ts b/sentry.client.config.ts deleted file mode 100644 index 093f87fc876..00000000000 --- a/sentry.client.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as Sentry from "@sentry/nextjs" - -const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN - -Sentry.init({ - dsn, - enabled: process.env.NODE_ENV === "production", - environment: process.env.NEXT_PUBLIC_CONTEXT, - tracesSampleRate: 1.0, -}) diff --git a/src/@chakra-ui/components/Button.ts b/src/@chakra-ui/components/Button.ts index 1b51d328012..5d46960d242 100644 --- a/src/@chakra-ui/components/Button.ts +++ b/src/@chakra-ui/components/Button.ts @@ -11,27 +11,40 @@ import { defineStyle, defineStyleConfig } from "@chakra-ui/react" const ICON_SELECTOR = "& svg" const baseStyle = defineStyle({ + // Sizing and positioning classes: borderRadius: "base", border: "1px", - color: "primary.base", fontWeight: "normal", lineHeight: "1.6", transitionProperty: "common", transitionDuration: "normal", whiteSpace: "normal", p: "unset", + // Base default styling is "outline" pattern, primary color for text, border matches, no bg + borderColor: "currentColor", + color: "primary.base", + // Hover: Default hover adds box-shadow, text (border) to --primary-hover + _hover: { + color: "primary.hover", + boxShadow: "buttonHover", + }, + // Focus: Add 4px outline to all buttons, --primary-hover _focusVisible: { outline: "4px solid", outlineColor: "primary.hover", outlineOffset: -1, }, + // Active: text (border) to --primary-hover instead of primary, hide shadow + _active: { + color: "primary.hover", + boxShadow: "none", + }, + // Disabled: Pointer events none, text (border) to --disabled _disabled: { color: "disabled", pointerEvents: "none", }, - _hover: { - color: "primary.hover", - }, + // isSecondary: Switch text (border) to --body instead of --primary "&[data-secondary='true']": { color: "body.base", }, @@ -41,42 +54,39 @@ const baseStyle = defineStyle({ textDecoration: "none", }, }, + [ICON_SELECTOR]: { + flexShrink: 0, + }, }) const variantSolid = defineStyle({ - color: "background.base", - bg: "primary.base", - borderColor: "transparent", - _disabled: { - bg: "disabled", - color: "background.base", - }, + color: "white", + bg: "primary.action", + borderColor: "transparent !important", _hover: { - color: "background.base", - bg: "primary.hover", - boxShadow: "buttonHover", + color: "white !important", + bg: "primary.actionHover", }, _active: { - boxShadow: "none", - }, -}) - -const variantOutline = defineStyle({ - _hover: { - boxShadow: "buttonHover", + bg: "primary.actionHover", }, - _active: { - boxShadow: "none", + _disabled: { + bg: "disabled", + color: "background.base", }, }) +const variantOutline = defineStyle({}) // "outline" is base styling above + const variantGhost = { borderColor: "transparent", + _hover: { shadow: "none" }, } const variantLink = defineStyle({ borderColor: "transparent", - fontWeight: 700, + // fontWeight: 700, // TODO: Not in DS; confirm then remove + _hover: { shadow: "none" }, textDecor: "underline", py: 0, px: 1, diff --git a/src/@chakra-ui/components/ReactSelect.ts b/src/@chakra-ui/components/ReactSelect.ts deleted file mode 100644 index 17abb11362f..00000000000 --- a/src/@chakra-ui/components/ReactSelect.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { createMultiStyleConfigHelpers, cssVar } from "@chakra-ui/react" - -import { reactSelectAnatomyKeys } from "@/components/Select/innerComponents" - -const $borderBaseWidth = cssVar("border-base-width") - -const { defineMultiStyleConfig, definePartsStyle } = - createMultiStyleConfigHelpers(reactSelectAnatomyKeys) - -const baseStyle = definePartsStyle({ - container: { - [$borderBaseWidth.variable]: "borders.1px", - w: "full", - minH: 10.5, - cursor: "pointer", - position: "relative", - zIndex: 1, - "& > .react-select__menu": { - zIndex: -1, - }, - }, - control: { - border: $borderBaseWidth.reference, - borderColor: "currentColor", - outlineOffset: "-2px", - p: 2, - gap: 4, - _hover: { - color: "primary.base", - borderColor: "primary.lowContrast", - }, - "&[data-expanded=true]": { - bg: "background.highlight", - color: "primary.base", - borderColor: "primary.lowContrast", - }, - "&:focus-within:not([data-expanded=true])": { - outline: "3px solid", - outlineColor: "primary.hover", - borderColor: "transparent", - }, - }, - groupHeading: { - color: "body.medium", - }, - indicatorIcon: { - fontSize: "sm", - transitionProperty: "common", - transitionDuration: "normal", - "*[data-expanded=true] &": { - transform: "rotate(180deg)", - }, - }, - menuList: { - bg: "background.highlight", - w: "full", - maxH: "xs", - overflowY: "auto", - }, - option: { - color: "body.base", - p: 2, - "&[data-focused=true]": { - bg: "primary.lowContrast", - color: "primary.base", - }, - "&[data-active=true]": { - bg: "body.light", - color: "primary.visited", - }, - }, -}) - -const $borderTopRadius = cssVar("border-top-radius") - -const variantFlushed = definePartsStyle({ - container: { - [$borderTopRadius.variable]: "radii.base", - borderTopRadius: $borderTopRadius.reference, - }, - control: { - borderTopRadius: $borderTopRadius.reference, - borderTopColor: "transparent", - borderInlineColor: "transparent", - _hover: { - borderTopColor: "transparent", - borderInlineColor: "transparent", - }, - "&[data-expanded=true]": { - borderColor: "body.light", - borderBottomColor: "primary.base", - }, - }, - menuList: { - borderInline: $borderBaseWidth.reference, - borderBottom: $borderBaseWidth.reference, - borderColor: "body.light", - borderBottomRadius: "base", - }, -}) - -const $borderOutlineRadius = cssVar("border-outline-radius") - -const variantOutline = definePartsStyle({ - container: { - [$borderOutlineRadius.variable]: "radii.base", - borderRadius: $borderOutlineRadius.reference, - }, - control: { - borderRadius: $borderOutlineRadius.reference, - "&[data-expanded=true]": { - borderBottomColor: "transparent", - borderBottomRadius: "none", - }, - }, - menuList: { - borderInline: $borderBaseWidth.reference, - borderBottom: $borderBaseWidth.reference, - borderColor: "primary.lowContrast", - borderBottomRadius: "base", - }, -}) - -const variants = { - flushed: variantFlushed, - outline: variantOutline, -} - -export const ReactSelect = defineMultiStyleConfig({ - baseStyle, - variants, - defaultProps: { - variant: "flushed", - }, -}) diff --git a/src/@chakra-ui/components/index.ts b/src/@chakra-ui/components/index.ts index 9cf99739fa5..1a1b20cefcf 100644 --- a/src/@chakra-ui/components/index.ts +++ b/src/@chakra-ui/components/index.ts @@ -22,7 +22,6 @@ import { Modal } from "./Modal" import { Popover } from "./Popover" import { Progress } from "./Progress" import { Radio } from "./Radio" -import { ReactSelect } from "./ReactSelect" import { Switch } from "./Switch" import { Table } from "./Table" import { Tabs } from "./Tabs" @@ -52,7 +51,6 @@ export default { Popover, Progress, Radio, - ReactSelect, Spinner: spinnerDefaultTheme, Switch, Table, diff --git a/src/@chakra-ui/foundations/colors.ts b/src/@chakra-ui/foundations/colors.ts index dbf3e6cd57e..58f443a9282 100644 --- a/src/@chakra-ui/foundations/colors.ts +++ b/src/@chakra-ui/foundations/colors.ts @@ -2,41 +2,54 @@ export type Colors = typeof colors const colors = { gray: { - 100: "#F7F7F7", - 150: "#F2F2F2", - 200: "#E7E7E7", - 300: "#C8C8C8", + 50: "#f7f7f7", + 100: "#eeeeee", + 150: "#ececec", + 200: "#cecece", + 300: "#acacac", 400: "#8C8C8C", 500: "#616161", 600: "#333333", 700: "#222222", - 800: "#1B1B1B", - 900: "#141414", + 800: "#1b1b1b", + 900: "#121212", + 950: "#0a0a0a", }, blue: { - 50: "#F6F6FF", - 100: "#EBEBFF", - 200: "#D6D6FF", - 300: "#9999FF", - 400: "#5555FF", - 500: "#1C1CFF", - 600: "#0000E0", - 700: "#0000A3", - 800: "#000066", - 900: "#000029", + 50: "#F8FBFF", + 100: "#E8F1FF", + 200: "#CADFFB", + 300: "#88AAF1", + 400: "#6995F7", + 500: "#4473EF", + 600: "#3C4CEB", + 700: "#2B36A8", + 800: "#232F71", + 900: "#1B273A", }, orange: { 50: "#FFF3ED", - 100: "#FFE5D6", - 200: "#FFCBAD", - 300: "#FFB185", - 400: "#FF985C", - 500: "#FF7324", - 550: "#DF5A0E", - 600: "#B84300", - 700: "#7A2D00", - 800: "#521E00", - 900: "#2F1000", + 100: "#FFF0DB", + 200: "#FFD7A7", + 300: "#FEB077", + 400: "#FD8640", + 500: "#FB610E", + 600: "#EC4A0A", + 700: "#C4350A", + 800: "#7D2711", + 900: "#3A291D", + }, + purple: { + 50: "#F3ECFF", + 100: "#EDE2FF", + 200: "#DAC5FC", + 300: "#CCAFFC", + 400: "#B38DF0", + 500: "#945AF4", + 600: "#6C24DF", + 700: "#561BB5", + 800: "#41128B", + 900: "#1E0546", }, red: { 100: "#f7c8c8", diff --git a/src/@chakra-ui/foundations/shadows.ts b/src/@chakra-ui/foundations/shadows.ts index ee4ff14e936..15190c39b41 100644 --- a/src/@chakra-ui/foundations/shadows.ts +++ b/src/@chakra-ui/foundations/shadows.ts @@ -20,8 +20,7 @@ const shadows = { gridBlueBowShadow: "8px 8px 0px 0px var(--eth-colors-gridBlue)", // * Part of new DS - // TODO: From current theme. Deprecate for 'buttonHover' - primary: "4px 4px 0px 0px var(--eth-colors-primary-light)", + // TODO: Deprecate buttonHover when all buttons migrated to tailwind buttonHover: "4px 4px 0 0 var(--eth-colors-primary-lowContrast)", tooltip: "0 0 16px var(--eth-colors-tooltipShadow)", } diff --git a/src/@chakra-ui/semanticTokens.ts b/src/@chakra-ui/semanticTokens.ts index 9b81ae3c21a..b1d447bd07b 100644 --- a/src/@chakra-ui/semanticTokens.ts +++ b/src/@chakra-ui/semanticTokens.ts @@ -37,11 +37,13 @@ const semanticTokens = { // Main Set primary: { - base: { _light: "blue.500", _dark: "orange.500" }, - highContrast: { _light: "blue.800", _dark: "orange.100" }, - lowContrast: { _light: "blue.100", _dark: "orange.800" }, - hover: { _light: "blue.400", _dark: "orange.400" }, - visited: { _light: "blue.700", _dark: "orange.550" }, + base: { _light: "purple.600", _dark: "purple.400" }, + highContrast: { _light: "purple.800", _dark: "purple.200" }, + lowContrast: { _light: "purple.100", _dark: "purple.900" }, + hover: { _light: "purple.500", _dark: "purple.300" }, + visited: { _light: "purple.700", _dark: "purple.300" }, + action: { _light: "purple.600", _dark: "purple.600" }, + actionHover: { _light: "purple.500", _dark: "purple.500" }, // ! Deprecating primary.light light: { _light: "blue.100", _dark: "orange.100" }, // ! Deprecating primary.dark @@ -53,11 +55,9 @@ const semanticTokens = { base: { _light: "gray.800", _dark: "gray.100" }, medium: { _light: "gray.500", _dark: "gray.400" }, light: { _light: "gray.200", _dark: "gray.600" }, - // ! Deprecating body.inverted - inverted: { _light: "gray.100", _dark: "gray.800" }, }, background: { - base: { _light: "white", _dark: "gray.800" }, + base: { _light: "white", _dark: "black" }, highlight: { _light: "gray.100", _dark: "gray.900" }, }, disabled: { _light: "gray.400", _dark: "gray.500" }, @@ -91,7 +91,6 @@ const semanticTokens = { _light: "blackAlpha.400", _dark: "whiteAlpha.400", }, - switchBackground: { _light: "gray.300", _dark: "whiteAlpha.400" }, hubHeroContentBg: { _light: "rgba(255, 255, 255, 0.80)", _dark: "rgba(34, 34, 34, 0.80)", diff --git a/src/@chakra-ui/stories/Colors.stories.tsx b/src/@chakra-ui/stories/Colors.stories.tsx index bfefcbe5ac7..ddaf32ef76d 100644 --- a/src/@chakra-ui/stories/Colors.stories.tsx +++ b/src/@chakra-ui/stories/Colors.stories.tsx @@ -113,7 +113,7 @@ export const SemanticScheme: StoryObj = { ] as const const deprecatedTokens: Record<(typeof tokenNames)[number], string[]> = { primary: ["light", "dark", "pressed"], - body: ["inverted"], + body: [], background: [], disabled: [], success: ["neutral", "outline"], diff --git a/src/@chakra-ui/theme.ts b/src/@chakra-ui/theme.ts index ccce5e63610..ddafd133eee 100644 --- a/src/@chakra-ui/theme.ts +++ b/src/@chakra-ui/theme.ts @@ -7,7 +7,15 @@ import semanticTokens from "./semanticTokens" const config: ThemeConfig = { cssVarPrefix: "eth", initialColorMode: "system", - useSystemColorMode: true, + /** + * Disable Chakra's system color subscription, as it works differently from + * `next-themes` and causes a desync with it. + * + * Chakra will always change the color mode based on the system preference. + * While `next-themes` will only change to the system preference if the user + * has `system` as their active theme. + */ + useSystemColorMode: false, } /** diff --git a/src/components/AssetDownload/index.tsx b/src/components/AssetDownload/index.tsx index f3a4e2e0c1d..613d8d9eceb 100644 --- a/src/components/AssetDownload/index.tsx +++ b/src/components/AssetDownload/index.tsx @@ -26,6 +26,7 @@ const AssetDownload = ({ artistName, artistUrl, image, + svgUrl, title, ...props }: AssetDownloadProps) => { @@ -66,12 +67,11 @@ const AssetDownload = ({ {t("page-assets-download-download")} ( {extname(imgSrc).slice(1).toUpperCase()}) - {/* Disables SVG due to bug: https://github.com/ethereum/ethereum-org-website/issues/12267 */} - {/* {svgUrl && ( + {svgUrl && ( {t("page-assets-download-download")} (SVG) - )} */} + )} ) diff --git a/src/components/Banners/BannerNotification.tsx b/src/components/Banners/BannerNotification.tsx index 70f0e14ac3d..7c0bb19ac6c 100644 --- a/src/components/Banners/BannerNotification.tsx +++ b/src/components/Banners/BannerNotification.tsx @@ -1,40 +1,26 @@ -import React from "react" -import { Center, FlexProps, useMediaQuery } from "@chakra-ui/react" +import { cn } from "@/lib/utils/cn" -import { lightTheme as oldTheme } from "../../theme" - -export type BannerNotificationProps = FlexProps & { +export type BannerNotificationProps = React.HTMLAttributes & { shouldShow?: boolean } const BannerNotification = ({ children, - shouldShow = false, + shouldShow, + className, ...props }: BannerNotificationProps) => { - const [isLGScreen] = useMediaQuery(`min-width: ${oldTheme.breakpoints.l}`) + if (!shouldShow) return <> return ( - <> - {shouldShow && ( -
- {children} -
+ ) } diff --git a/src/components/Banners/ContributorsQuizBanner.tsx b/src/components/Banners/ContributorsQuizBanner.tsx index 6ca19865f8a..a1128bdfa59 100644 --- a/src/components/Banners/ContributorsQuizBanner.tsx +++ b/src/components/Banners/ContributorsQuizBanner.tsx @@ -1,19 +1,21 @@ -import { Box, Flex, FlexProps, Heading, Text } from "@chakra-ui/react" +import { Box, Flex, Heading, Text } from "@chakra-ui/react" import { Image } from "@/components/Image" +import { cn } from "@/lib/utils/cn" + import { ButtonLink } from "../Buttons" import PeopleLearning from "@/public/images/people-learning.png" // TODO: refactor to use CalloutBanner component -function ContributorsQuizBanner(props: FlexProps) { +function ContributorsQuizBanner(props: React.HTMLAttributes) { return ( - - + ) } diff --git a/src/components/Banners/DismissableBanner/index.tsx b/src/components/Banners/DismissableBanner/index.tsx index 09cb50aabd1..1384c497572 100644 --- a/src/components/Banners/DismissableBanner/index.tsx +++ b/src/components/Banners/DismissableBanner/index.tsx @@ -1,20 +1,24 @@ -// Libraries -import React, { useEffect, useState } from "react" -import { Center, CloseButton } from "@chakra-ui/react" +import { useEffect, useState } from "react" +import { useTranslation } from "next-i18next" +import { MdClose } from "react-icons/md" + +import { Button } from "@/components/ui/buttons/Button" +import { Center } from "@/components/ui/flex" + +import { cn } from "@/lib/utils/cn" -// Components import BannerNotification from "../BannerNotification" -// Interface -export type DismissableBannerProps = { - children: JSX.Element +type DismissableBannerProps = React.HTMLAttributes & { storageKey: string } const DismissableBanner = ({ children, storageKey, + className, }: DismissableBannerProps) => { + const { t } = useTranslation("common") const [show, setShow] = useState(false) useEffect(() => { @@ -28,13 +32,16 @@ const DismissableBanner = ({ } return ( - -
{children}
- +
{children}
+
) } diff --git a/src/components/BigNumber/index.tsx b/src/components/BigNumber/index.tsx new file mode 100644 index 00000000000..d276611edd4 --- /dev/null +++ b/src/components/BigNumber/index.tsx @@ -0,0 +1,76 @@ +import { type ReactNode } from "react" +import { useRouter } from "next/router" +import { useTranslation } from "next-i18next" +import { MdInfoOutline } from "react-icons/md" + +import { cn } from "@/lib/utils/cn" +import { isValidDate } from "@/lib/utils/date" + +import Tooltip from "../Tooltip" +import Link from "../ui/Link" + +type BigNumberProps = { + children: ReactNode + value?: ReactNode + sourceName?: string + sourceUrl?: string + lastUpdated?: number | string + className?: string +} + +const BigNumber = ({ + children, + value, + sourceName, + sourceUrl, + lastUpdated, + className, +}: BigNumberProps) => { + const { t } = useTranslation("common") + const { locale } = useRouter() + const lastUpdatedDisplay = + lastUpdated && isValidDate(lastUpdated) + ? new Intl.DateTimeFormat(locale, { + dateStyle: "medium", + }).format(new Date(lastUpdated)) + : "" + return ( +
+ {value ? ( + <> +
{value}
+
+ {children} + {sourceName && sourceUrl && ( + +

+ {t("data-provided-by")}{" "} + {sourceName} +

+ {lastUpdated && ( +

+ {t("last-updated")}: {lastUpdatedDisplay} +

+ )} + + } + > + +
+ )} +
+ + ) : ( + {t("loading-error-refresh")} + )} +
+ ) +} +export default BigNumber diff --git a/src/components/Buttons/SvgButtonLink.tsx b/src/components/Buttons/SvgButtonLink.tsx new file mode 100644 index 00000000000..a070a9e30dc --- /dev/null +++ b/src/components/Buttons/SvgButtonLink.tsx @@ -0,0 +1,73 @@ +import { cva, VariantProps } from "class-variance-authority" +import type { FC, ReactNode, SVGProps } from "react" + +import { cn } from "@/lib/utils/cn" + +import { BaseLink } from "../ui/Link" + +type SvgButtonLinkProps = { + Svg: FC> + label?: string + children: ReactNode + href: string + className?: string + size?: number +} + +const variants = cva("flex items-center gap-3.5", { + variants: { + variant: { + col: "flex-col text-center [&_.body]:text-center", + row: "flex-row text-start [&_.body]:text-start [&_.header]:self-start", + }, + }, + defaultVariants: { + variant: "row", + }, +}) + +type Variants = VariantProps + +const SvgButtonLink = ({ + label, + children, + Svg, + className, + variant, + ...props +}: SvgButtonLinkProps & Variants) => ( + +
+
+ +
+
+ {label &&

{label}

} + {children} +
+
+
+) + +export default SvgButtonLink diff --git a/src/components/CalloutBanner.tsx b/src/components/CalloutBanner.tsx index 2b6bd4f1fba..23e7aec6423 100644 --- a/src/components/CalloutBanner.tsx +++ b/src/components/CalloutBanner.tsx @@ -1,14 +1,12 @@ import { useTranslation } from "next-i18next" -import { Flex, type FlexProps } from "@chakra-ui/react" import type { TranslationKey } from "@/lib/types" -import { Image, type ImageProps } from "@/components/Image" -import OldHeading from "@/components/OldHeading" -import Text from "@/components/OldText" +import { type ImageProps, TwImage } from "@/components/Image" -export type CalloutBannerProps = FlexProps & { - children?: React.ReactNode +import { cn } from "@/lib/utils/cn" + +export type CalloutBannerProps = React.HTMLAttributes & { image: ImageProps["src"] imageWidth?: number titleKey: TranslationKey @@ -23,57 +21,39 @@ const CalloutBanner = ({ descriptionKey, alt, children, + className, ...props }: CalloutBannerProps) => { const { t } = useTranslation("page-staking") return ( - - {image && ( - - {alt} - - )} - - +
+ +
+ +
+

{t(titleKey)} - - +

+

{t(descriptionKey)} - +

{children} - - +
+ ) } diff --git a/src/components/CentralizedExchanges/index.tsx b/src/components/CentralizedExchanges/index.tsx index 64e4444005d..4898ddd01ad 100644 --- a/src/components/CentralizedExchanges/index.tsx +++ b/src/components/CentralizedExchanges/index.tsx @@ -9,7 +9,7 @@ import Emoji from "@/components/Emoji" import InlineLink from "@/components/Link" import OldHeading from "@/components/OldHeading" import Text from "@/components/OldText" -import Select from "@/components/Select" +import Select from "@/components/ui/Select" import { getLocaleTimestamp } from "@/lib/utils/time" diff --git a/src/components/Chevron/index.tsx b/src/components/Chevron/index.tsx new file mode 100644 index 00000000000..33116e5cdd9 --- /dev/null +++ b/src/components/Chevron/index.tsx @@ -0,0 +1,21 @@ +import { MdChevronLeft, MdChevronRight } from "react-icons/md" + +import { cn } from "@/lib/utils/cn" + +import { useRtlFlip } from "@/hooks/useRtlFlip" + +export const ChevronNext = ({ + className, + ...props +}: React.HTMLAttributes) => { + const { twFlipForRtl } = useRtlFlip() + return +} + +export const ChevronPrev = ({ + className, + ...props +}: React.HTMLAttributes) => { + const { twFlipForRtl } = useRtlFlip() + return +} diff --git a/src/components/CodeModal.tsx b/src/components/CodeModal.tsx index 399ee1e40b7..6f44d4e28e1 100644 --- a/src/components/CodeModal.tsx +++ b/src/components/CodeModal.tsx @@ -1,24 +1,26 @@ -import type { ReactNode } from "react" -import { - Modal, - ModalBody, - ModalCloseButton, - ModalContent, - ModalHeader, - ModalOverlay, - useColorModeValue, -} from "@chakra-ui/react" +import { Children, type ReactElement } from "react" +import { useTranslation } from "next-i18next" +import { IoMdCopy } from "react-icons/io" +import { MdCheck } from "react-icons/md" +import { Modal, ModalBody, ModalContent, ModalOverlay } from "@chakra-ui/react" + +import { Button } from "./ui/buttons/Button" + +import { useClipboard } from "@/hooks/useClipboard" type CodeModalProps = { title: string - children: ReactNode + children?: ReactElement isOpen: boolean setIsOpen: (isOpen: boolean) => void } const CodeModal = ({ children, isOpen, setIsOpen, title }: CodeModalProps) => { - const bgColor = useColorModeValue("rgb(247, 247, 247)", "rgb(25, 25, 25)") - const borderColor = useColorModeValue("rgb(51, 51, 51)", "rgb(242, 242, 242)") + const { t } = useTranslation() + const codeSnippet = (Children.toArray(children)[0] as ReactElement).props + .children.props.children + + const { onCopy, hasCopied } = useClipboard() return ( { scrollBehavior="inside" onClose={() => setIsOpen(false)} > - + { p={{ base: "0", md: "0" }} gap="0" > - - {title} - - +
+

{title}

+ +
{children} +
) diff --git a/src/components/Codeblock.tsx b/src/components/Codeblock.tsx index 9f00303918c..ef6b7b9ca55 100644 --- a/src/components/Codeblock.tsx +++ b/src/components/Codeblock.tsx @@ -6,34 +6,32 @@ import Highlight, { PrismTheme, } from "prism-react-renderer" import Prism from "prism-react-renderer/prism" -import { Box, BoxProps, Flex, useColorModeValue } from "@chakra-ui/react" // https://github.com/FormidableLabs/prism-react-renderer/tree/master#custom-language-support import CopyToClipboard from "@/components/CopyToClipboard" import Emoji from "@/components/Emoji" +import { Flex } from "@/components/ui/flex" + +import { cn } from "@/lib/utils/cn" import { LINES_BEFORE_COLLAPSABLE } from "@/lib/constants" + +import useColorModeValue from "@/hooks/useColorModeValue" ;(typeof global !== "undefined" ? global : window).Prism = Prism require("prismjs/components/prism-solidity") -const TopBarItem = (props: BoxProps) => { - const bgColor = useColorModeValue("#f7f7f7", "#363641") - +const TopBarItem = ({ + className, + ...props +}: React.HTMLAttributes) => { return ( - ) @@ -42,8 +40,8 @@ const TopBarItem = (props: BoxProps) => { const codeTheme = { light: { plain: { - backgroundColor: "#fafafa", - color: "#333333", + backgroundColor: "#f7f7f7", // background-highlight (gray-50) + color: "#6C24DF", // primary (purple-600) }, styles: [ { @@ -114,8 +112,8 @@ const codeTheme = { dark: { // Pulled from `defaultProps.theme` for potential customization plain: { - backgroundColor: "#2a2734", - color: "#9a86fd", + backgroundColor: "#121212", // background-highlight (gray-900) + color: "#B38DF0", // primary (purple-400) }, styles: [ { @@ -204,11 +202,10 @@ const getValidChildrenForCodeblock = (child) => { } } -export type CodeblockProps = { +export type CodeblockProps = React.HTMLAttributes & { allowCollapse?: boolean codeLanguage: string fromHomepage?: boolean - children: React.ReactNode } const Codeblock = ({ @@ -216,6 +213,7 @@ const Codeblock = ({ allowCollapse = true, codeLanguage, fromHomepage = false, + className, }: CodeblockProps) => { const { t } = useTranslation("common") const selectedTheme = useColorModeValue(codeTheme.light, codeTheme.dark) @@ -229,14 +227,14 @@ const Codeblock = ({ const [isCollapsed, setIsCollapsed] = useState(allowCollapse) - let className: string + let langClass: string if (React.isValidElement(children)) { - className = children?.props?.className + langClass = children?.props?.className } else { - className = codeLanguage || "" + langClass = codeLanguage || "" } - const matches = className?.match(/language-(.*)/) + const matches = langClass?.match(/language-(.*)/) const language = matches?.[1] || "" const shouldShowCopyWidget = ["js", "json", "python", "solidity"].includes( @@ -251,18 +249,14 @@ const Codeblock = ({ return ( /* Overwrites codeblocks inheriting RTL styling in Right-To-Left script languages (e.g. Arabic) */ /* Context: https://github.com/ethereum/ethereum-org-website/issues/6202 */ - - +
{({ className, style, tokens, getLineProps, getTokenProps }) => ( - {tokens.map((line, i) => { return i === tokens.length - 1 && line[0].content === "" ? null : ( - {shouldShowLineNumbers && ( - + {i + 1} - + )} - + {line.map((token, key) => ( ))} - - + +
) })} {!fromHomepage && ( {allowCollapse && totalLines - 1 > LINES_BEFORE_COLLAPSABLE && ( @@ -349,11 +328,11 @@ const Codeblock = ({ )} )} -
+ )} -
-
+ + ) } diff --git a/src/components/CommunityEvents/index.tsx b/src/components/CommunityEvents/index.tsx deleted file mode 100644 index b963a8bb03d..00000000000 --- a/src/components/CommunityEvents/index.tsx +++ /dev/null @@ -1,201 +0,0 @@ -import { useRouter } from "next/router" -import { useTranslation } from "next-i18next" -import { FaDiscord } from "react-icons/fa" -import { - Box, - Center, - Divider, - Flex, - Grid, - GridItem, - Icon, -} from "@chakra-ui/react" - -import type { Lang } from "@/lib/types" -import type { CommunityEvent } from "@/lib/interfaces" - -import { ButtonLink } from "@/components/Buttons" -import InlineLink from "@/components/Link" -import OldHeading from "@/components/OldHeading" -import Text from "@/components/OldText" -import Translation from "@/components/Translation" - -import { trackCustomEvent } from "@/lib/utils/matomo" -import { getLocaleTimestamp } from "@/lib/utils/time" - -const matomoEvent = (buttonType: string) => { - trackCustomEvent({ - eventCategory: "CommunityEventsWidget", - eventAction: "clicked", - eventName: buttonType, - }) -} - -type EventProps = { - event: CommunityEvent - type: "upcoming" | "past" -} - -const Event = ({ event, type }: EventProps) => { - const { locale } = useRouter() - const { date, title, calendarLink } = event - const options: Intl.DateTimeFormatOptions = { - year: "numeric", - month: "short", - day: "numeric", - } - - return ( - - - - {getLocaleTimestamp(locale! as Lang, date, options)} - - - - matomoEvent(type)}> - {title} - - - - ) -} - -type CommunityEventsProps = { - events: { - pastEventData: CommunityEvent[] - upcomingEventData: CommunityEvent[] - } -} - -const CommunityEvents = ({ events }: CommunityEventsProps) => { - const { locale } = useRouter() - const { t } = useTranslation("page-index") - const { pastEventData, upcomingEventData } = events - - const reversedUpcomingEventData = upcomingEventData.slice().reverse() - const reversedPastEventData = pastEventData.slice().reverse() - - return ( - -
- - - {t("page-index:community-events-content-heading")} - - - - - {t("page-index:community-events-content-2")} - -
- - - - {reversedUpcomingEventData.length ? ( - - - {reversedUpcomingEventData[0].title} - - - {getLocaleTimestamp( - locale! as Lang, - reversedUpcomingEventData[0].date, - { - year: "numeric", - month: "long", - day: "numeric", - hour12: false, - hour: "numeric", - minute: "numeric", - } - )} - - - ({Intl.DateTimeFormat().resolvedOptions().timeZone}) - - - ) : ( - - {t("page-index:community-events-no-events-planned")} - - )} - - matomoEvent("discord")} - > - - Join Discord - - {reversedUpcomingEventData[0] && ( - matomoEvent("Add to calendar")} - fontWeight={700} - > - {t("community-events-add-to-calendar")} - - )} - - - - - - {t("page-index:community-events-upcoming-calls")} - - - {reversedUpcomingEventData.slice(1).length ? ( - reversedUpcomingEventData.slice(1).map((item, idx) => { - return - }) - ) : ( - - {t("page-index:community-events-no-upcoming-calls")} - - )} - - {t("page-index:community-events-previous-calls")} - - - {reversedPastEventData.length ? ( - reversedPastEventData.map((item, idx) => { - return - }) - ) : ( - - {t("page-index:community-events-there-are-no-past-calls")} - - )} - - -
- ) -} - -export default CommunityEvents diff --git a/src/components/EnergyConsumptionChart/index.tsx b/src/components/EnergyConsumptionChart/index.tsx index 43f4d9f34c4..6f8d0008657 100644 --- a/src/components/EnergyConsumptionChart/index.tsx +++ b/src/components/EnergyConsumptionChart/index.tsx @@ -12,7 +12,6 @@ import ChartDataLabels from "chartjs-plugin-datalabels" import { useRouter } from "next/router" import { useTranslation } from "next-i18next" import { Bar } from "react-chartjs-2" -import { useBreakpointValue } from "@chakra-ui/react" import type { Lang } from "@/lib/types" @@ -21,6 +20,7 @@ import { Center } from "@/components/ui/flex" import { wrapLabel } from "@/lib/utils/charts" import { isLangRightToLeft } from "@/lib/utils/translations" +import { useBreakpointValue } from "@/hooks/useBreakpointValue" import useColorModeValue from "@/hooks/useColorModeValue" import { useIsClient } from "@/hooks/useIsClient" diff --git a/src/components/EthPriceCard.tsx b/src/components/EthPriceCard.tsx index f2cc64cfde7..3b3ab3670f5 100644 --- a/src/components/EthPriceCard.tsx +++ b/src/components/EthPriceCard.tsx @@ -2,19 +2,15 @@ import { useEffect, useState } from "react" import { useRouter } from "next/router" import { useTranslation } from "next-i18next" import { MdInfoOutline } from "react-icons/md" -import { - Box, - Flex, - type FlexProps, - Heading, - Icon, - Text, -} from "@chakra-ui/react" import type { LoadingState } from "@/lib/types" -import InlineLink from "@/components/Link" import Tooltip from "@/components/Tooltip" +import InlineLink from "@/components/ui/Link" + +import { cn } from "@/lib/utils/cn" + +import { Flex } from "./ui/flex" import { useRtlFlip } from "@/hooks/useRtlFlip" @@ -30,17 +26,16 @@ type EthPriceState = { percentChangeUSD: number } -export type EthPriceCardProps = FlexProps & { - isLeftAlign?: boolean -} - -const EthPriceCard = ({ isLeftAlign = false, ...props }: EthPriceCardProps) => { +const EthPriceCard = ({ + className, + ...props +}: React.HTMLAttributes) => { const { locale } = useRouter() const { t } = useTranslation() const [state, setState] = useState>({ loading: true, }) - const { flipForRtl } = useRtlFlip() + const { isRtl } = useRtlFlip() useEffect(() => { const fetchData = async () => { @@ -100,93 +95,65 @@ const EthPriceCard = ({ isLeftAlign = false, ...props }: EthPriceCardProps) => { const change = hasData ? formatPercentage(state.data.percentChangeUSD) : "" const tooltipContent = ( - +
{t("data-provided-by")}{" "} coingecko.com - +
) return ( - +

{t("eth-current-price")} - - - + - +

- {price} - - - + + {/* min-h-[33px] prevents jump when price loads */} + +
- {change} - - - + +
+
({t("last-24-hrs")}) - +
) diff --git a/src/components/EventCard.tsx b/src/components/EventCard.tsx index e4da86a39b6..fea404ed71d 100644 --- a/src/components/EventCard.tsx +++ b/src/components/EventCard.tsx @@ -1,13 +1,17 @@ import React from "react" import { useRouter } from "next/router" -import { useTranslation } from "react-i18next" +import { useTranslation } from "next-i18next" import { BsCalendar3 } from "react-icons/bs" import { Box, Flex, Heading, Icon } from "@chakra-ui/react" -import { Image } from "@chakra-ui/react" + +import type { EventCardProps } from "@/lib/types" import { ButtonLink } from "./Buttons" +import { TwImage } from "./Image" import Text from "./OldText" +import EventFallback from "@/public/images/events/event-placeholder.png" + const clearStyles = { content: '""', display: "block", @@ -15,18 +19,6 @@ const clearStyles = { clear: "both", } -export type EventCardProps = { - title: string - href: string - date: string - startDate: string - endDate: string - description: string - className?: string - location: string - imageUrl?: string -} - const EventCard = ({ title, href, @@ -90,14 +82,16 @@ const EventCard = ({ justifyContent="center" boxShadow="rgb(0 0 0 / 10%) 0px -1px 0px inset;" > - {title} + {imageUrl ? ( + // eslint-disable-next-line @next/next/no-img-element + {title} + ) : ( + + )}
diff --git a/src/components/ExpandableInfo.tsx b/src/components/ExpandableInfo.tsx deleted file mode 100644 index 9d5d9cb621e..00000000000 --- a/src/components/ExpandableInfo.tsx +++ /dev/null @@ -1,147 +0,0 @@ -import { motion } from "framer-motion" -import type { ReactNode } from "react" -import { MdExpandMore } from "react-icons/md" -import { - type BackgroundProps, - Box, - Center, - type ChakraProps, - Collapse, - Heading, - HStack, - Icon, - Stack, - useDisclosure, - VStack, -} from "@chakra-ui/react" - -import { Image, type ImageProps } from "@/components/Image" -import Text from "@/components/OldText" - -export type ExpandableInfoProps = ChakraProps & { - children?: ReactNode - image?: ImageProps["src"] - title: ReactNode - contentPreview: ReactNode - background: BackgroundProps["background"] - forceOpen?: boolean -} - -const ExpandableInfo = ({ - image, - title, - contentPreview, - children, - background, - forceOpen, - ...props -}: ExpandableInfoProps) => { - const { isOpen, getButtonProps, getDisclosureProps } = useDisclosure({ - defaultIsOpen: forceOpen, - }) - - const chevronFlip = { - collapsed: { - rotate: 0, - transition: { - duration: 0.1, - }, - }, - expanded: { - rotate: 180, - transition: { - duration: 0.4, - }, - }, - } - - const animateToggle = isOpen ? "expanded" : "collapsed" - - return ( - - - {image && ( - - )} - - - - - {title} - - - - {contentPreview} - - - - {!forceOpen && ( -
- -
- )} -
- - - {children} - - -
- ) -} - -export default ExpandableInfo diff --git a/src/components/FeedbackCard.tsx b/src/components/FeedbackCard.tsx index 190325d2fb4..4caf5327c24 100644 --- a/src/components/FeedbackCard.tsx +++ b/src/components/FeedbackCard.tsx @@ -75,23 +75,17 @@ const FeedbackCard = ({ prompt, isArticle, ...props }: FeedbackCardProps) => {
{!feedbackSubmitted ? ( <> - - ) : ( - )} diff --git a/src/components/FindWallet/LanguageSupportFilter.tsx b/src/components/FindWallet/LanguageSupportFilter.tsx index fe425fd92de..36f3c567e29 100644 --- a/src/components/FindWallet/LanguageSupportFilter.tsx +++ b/src/components/FindWallet/LanguageSupportFilter.tsx @@ -12,7 +12,7 @@ import { Text, } from "@chakra-ui/react" -import Select from "@/components/Select" +import Select from "@/components/ui/Select" import { getLanguageCodeName } from "@/lib/utils/intl" import { trackCustomEvent } from "@/lib/utils/matomo" diff --git a/src/components/FindWallet/WalletFilterPersona.tsx b/src/components/FindWallet/WalletFilterPersona.tsx index cfb0d6d4c3c..669fa97cb75 100644 --- a/src/components/FindWallet/WalletFilterPersona.tsx +++ b/src/components/FindWallet/WalletFilterPersona.tsx @@ -102,15 +102,23 @@ const WalletFilterPersona = ({ return ( {personas.map((persona, idx) => { return ( diff --git a/src/components/Glossary/GlossaryDefinition/index.tsx b/src/components/Glossary/GlossaryDefinition/index.tsx index 41b5179fff9..274b3e09828 100644 --- a/src/components/Glossary/GlossaryDefinition/index.tsx +++ b/src/components/Glossary/GlossaryDefinition/index.tsx @@ -1,10 +1,11 @@ import { ComponentProps } from "react" -import { type HeadingProps, Text, VStack } from "@chakra-ui/react" -import Heading from "@/components/Heading" import IdAnchor from "@/components/IdAnchor" -import InlineLink from "@/components/Link" import Translation from "@/components/Translation" +import { Stack } from "@/components/ui/flex" +import InlineLink from "@/components/ui/Link" + +import { cn } from "@/lib/utils/cn" import { DEFAULT_GLOSSARY_NS } from "@/lib/constants" @@ -25,42 +26,30 @@ const GlossaryDefinition = ({ size = "md", options = { ns: DEFAULT_GLOSSARY_NS }, }: GlossaryDefinitionProps) => { - const textStyles = size === "sm" ? { mb: 0 } : {} - - const headingPropsForAnchor = (id?: string): HeadingProps => { - if (!id) return {} - return { - scrollMarginTop: 28, - id, - "data-group": true, - position: "relative", - } as HeadingProps - } + const textClasses = size === "sm" ? "mb-0" : "" return ( - - + +

- - {/** - * `as="span"` prevents hydration warnings for strings that contain - * elements that cannot be nested inside `p` tags, like `ul` tags - * (found in some Glossary definition). - * TODO: Develop a better solution to handle this case. - */} - +

+ +
- - +
+
) } diff --git a/src/components/Hero/CallToAction.tsx b/src/components/Hero/CallToAction.tsx index e27110e354c..3d09a08d672 100644 --- a/src/components/Hero/CallToAction.tsx +++ b/src/components/Hero/CallToAction.tsx @@ -1,7 +1,12 @@ import type { ReactNode } from "react" -import { Button, type ButtonProps } from "@/components/Buttons" +import { + Button, + ButtonLink, + type ButtonProps, +} from "@/components/ui/buttons/Button" +import { cn } from "@/lib/utils/cn" import { type MatomoEventOptions, trackCustomEvent } from "@/lib/utils/matomo" export type CallToActionProps = Omit< @@ -9,22 +14,36 @@ export type CallToActionProps = Omit< "children" | "content" | "variant" | "isSecondary" > & { content: ReactNode - matomo: MatomoEventOptions + matomo?: MatomoEventOptions index: number + href?: string } export const CallToAction = ({ content, matomo, index, + className, + href, ...props }: CallToActionProps) => { - const handleClick = () => trackCustomEvent(matomo) + const handleClick = () => matomo && trackCustomEvent(matomo) const buttonProps: ButtonProps = { variant: index === 0 ? "solid" : "outline", isSecondary: index !== 0, - flex: { base: 1, md: "initial" }, + className: cn("flex-[1] md:flex-[initial]", className), + } + + if (href) { + return ( + + {content} + + ) } return ( diff --git a/src/components/Hero/ContentHero/index.tsx b/src/components/Hero/ContentHero/index.tsx index 6ecba13e23c..ba42f38da8f 100644 --- a/src/components/Hero/ContentHero/index.tsx +++ b/src/components/Hero/ContentHero/index.tsx @@ -29,6 +29,7 @@ const ContentHero = (props: ContentHeroProps) => { > { boxSize="full" style={{ objectFit: "contain" }} flex={{ base: "1 1 100%", md: "none" }} + maxHeight={451} /> diff --git a/src/components/Hero/HomeHero/index.tsx b/src/components/Hero/HomeHero/index.tsx index c4408f80b5e..e333649c95a 100644 --- a/src/components/Hero/HomeHero/index.tsx +++ b/src/components/Hero/HomeHero/index.tsx @@ -1,51 +1,37 @@ import { useTranslation } from "next-i18next" -import { Box, Heading, Stack, Text, VStack } from "@chakra-ui/react" -import type { CommonHeroProps } from "@/lib/types" +import type { ClassNameProp, CommonHeroProps } from "@/lib/types" -import { ButtonLink } from "@/components/Buttons" -import { Image } from "@/components/Image" +import { TwImage } from "@/components/Image" import Morpher from "@/components/Morpher" -export type HomeHeroProps = Pick +export type HomeHeroProps = Pick & ClassNameProp -const HomeHero = ({ heroImg }: HomeHeroProps) => { +const HomeHero = ({ heroImg, className }: HomeHeroProps) => { const { t } = useTranslation("page-index") + return ( - - - +
+ - - - - - - - {t("page-index:page-index-title")} - - {t("page-index:page-index-description")} - - {t("page-index:page-index-title-button")} - - - - - +
+
+ +
+

{t("page-index:page-index-title")}

+

+ {t("page-index:page-index-description")} +

+
+
+
) } diff --git a/src/components/Hero/HubHero/index.tsx b/src/components/Hero/HubHero/index.tsx index 09eea84930f..168bd328843 100644 --- a/src/components/Hero/HubHero/index.tsx +++ b/src/components/Hero/HubHero/index.tsx @@ -1,9 +1,10 @@ -import { Box, Heading, Stack, Text } from "@chakra-ui/react" - import type { CommonHeroProps } from "@/lib/types" import { CallToAction } from "@/components/Hero/CallToAction" -import { Image } from "@/components/Image" +import { TwImage } from "@/components/Image" +import { Stack } from "@/components/ui/flex" + +import { cn } from "@/lib/utils/cn" export type HubHeroProps = Omit @@ -21,64 +22,48 @@ const HubHero = ({ } return ( - - + {title ? ( - +

{title} - +

) : null} - - - {header} - - {description} + + {title ? ( +

{header}

+ ) : ( +

{header}

+ )} + +

{description}

{buttons?.map((button, idx) => { if (!button) return @@ -86,7 +71,7 @@ const HubHero = ({ })}
-
+ ) } diff --git a/src/components/Homepage/BentoCard.tsx b/src/components/Homepage/BentoCard.tsx new file mode 100644 index 00000000000..969c797e415 --- /dev/null +++ b/src/components/Homepage/BentoCard.tsx @@ -0,0 +1,53 @@ +import { HTMLAttributes } from "react" +import { type StaticImageData } from "next/image" + +import { TwImage } from "@/components/Image" +import { ButtonLink } from "@/components/ui/buttons/Button" + +import { cn } from "@/lib/utils/cn" + +import { ChevronNext } from "../Chevron" +import { Card, CardTitle } from "../ui/card" +import { Center } from "../ui/flex" + +export type BentoCardProps = HTMLAttributes & { + action: string + href: string + imgSrc: StaticImageData + imgWidth?: number + imgHeight?: number + title: string +} + +const BentoCard = ({ + action, + children, + className, + href, + imgSrc, + imgWidth, + imgHeight, + title, +}: BentoCardProps) => ( + +
+ +
+
+ + {title} + +

{children}

+ + {action} + +
+
+) + +export default BentoCard diff --git a/src/components/Homepage/useBentoBox.ts b/src/components/Homepage/useBentoBox.ts new file mode 100644 index 00000000000..e19f67d0667 --- /dev/null +++ b/src/components/Homepage/useBentoBox.ts @@ -0,0 +1,136 @@ +import { useTranslation } from "next-i18next" + +import { cn } from "@/lib/utils/cn" + +import ImpactImage from "@/public/images/impact_transparent.png" +import ManAndDogImage from "@/public/images/man-and-dog-playing.png" +import ManBabyWomanImage from "@/public/images/man-baby-woman.png" +import RobotBarImage from "@/public/images/robot-help-bar.png" +import MergeImage from "@/public/images/upgrades/merge.png" + +type Breakpoint = "mobile" | "lg" | "xl" +type Direction = "down" | "up" | "right" | "left" +type Color = "primary" | "accent-a" | "accent-b" | "accent-c" +type Category = "stablecoins" | "defi" | "dapps" | "networks" | "assets" +type CopyDetails = { + title: string + children: string + action: string + href: string +} + +const gradientStops = "from-20% to-60%" + +const colorOptions: Record = { + primary: cn( + gradientStops, + "from-primary/10 to-primary/5 dark:from-primary/20 dark:to-primary/10 border-primary/10" + ), + "accent-a": cn( + gradientStops, + "from-accent-a/10 to-accent-a/5 dark:from-accent-a/20 dark:to-accent-a/10 border-accent-a/10" + ), + "accent-b": cn( + gradientStops, + "from-accent-b/10 to-accent-b/5 dark:from-accent-b/20 dark:to-accent-b/10 border-accent-b/10" + ), + "accent-c": cn( + gradientStops, + "from-accent-c/10 to-accent-c/5 dark:from-accent-c/20 dark:to-accent-c/10 border-accent-c/10" + ), +} + +const flow: Record> = { + mobile: { + down: "flex-col bg-gradient-to-b", + up: "flex-col-reverse bg-gradient-to-t", + right: "flex-row bg-gradient-to-r", + left: "flex-row-reverse bg-gradient-to-l", + }, + lg: { + down: "lg:flex-col lg:bg-gradient-to-b", + up: "lg:flex-col-reverse lg:bg-gradient-to-t", + right: "lg:flex-row lg:bg-gradient-to-r", + left: "lg:flex-row-reverse lg:bg-gradient-to-l", + }, + xl: { + down: "xl:flex-col xl:bg-gradient-to-b", + up: "xl:flex-col-reverse xl:bg-gradient-to-t", + right: "xl:flex-row xl:bg-gradient-to-r", + left: "xl:flex-row-reverse xl:bg-gradient-to-l", + }, +} + +const stylesByPosition: Record = { + mobile: [ + flow.mobile.down, + flow.mobile.down, + flow.mobile.down, + flow.mobile.down, + flow.mobile.down, + ], + lg: [ + cn("lg:col-span-6 lg:row-start-2", flow.lg.up), + cn("lg:col-span-6 lg:col-start-7 lg:row-start-2", flow.lg.down), + cn("lg:col-span-12 lg:row-start-3", flow.lg.right), + cn("lg:col-span-6 lg:col-start-7 lg:row-start-4", flow.lg.up), + cn("lg:col-span-6 lg:row-start-4", flow.lg.down), + ], + xl: [ + cn("xl:col-span-7 xl:col-start-5 xl:row-start-1", flow.xl.right), + cn("xl:col-span-4 xl:col-start-2 xl:row-start-2", flow.xl.up), + cn("xl:col-span-3 xl:col-start-6 xl:row-start-2", flow.xl.down), + cn("xl:col-span-3 xl:col-start-9 xl:row-span-2 xl:row-start-2", flow.xl.up), + cn("xl:col-span-7 xl:col-start-2 xl:row-start-3", flow.xl.right), + ], +} + +const getPosition = (position: number): string => + cn( + stylesByPosition.mobile[position], + stylesByPosition.lg[position], + stylesByPosition.xl[position] + ) + +export const useBentoBox = () => { + const { t } = useTranslation("page-index") + + const getCopy = (category: Category, href: string): CopyDetails => ({ + title: t(`page-index:page-index-bento-${category}-title`), + children: t(`page-index:page-index-bento-${category}-content`), + action: t(`page-index:page-index-bento-${category}-action`), + href, + }) + + return [ + { + ...getCopy("stablecoins", "/stablecoins/"), + imgSrc: ManAndDogImage, + className: cn(colorOptions["primary"], getPosition(0)), + }, + { + ...getCopy("defi", "/defi/"), + imgSrc: ImpactImage, + imgWidth: 400, + className: cn(colorOptions["accent-c"], getPosition(1)), + }, + { + ...getCopy("networks", "/layer-2/"), + imgSrc: MergeImage, + imgWidth: 320, + className: cn(colorOptions["accent-b"], getPosition(2)), + }, + { + ...getCopy("dapps", "/dapps/"), + imgSrc: ManBabyWomanImage, + imgWidth: 324, + className: cn(colorOptions["accent-a"], getPosition(3)), + }, + { + ...getCopy("assets", "/nft/"), + imgSrc: RobotBarImage, + imgWidth: 324, + className: cn(colorOptions["primary"], getPosition(4)), + }, + ] +} diff --git a/src/components/Homepage/useHome.ts b/src/components/Homepage/useHome.ts new file mode 100644 index 00000000000..ef38077ac91 --- /dev/null +++ b/src/components/Homepage/useHome.ts @@ -0,0 +1,209 @@ +import { useState } from "react" +import { useRouter } from "next/router" +import { useTranslation } from "next-i18next" +import { FaDiscord, FaGithub, FaXTwitter } from "react-icons/fa6" + +import type { EventCardProps } from "@/lib/types" +import type { CodeExample } from "@/lib/interfaces" + +import { useBentoBox } from "@/components/Homepage/useBentoBox" +import BlockHeap from "@/components/icons/block-heap.svg" +import EthGlyphIcon from "@/components/icons/eth-glyph.svg" +import EthTokenIcon from "@/components/icons/eth-token.svg" +import PickWalletIcon from "@/components/icons/eth-wallet.svg" +import ChooseNetworkIcon from "@/components/icons/network-layers.svg" +import TryAppsIcon from "@/components/icons/phone-homescreen.svg" +import RoadmapSign from "@/components/icons/roadmap-sign.svg" +import Whitepaper from "@/components/icons/whitepaper.svg" + +import { cn } from "@/lib/utils/cn" +import { isValidDate } from "@/lib/utils/date" + +import events from "@/data/community-events.json" +import CreateWalletContent from "@/data/CreateWallet" + +import { GITHUB_REPO_URL } from "@/lib/constants" + +import SimpleDomainRegistryContent from "!!raw-loader!@/data/SimpleDomainRegistry.sol" +import SimpleTokenContent from "!!raw-loader!@/data/SimpleToken.sol" +import SimpleWalletContent from "!!raw-loader!@/data/SimpleWallet.sol" +import { useRtlFlip } from "@/hooks/useRtlFlip" + +export const useHome = () => { + const { t } = useTranslation(["common", "page-index"]) + const { locale, asPath } = useRouter() + + const [isModalOpen, setModalOpen] = useState(false) + const [activeCode, setActiveCode] = useState(0) + + const bentoItems = useBentoBox() + + const { direction, isRtl } = useRtlFlip() + + const toggleCodeExample = (id: number): void => { + setActiveCode(id) + setModalOpen(true) + } + + const codeExamples: CodeExample[] = [ + { + title: t("page-index:page-index-developers-code-example-title-0"), + description: t( + "page-index:page-index-developers-code-example-description-0" + ), + codeLanguage: "language-solidity", + code: SimpleWalletContent, + }, + { + title: t("page-index:page-index-developers-code-example-title-1"), + description: t( + "page-index:page-index-developers-code-example-description-1" + ), + codeLanguage: "language-solidity", + code: SimpleTokenContent, + }, + { + title: t("page-index:page-index-developers-code-example-title-2"), + description: t( + "page-index:page-index-developers-code-example-description-2" + ), + codeLanguage: "language-javascript", + code: CreateWalletContent, + }, + { + title: t("page-index:page-index-developers-code-example-title-3"), + description: t( + "page-index:page-index-developers-code-example-description-3" + ), + codeLanguage: "language-solidity", + code: SimpleDomainRegistryContent, + }, + ] + + const subHeroCTAs = [ + { + label: t("page-index:page-index-cta-wallet-label"), + description: t("page-index:page-index-cta-wallet-description"), + href: "/wallets/find-wallet/", + Svg: PickWalletIcon, + className: "text-primary hover:text-primary-hover", // TODO: Confirm hover style + }, + { + label: t("page-index:page-index-cta-get-eth-label"), + description: t("page-index:page-index-cta-get-eth-description"), + href: "/get-eth/", + Svg: EthTokenIcon, + className: "text-accent-a hover:text-accent-a-hover", + }, + { + label: t("page-index:page-index-cta-networks-label"), + description: t("page-index:page-index-cta-networks-description"), + href: "/layer-2/", // TODO: Update with new networks page when ready + Svg: ChooseNetworkIcon, + className: "text-accent-b hover:text-accent-b-hover", + }, + { + label: t("page-index:page-index-cta-dapps-label"), + description: t("page-index:page-index-cta-dapps-description"), + href: "/dapps/", + Svg: TryAppsIcon, + className: cn( + "text-accent-c hover:text-accent-c-hover", + isRtl && "[&_svg]:-scale-x-100" + ), + }, + ] + + const popularTopics = [ + { + label: t("page-index:page-index-popular-topics-ethereum"), + Svg: EthTokenIcon, + href: "/what-is-ethereum/", + }, + { + label: t("page-index:page-index-popular-topics-wallets"), + Svg: PickWalletIcon, + href: "/wallets/", + }, + { + label: t("page-index:page-index-popular-topics-start"), + Svg: BlockHeap, + href: "/guides/", + }, + { + label: t("page-index:page-index-popular-topics-whitepaper"), + Svg: Whitepaper, + className: cn(isRtl && "[&_svg]:-scale-x-100"), + href: "/whitepaper/", + }, + { + label: t("page-index:page-index-popular-topics-roadmap"), + Svg: RoadmapSign, + className: cn(isRtl && "[&_svg]:-scale-x-100"), + href: "/roadmap/", + }, + ] + + const upcomingEvents = events + .filter((event) => { + const isValid = isValidDate(event.endDate) + const beginningOfEndDate = new Date(event.endDate).getTime() + const endOfEndDate = beginningOfEndDate + 24 * 60 * 60 * 1000 + const isUpcoming = endOfEndDate >= new Date().getTime() + return isValid && isUpcoming + }) + .sort( + (a, b) => new Date(a.endDate).getTime() - new Date(b.endDate).getTime() + ) + .slice(0, 3) as EventCardProps[] // Show 3 events ending soonest + + const joinActions = [ + { + Svg: EthGlyphIcon, + label: t("page-index:page-index-join-action-contribute-label"), + href: "/contributing/", + className: "text-accent-c hover:text-accent-c-hover", + description: t( + "page-index:page-index-join-action-contribute-description" + ), + }, + { + Svg: FaGithub, + label: "GitHub", + href: GITHUB_REPO_URL, + className: "text-accent-a hover:text-accent-a-hover", + description: t("page-index:page-index-join-action-github-description"), + }, + { + Svg: FaDiscord, + label: "Discord", + href: "/discord/", + className: "text-primary hover:text-primary-hover", + description: t("page-index:page-index-join-action-discord-description"), + }, + { + Svg: FaXTwitter, + label: "X", + href: "https://x.com/EthDotOrg", + className: "text-accent-b hover:text-accent-b-hover", + description: t("page-index:page-index-join-action-twitter-description"), + }, + ] + + return { + t, + locale, + asPath, + dir: direction, + isModalOpen, + setModalOpen, + activeCode, + toggleCodeExample, + codeExamples, + subHeroCTAs, + popularTopics, + upcomingEvents, + joinActions, + bentoItems, + } +} diff --git a/src/components/Image.tsx b/src/components/Image.tsx index a93e493726a..3c67258b35a 100644 --- a/src/components/Image.tsx +++ b/src/components/Image.tsx @@ -33,10 +33,16 @@ const imageProps: (keyof NextImageProps)[] = [ "useMap", ] +const isStaticImageData = (src: ImageProps["src"]): src is StaticImageData => { + return typeof src === "object" && "blurDataURL" in src +} + const DefaultNextImage = (props: ImageProps) => { - const hasBlurData = !!( - (props.src as StaticImageData).blurDataURL || props.blurDataURL - ) + if (isStaticImageData(props.src)) { + return + } + + const hasBlurData = !!props.blurDataURL return } diff --git a/src/components/LanguagePicker/index.tsx b/src/components/LanguagePicker/index.tsx index 0bcb653a176..b1c4b06e6df 100644 --- a/src/components/LanguagePicker/index.tsx +++ b/src/components/LanguagePicker/index.tsx @@ -1,5 +1,5 @@ import { useRouter } from "next/router" -import { useTranslation } from "react-i18next" +import { useTranslation } from "next-i18next" import { BaseLink } from "@/components/Link" diff --git a/src/components/Layer2/Layer2Onboard.tsx b/src/components/Layer2/Layer2Onboard.tsx index cfce20bb152..e9864e9b492 100644 --- a/src/components/Layer2/Layer2Onboard.tsx +++ b/src/components/Layer2/Layer2Onboard.tsx @@ -13,6 +13,7 @@ import type { ChildOnlyProp } from "@/lib/types" import { Image } from "@/components/Image" +import { cn } from "@/lib/utils/cn" import { trackCustomEvent } from "@/lib/utils/matomo" // Data @@ -26,7 +27,7 @@ import { ButtonLink } from "../Buttons" import InlineLink from "../Link" import OldHeading from "../OldHeading" import Text from "../OldText" -import Select, { SelectOnChange } from "../Select" +import Select, { SelectOnChange } from "../ui/Select" const Flex50 = (props: ChildOnlyProp) => ( @@ -213,7 +214,12 @@ const Layer2Onboard = ({ } return ( - +
- +
) } diff --git a/src/components/LeftNavBar/index.tsx b/src/components/LeftNavBar/index.tsx index 2c50164fe70..ee654d9280e 100644 --- a/src/components/LeftNavBar/index.tsx +++ b/src/components/LeftNavBar/index.tsx @@ -1,68 +1,47 @@ -import { calc, Flex, type FlexProps, type HeadingProps } from "@chakra-ui/react" - import type { ToCItem } from "@/lib/types" import ButtonDropdown, { - ButtonDropdownProps, List as ButtonDropdownList, } from "@/components/ButtonDropdown" -import OldHeading from "@/components/OldHeading" import Translation from "@/components/Translation" import UpgradeTableOfContents from "@/components/UpgradeTableOfContents" -export const H2 = (props: HeadingProps) => ( - -) - -export const StyledButtonDropdown = ({ - list, - ...rest -}: FlexProps & Pick) => ( - - - -) +import { cn } from "@/lib/utils/cn" -type LeftNavBarProps = FlexProps & { +export type LeftNavBarProps = { dropdownLinks?: ButtonDropdownList maxDepth?: number tocItems: ToCItem[] + className?: string } const LeftNavBar = ({ dropdownLinks, maxDepth = 1, tocItems, + className, ...props }: LeftNavBarProps) => { return ( - - {dropdownLinks && } -

+ {dropdownLinks && ( +
+ +
+ )} +

-

+ {tocItems && ( )} -
+ ) } diff --git a/src/components/Logo/Logo.stories.tsx b/src/components/Logo/Logo.stories.tsx index 989dff7c1aa..66a8be0858a 100644 --- a/src/components/Logo/Logo.stories.tsx +++ b/src/components/Logo/Logo.stories.tsx @@ -13,7 +13,5 @@ export default meta type Story = StoryObj export const Logo: Story = { - render: () => ( - - ), -} \ No newline at end of file + render: () => , +} diff --git a/src/components/MainArticle.tsx b/src/components/MainArticle.tsx index 3ce72e677d4..cbe807d47a8 100644 --- a/src/components/MainArticle.tsx +++ b/src/components/MainArticle.tsx @@ -1,9 +1,16 @@ -import { Box, type BoxProps } from "@chakra-ui/react" +import { cn } from "@/lib/utils/cn" import { MAIN_CONTENT_ID } from "@/lib/constants" -const MainArticle = (props: BoxProps) => ( - +const MainArticle = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
) export default MainArticle diff --git a/src/components/MdComponents.tsx b/src/components/MdComponents.tsx deleted file mode 100644 index 9affa173a57..00000000000 --- a/src/components/MdComponents.tsx +++ /dev/null @@ -1,253 +0,0 @@ -import { ComponentProps } from "react" -import { - Badge, - Box, - type BoxProps, - chakra, - Divider as ChakraDivider, - Flex, - type FlexProps, - type HeadingProps, - ListItem, - OrderedList, - Text, - UnorderedList, - useToken, -} from "@chakra-ui/react" - -import type { ChildOnlyProp } from "@/lib/types" - -import ButtonDropdown, { - type ButtonDropdownProps, -} from "@/components/ButtonDropdown" -import { ButtonLink } from "@/components/Buttons" -import Contributors from "@/components/Contributors" -import MarkdownImage from "@/components/MarkdownImage" -import OldHeading from "@/components/OldHeading" -import { mdxTableComponents } from "@/components/Table" -import TooltipLink from "@/components/TooltipLink" -import YouTube from "@/components/YouTube" - -import ContributorsQuizBanner from "./Banners/ContributorsQuizBanner" -import GlossaryTooltip from "./Glossary/GlossaryTooltip" -import { StandaloneQuizWidget } from "./Quiz/QuizWidget" -import Card from "./Card" -import DocLink from "./DocLink" -import Emoji from "./Emoji" -import ExpandableCard from "./ExpandableCard" -import FeaturedText from "./FeaturedText" -import IdAnchor from "./IdAnchor" -import InfoBanner from "./InfoBanner" -import IssuesList from "./IssuesList" -import LocaleDateTime from "./LocaleDateTime" -import MainArticle from "./MainArticle" - -/** - * Base HTML elements - */ -const headingPropsForAnchor = (id?: string): HeadingProps => { - if (!id) return {} - return { - scrollMarginTop: 28, - id, - "data-group": true, - position: "relative", - } as HeadingProps -} - -export const commonHeadingProps = (id?: string): HeadingProps => ({ - fontWeight: 700, - lineHeight: 1.4, - ...headingPropsForAnchor(id), -}) - -export const Heading1 = ({ children, ...rest }: HeadingProps) => ( - - {children} - -) - -export const Heading2 = ({ id, children, ...rest }: HeadingProps) => ( - - - {children} - -) - -export const Heading3 = ({ id, children, ...rest }: HeadingProps) => ( - - - {children} - -) - -export const Heading4 = ({ id, children, ...rest }: HeadingProps) => ( - - - {children} - -) - -export const Pre = (props: ChildOnlyProp) => ( - -) - -export const Paragraph = (props: ChildOnlyProp) => ( - -) - -export const HR = () => ( - -) - -// All base html element components -export const htmlElements = { - a: TooltipLink, - div: Box, - h1: Heading1, - h2: Heading2, - h3: Heading3, - h4: Heading4, - hr: HR, - img: MarkdownImage, - li: ListItem, - ol: OrderedList, - p: Paragraph, - pre: Pre, - time: LocaleDateTime, - ul: UnorderedList, - ...mdxTableComponents, -} - -/** - * Custom React components - */ -export const Page = (props: FlexProps) => ( - -) - -export const Title = (props: ChildOnlyProp) => - -export const ContentContainer = (props: Pick) => { - const lgBp = useToken("breakpoints", "lg") - - return ( - - ) -} - -export const MobileButton = (props: ChildOnlyProp) => { - const borderColor = useToken("colors", "border") - return ( - - ) -} - -export const StyledButtonDropdown = ({ - list, - ...rest -}: FlexProps & Pick) => ( - - - -) - -export const MobileButtonDropdown = ( - props: ComponentProps -) => - -export const Divider = () => - -// All custom React components -export const reactComponents = { - Badge, - ButtonLink, - Card, - ContentContainer, - Contributors, - ContributorsQuizBanner, - Divider, - DocLink, - Emoji, - ExpandableCard, - FeaturedText, - GlossaryTooltip, - InfoBanner, - MobileButton, - MobileButtonDropdown, - Page, - QuizWidget: StandaloneQuizWidget, - StyledButtonDropdown, - IssuesList, - Title, - YouTube, -} - -/** - * All base markdown components as default export - */ -const MdComponents = { - ...htmlElements, - ...reactComponents, -} - -export default MdComponents diff --git a/src/components/MdComponents/MdComponents.stories.tsx b/src/components/MdComponents/MdComponents.stories.tsx new file mode 100644 index 00000000000..9d101a7334d --- /dev/null +++ b/src/components/MdComponents/MdComponents.stories.tsx @@ -0,0 +1,129 @@ +import pickBy from "lodash/pickBy" +import type { Meta, StoryObj } from "@storybook/react/*" + +import type { List as ButtonDropdownList } from "@/components/ButtonDropdown" + +import { viewportModes } from "../../../.storybook/modes" + +import MdComponentSet from "." + +const meta = { + title: "Molecules / Display Content / MdComponents", + parameters: { + layout: "none", + chromatic: { + modes: pickBy(viewportModes, (args) => + ["md", "lg"].includes(args.viewport) + ), + }, + }, +} satisfies Meta + +export default meta + +const { + ContentContainer, + h1: Heading1, + h2: Heading2, + h3: Heading3, + h4: Heading4, + Title, + p: Paragraph, + FeaturedText, + Divider, + hr: HR, + pre: Pre, + Page, + MobileButton, + MobileButtonDropdown, +} = MdComponentSet + +const Para = () => ( + + Ether (also known by its ticker symbol, ETH) is the native currency + transacted on Ethereum. ETH is needed to pay for usage of the Ethereum + network (in the form of transaction fees). ETH is also used to secure the + network with staking. When people talk about the price of Ethereum, + they're referring to ETH the asset. + +) + +export const MdComponents: StoryObj = { + render: () => ( +
+ + + + + + Heading1 + + Heading2 + + Heading3 + + Heading4 + + Title + + +
Lots of coding here
+
+ Feature Text +
+
+
+ ), +} + +const roadmapDropdownLinks: ButtonDropdownList = { + text: "nav-roadmap-options", + ariaLabel: "nav-roadmap-options-alt", + items: [ + { + text: "nav-roadmap-home", + href: "/roadmap/", + matomo: { + eventCategory: `Roadmap dropdown`, + eventAction: `Clicked`, + eventName: "clicked roadmap home", + }, + }, + { + text: "nav-roadmap-security", + href: "/roadmap/security", + matomo: { + eventCategory: `Roadmap security dropdown`, + eventAction: `Clicked`, + eventName: "clicked roadmap security", + }, + }, + { + text: "nav-roadmap-scaling", + href: "/roadmap/scaling", + matomo: { + eventCategory: `Roadmap scaling dropdown`, + eventAction: `Clicked`, + eventName: "clicked roadmap scaling home", + }, + }, + { + text: "nav-roadmap-user-experience", + href: "/roadmap/user-experience/", + matomo: { + eventCategory: `Roadmap user experience dropdown`, + eventAction: `Clicked`, + eventName: "clicked roadmap user experience home", + }, + }, + { + text: "nav-roadmap-future-proofing", + href: "/roadmap/future-proofing", + matomo: { + eventCategory: `Roadmap future-proofing dropdown`, + eventAction: `Clicked`, + eventName: "clicked roadmap future-proofing home", + }, + }, + ], +} diff --git a/src/components/MdComponents/index.tsx b/src/components/MdComponents/index.tsx new file mode 100644 index 00000000000..09ff6d9638b --- /dev/null +++ b/src/components/MdComponents/index.tsx @@ -0,0 +1,220 @@ +import { ComponentProps, type HTMLAttributes } from "react" +import { Badge, Box, type BoxProps } from "@chakra-ui/react" + +import type { ChildOnlyProp } from "@/lib/types" + +import ButtonDropdown, { + type ButtonDropdownProps, +} from "@/components/ButtonDropdown" +import Contributors from "@/components/Contributors" +import MarkdownImage from "@/components/MarkdownImage" +import TooltipLink from "@/components/TooltipLink" +import YouTube from "@/components/YouTube" + +import { cn } from "@/lib/utils/cn" + +import ContributorsQuizBanner from "../Banners/ContributorsQuizBanner" +import Card from "../Card" +import DocLink from "../DocLink" +import Emoji from "../Emoji" +import ExpandableCard from "../ExpandableCard" +import FeaturedText from "../FeaturedText" +import GlossaryTooltip from "../Glossary/GlossaryTooltip" +import IdAnchor from "../IdAnchor" +import InfoBanner from "../InfoBanner" +import IssuesList from "../IssuesList" +import LocaleDateTime from "../LocaleDateTime" +import MainArticle from "../MainArticle" +import { StandaloneQuizWidget } from "../Quiz/QuizWidget" +import { ButtonLink } from "../ui/buttons/Button" +import { Flex } from "../ui/flex" +import { ListItem, OrderedList, UnorderedList } from "../ui/list" +import { mdxTableComponents } from "../ui/Table" + +export const commonHeadingAttributes = (className: string, id?: string) => ({ + id, + className: cn( + "font-bold leading-xs my-8", + id && "scroll-mt-28 relative", + className + ), + "data-group": !!id || undefined, +}) + +type HeadingProps = HTMLAttributes + +export const Heading1 = ({ children, className, ...rest }: HeadingProps) => ( +

+ {children} +

+) + +export const Heading2 = ({ + id, + children, + className, + ...rest +}: HeadingProps) => ( +

+ + {children} +

+) + +export const Heading3 = ({ + id, + children, + className, + ...rest +}: HeadingProps) => ( +

+ + {children} +

+) + +export const Heading4 = ({ + id, + children, + className, + ...rest +}: HeadingProps) => ( +

+ + {children} +

+) + +export const Pre = (props: ChildOnlyProp) => ( +
+)
+
+export const Paragraph = (props: ChildOnlyProp) => (
+  

+) + +export const HR = () => ( +


+) + +// All base html element components +export const htmlElements = { + a: TooltipLink, + div: Box, + h1: Heading1, + h2: Heading2, + h3: Heading3, + h4: Heading4, + hr: HR, + img: MarkdownImage, + li: ListItem, + ol: OrderedList, + p: Paragraph, + pre: Pre, + time: LocaleDateTime, + ul: UnorderedList, + ...mdxTableComponents, +} + +/** + * Custom React components + */ +export const Page = ({ + className, + ...props +}: HTMLAttributes) => ( + +) + +export const Title = (props: ChildOnlyProp) => ( + +) + +export const ContentContainer = (props: Pick) => { + return ( + + ) +} + +export const MobileButton = (props: ChildOnlyProp) => { + return ( +
+ ) +} + +export const StyledButtonDropdown = ({ + list, + className, + ...rest +}: HTMLAttributes & Pick) => ( + + + +) + +export const MobileButtonDropdown = ({ + className, + ...props +}: ComponentProps) => ( + +) + +export const Divider = () => ( +
+) + +// All custom React components +export const reactComponents = { + Badge, + ButtonLink, + Card, + ContentContainer, + Contributors, + ContributorsQuizBanner, + Divider, + DocLink, + Emoji, + ExpandableCard, + FeaturedText, + GlossaryTooltip, + InfoBanner, + MobileButton, + MobileButtonDropdown, + Page, + QuizWidget: StandaloneQuizWidget, + StyledButtonDropdown, + IssuesList, + Title, + YouTube, +} + +/** + * All base markdown components as default export + */ +const MdComponents = { + ...htmlElements, + ...reactComponents, +} + +export default MdComponents diff --git a/src/components/MeetupList.tsx b/src/components/MeetupList.tsx index 12761645b1e..89f9df8994b 100644 --- a/src/components/MeetupList.tsx +++ b/src/components/MeetupList.tsx @@ -1,29 +1,21 @@ import { useState } from "react" import sortBy from "lodash/sortBy" import { FaChevronRight } from "react-icons/fa6" -import { - Box, - Flex, - Icon, - LinkBox, - LinkOverlay, - List, - ListItem, - useToken, - VisuallyHidden, -} from "@chakra-ui/react" import Emoji from "@/components/Emoji" import InfoBanner from "@/components/InfoBanner" -import Input from "@/components/Input" -import InlineLink, { BaseLink } from "@/components/Link" -import Text from "@/components/OldText" import Translation from "@/components/Translation" +import { cn } from "@/lib/utils/cn" import { trackCustomEvent } from "@/lib/utils/matomo" import meetups from "@/data/community-meetups.json" +import Input from "../../tailwind/ui/Input" + +import { Flex } from "./ui/flex" +import InlineLink, { BaseLink } from "./ui/Link" + export interface Meetup { title: string emoji: string @@ -59,89 +51,55 @@ const MeetupList = () => { }) } - const primaryBaseColor = useToken("colors", "primary.base") - return ( - +
{/* hidden for attachment to input only */} - - - +
    {filteredMeetups.map((meetup, idx) => ( - - - - {idx + 1} - - - + +
    {idx + 1}
    +
    +

    {meetup.title} - - +

    +
    - + - - {meetup.location} - +

    {meetup.location}

    - - + + -
    + ))} - - +
+
{!filteredMeetups.length && ( {" "} @@ -150,8 +108,8 @@ const MeetupList = () => { )} - - +
+
) } diff --git a/src/components/Morpher.tsx b/src/components/Morpher.tsx index 36e157bad76..0a8f7c91d87 100644 --- a/src/components/Morpher.tsx +++ b/src/components/Morpher.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from "react" -import { useBreakpointValue } from "@chakra-ui/react" +import { useMediaQuery } from "usehooks-ts" -import { Button } from "@/components/Buttons" +import { Button } from "@/components/ui/buttons/Button" import { DESKTOP_LANGUAGE_BUTTON_NAME, @@ -125,6 +125,8 @@ const Morpher = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, []) + const isLarge = useMediaQuery("(min-width: 48rem)") // TW md breakpoint, 768px + const handleMobileClick = () => { if (!document) return ;(document.getElementById(HAMBURGER_BUTTON_ID) as HTMLButtonElement).click() @@ -147,25 +149,16 @@ const Morpher = () => { ).click() } - const handleClick = - useBreakpointValue({ - base: handleMobileClick, - md: handleDesktopClick, - }) || handleDesktopClick - return ( - + <> + + ) } diff --git a/src/components/Nav/Desktop/index.tsx b/src/components/Nav/Desktop/index.tsx index 92214ca540c..d12980e3d33 100644 --- a/src/components/Nav/Desktop/index.tsx +++ b/src/components/Nav/Desktop/index.tsx @@ -3,14 +3,16 @@ import { useRouter } from "next/router" import { useTranslation } from "next-i18next" import { BsTranslate } from "react-icons/bs" import { MdBrightness2, MdWbSunny } from "react-icons/md" -import { HStack, useColorModeValue, useEventListener } from "@chakra-ui/react" -import { IconButton } from "@/components/Buttons" import LanguagePicker from "@/components/LanguagePicker" import { Button } from "@/components/ui/buttons/Button" +import { HStack } from "@/components/ui/flex" import { DESKTOP_LANGUAGE_BUTTON_NAME } from "@/lib/constants" +import useColorModeValue from "@/hooks/useColorModeValue" +import { useEventListener } from "@/hooks/useEventListener" + type DesktopNavMenuProps = { toggleColorMode: () => void } @@ -20,20 +22,13 @@ const DesktopNavMenu = ({ toggleColorMode }: DesktopNavMenuProps) => { const { locale } = useRouter() const languagePickerRef = useRef(null) - const ThemeIcon = useColorModeValue(, ) + const ThemeIcon = useColorModeValue(MdBrightness2, MdWbSunny) const themeIconAriaLabel = useColorModeValue( + // TODO: Add i18n support "Switch to Dark Theme", "Switch to Light Theme" ) - const desktopHoverFocusStyles = { - "& > svg": { - transform: "rotate(10deg)", - color: "primary.hover", - transition: "transform 0.5s, color 0.2s", - }, - } - /** * Adds a keydown event listener to toggle color mode (ctrl|cmd + \) * or open the language picker (\). @@ -52,22 +47,16 @@ const DesktopNavMenu = ({ toggleColorMode }: DesktopNavMenuProps) => { }) return ( - - + {/* Locale-picker menu */} @@ -75,7 +64,7 @@ const DesktopNavMenu = ({ toggleColorMode }: DesktopNavMenuProps) => { name={DESKTOP_LANGUAGE_BUTTON_NAME} ref={languagePickerRef} variant="ghost" - className="gap-0 px-2 text-body transition-colors duration-200 active:bg-primary-low-contrast active:text-primary-hover data-[state='open']:bg-primary-low-contrast data-[state='open']:text-primary-hover xl:px-3 [&>svg]:transition-transform [&>svg]:duration-500 [&_svg]:hover:rotate-12" + className="gap-0 px-2 text-body transition-transform duration-500 active:bg-primary-low-contrast active:text-primary-hover data-[state='open']:bg-primary-low-contrast data-[state='open']:text-primary-hover xl:px-3 [&_svg]:transition-transform [&_svg]:duration-500 [&_svg]:hover:rotate-12" > diff --git a/src/components/Nav/Dropdown.tsx b/src/components/Nav/Dropdown.tsx deleted file mode 100644 index 1108cf0cc8f..00000000000 --- a/src/components/Nav/Dropdown.tsx +++ /dev/null @@ -1,178 +0,0 @@ -import React, { createRef, useContext, useState } from "react" -import { MdExpandMore } from "react-icons/md" -import { Box, Fade, Flex, Icon, ListItem } from "@chakra-ui/react" - -import { BaseLink, type LinkProps } from "../Link" - -import { NavSectionDetail } from "./types" - -import { useOnClickOutside } from "@/hooks/useOnClickOutside" - -const NavLink = (props: LinkProps) => ( - -) - -type DropdownContext = { - isOpen: boolean - toggle: () => void - close: () => void - tabInteractionHandler: ( - e: React.KeyboardEvent, - shouldClose: boolean - ) => void -} - -const DropdownContext = React.createContext(null) - -export type NavDropdownProps = { - children?: React.ReactNode - section: NavSectionDetail -} - -const NavDropdown = ({ children, section }: NavDropdownProps) => { - const [isOpen, setIsOpen] = useState(false) - - const ref = createRef() - - const toggle = () => setIsOpen((isOpen) => !isOpen) - const close = () => setIsOpen(false) - - useOnClickOutside(ref, () => setIsOpen(false)) - - // Toggle on `enter` key - const onKeyDownHandler = (e: React.KeyboardEvent): void => { - if (e.keyCode === 13) { - setIsOpen(!isOpen) - } else if (e.shiftKey && e.keyCode === 9) { - setIsOpen(false) - } - } - - const tabInteractionHandler = ( - e: React.KeyboardEvent, - shouldClose: boolean - ): void => { - if (shouldClose) { - e.keyCode === 9 && !e.shiftKey && setIsOpen(false) - } - } - - const ariaLabel = section.ariaLabel || section.label - - return ( - - - toggle()} - onKeyDown={onKeyDownHandler} - tabIndex={0} - role="button" - aria-expanded={isOpen ? "true" : "false"} - alignItems="center" - cursor="pointer" - py={2} - _hover={{ - "& > svg": { - fill: "currentColor", - }, - }} - > - {section.label} - - - - {children} - - - - ) -} - -type ItemProps = { - children?: React.ReactNode - isLast?: boolean -} - -const Item = ({ children, isLast = false, ...rest }: ItemProps) => { - const context = useContext(DropdownContext) - - return ( - context?.close()} - onKeyDown={(e) => context?.tabInteractionHandler(e, isLast)} - m={0} - color="inherit" - _hover={{ - bg: "dropdownBackgroundHover", - color: "text", - }} - > - {children} - - ) -} - -type TitleProps = { - children?: React.ReactNode -} - -const Title = (props: TitleProps) => { - return ( - - ) -} - -export default Object.assign(NavDropdown, { Link: NavLink, Item, Title }) diff --git a/src/components/Nav/Menu/ItemContent.tsx b/src/components/Nav/Menu/ItemContent.tsx index af6bf7a64cc..2be0ea6a23b 100644 --- a/src/components/Nav/Menu/ItemContent.tsx +++ b/src/components/Nav/Menu/ItemContent.tsx @@ -1,11 +1,6 @@ -import { useRouter } from "next/router" -import { Box, Text } from "@chakra-ui/react" - -import { cleanPath } from "@/lib/utils/url" - import type { Level, NavItem } from "../types" -import { useNavMenuColors } from "@/hooks/useNavMenuColors" +import { navMenuVariants } from "./MenuContent" type ItemProps = { item: NavItem @@ -13,25 +8,14 @@ type ItemProps = { } const ItemContent = ({ item, lvl }: ItemProps) => { - const { label, description, ...action } = item - const { asPath } = useRouter() - const menuColors = useNavMenuColors() - - const isLink = "href" in action - const isActivePage = isLink && cleanPath(asPath) === action.href + const { label, description } = item + const { linkSubtext } = navMenuVariants({ level: lvl }) return ( - - - {label} - - - {description} - - +
+

{label}

+

{description}

+
) } diff --git a/src/components/Nav/Menu/MenuContent.tsx b/src/components/Nav/Menu/MenuContent.tsx index 2c075949c23..c3ba06030fb 100644 --- a/src/components/Nav/Menu/MenuContent.tsx +++ b/src/components/Nav/Menu/MenuContent.tsx @@ -1,12 +1,52 @@ import { motion } from "framer-motion" -import { Box } from "@chakra-ui/react" +import { tv } from "tailwind-variants" import { Content } from "@radix-ui/react-navigation-menu" +import { cn } from "@/lib/utils/cn" + import { NavItem, NavSections } from "../types" import SubMenu from "./SubMenu" import { useNavMenu } from "./useNavMenu" +export const navMenuVariants = tv({ + slots: { + base: "text-body", + item: "has-[button[data-state=open]]:rounded-s-md has-[button[data-state=open]]:rounded-e-none has-[button[data-state=open]]:-me-2 has-[button[data-state=open]]:pe-2", + link: "group w-full relative py-4 hover:text-menu-active [&:hover_p]:text-menu-active focus-visible:text-menu-active [&:focus-visible_p]:text-menu-active hover:outline-0 rounded-md hover:shadow-none focus-visible:outline-0 focus-visible:rounded-md focus-visible:shadow-none", + linkSubtext: "text-sm", + submenu: "grid h-full w-full grid-cols-1", + }, + variants: { + level: { + 1: { + submenu: "grid-cols-3 bg-menu-1-background", + item: "has-[button[data-state=open]]:bg-menu-1-active-background", + link: "data-[active=true]:bg-menu-1-active-background hover:bg-menu-1-active-background focus-visible:bg-menu-1-active-background", + linkSubtext: "group-[data-active=true]:text-menu-1-subtext", + }, + 2: { + submenu: "grid-cols-2 bg-menu-2-background", + item: "has-[button[data-state=open]]:bg-menu-2-active-background", + link: "hover:bg-menu-2-active-background focus-visible:bg-menu-2-active-background data-[active=true]:bg-menu-2-active-background", + linkSubtext: "group-[data-active=true]:text-menu-2-subtext", + }, + 3: { + submenu: "grid-cols-1 bg-menu-3-background", + item: "has-[button[data-state=open]]:bg-menu-3-active-background", + link: "data-[active=true]:bg-menu-3-active-background hover:bg-menu-3-active-background", + linkSubtext: "group-[data-active=true]:text-menu-3-subtext", + }, + 4: { + submenu: "grid-cols-1 bg-menu-4-background", + item: "has-[button[data-state=open]]:bg-menu-4-active-background", + link: "data-[active=true]:bg-menu-4-active-background hover:bg-menu-4-active-background", + linkSubtext: "group-[data-active=true]:text-menu-4-subtext", + }, + }, + }, +}) + type MenuContentProps = { items: NavItem[] isOpen: boolean @@ -15,23 +55,19 @@ type MenuContentProps = { // Desktop Menu content const MenuContent = ({ items, isOpen, sections }: MenuContentProps) => { - const { activeSection, containerVariants, menuColors, onClose } = - useNavMenu(sections) + const { activeSection, containerVariants, onClose } = useNavMenu(sections) + const { base } = navMenuVariants() return ( - { activeSection={activeSection} onClose={onClose} /> - + ) } diff --git a/src/components/Nav/Menu/NextChevron.tsx b/src/components/Nav/Menu/NextChevron.tsx deleted file mode 100644 index 425d211b1bb..00000000000 --- a/src/components/Nav/Menu/NextChevron.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { useRouter } from "next/router" -import { MdChevronLeft, MdChevronRight } from "react-icons/md" -import { Icon, type IconProps } from "@chakra-ui/react" - -import type { Lang } from "@/lib/types" - -import { isLangRightToLeft } from "@/lib/utils/translations" - -const NextChevron = (props: IconProps) => { - const { locale } = useRouter() - const isRtl = isLangRightToLeft(locale! as Lang) - return -} - -export default NextChevron diff --git a/src/components/Nav/Menu/SubMenu.tsx b/src/components/Nav/Menu/SubMenu.tsx index e53f2a0f5ae..886b5f8f09b 100644 --- a/src/components/Nav/Menu/SubMenu.tsx +++ b/src/components/Nav/Menu/SubMenu.tsx @@ -1,13 +1,5 @@ import { AnimatePresence, motion } from "framer-motion" import NextLink from "next/link" -import { - Box, - Button, - Grid, - Icon, - ListItem, - UnorderedList, -} from "@chakra-ui/react" import { Content, Item, @@ -18,16 +10,19 @@ import { Viewport, } from "@radix-ui/react-navigation-menu" -import { ButtonProps } from "@/components/Buttons" -import Link from "@/components/Link" +import { ChevronNext } from "@/components/Chevron" +import { Button } from "@/components/ui/buttons/Button" +import { BaseLink } from "@/components/ui/Link" +import { ListItem, UnorderedList } from "@/components/ui/list" +import { cn } from "@/lib/utils/cn" import { trackCustomEvent } from "@/lib/utils/matomo" import { cleanPath } from "@/lib/utils/url" import type { Level, NavItem, NavSectionKey } from "../types" import ItemContent from "./ItemContent" -import NextChevron from "./NextChevron" +import { navMenuVariants } from "./MenuContent" import { useSubMenu } from "./useSubMenu" type LvlContentProps = { @@ -47,77 +42,41 @@ type LvlContentProps = { * @returns The JSX element representing the menu content. */ const SubMenu = ({ lvl, items, activeSection, onClose }: LvlContentProps) => { - const { asPath, locale, menuColors, menuVariants, PADDING } = useSubMenu() + const { asPath, locale, menuVariants } = useSubMenu() + const { submenu, item: itemClasses, link } = navMenuVariants({ level: lvl }) if (lvl > 3) return null - const templateColumns = `repeat(${4 - lvl}, 1fr)` - return ( - - + {items.map((item) => { - const { label, icon, ...action } = item + const { label, icon: Icon, ...action } = item const subItems = action.items || [] const isLink = "href" in action const isActivePage = isLink && cleanPath(asPath) === action.href - const activeStyles = { - outline: "none", - rounded: "md", - "p, svg": { color: menuColors.highlight }, - bg: menuColors.lvl[lvl].activeBackground, - boxShadow: "none", - } - const buttonProps: ButtonProps = { - color: menuColors.body, - leftIcon: lvl === 1 && icon ? : undefined, - rightIcon: isLink ? undefined : , - position: "relative", - w: "full", - me: -PADDING, - sx: { - "span:first-of-type": { m: 0, me: 4 }, // Spacing for icon - }, - py: PADDING, - bg: isActivePage - ? menuColors.lvl[lvl].activeBackground - : "none", - _hover: activeStyles, - _focus: activeStyles, - variant: "ghost", - } + + const buttonClasses = cn("no-underline text-body", link()) + return ( - + {isLink ? ( ) : ( <> - - +
- +
)} @@ -161,7 +128,7 @@ const SubMenu = ({ lvl, items, activeSection, onClose }: LvlContentProps) => {
-
+
) diff --git a/src/components/Nav/Menu/index.tsx b/src/components/Nav/Menu/index.tsx index 71c8a954dfb..4b5fa415a43 100644 --- a/src/components/Nav/Menu/index.tsx +++ b/src/components/Nav/Menu/index.tsx @@ -1,6 +1,5 @@ import { BaseHTMLAttributes } from "react" import { motion } from "framer-motion" -import dynamic from "next/dynamic" import { Item, List, @@ -16,6 +15,7 @@ import { MAIN_NAV_ID, SECTION_LABELS } from "@/lib/constants" import { Button } from "../../ui/buttons/Button" import type { NavSections } from "../types" +import MenuContent from "./MenuContent" import { useNavMenu } from "./useNavMenu" type NavMenuProps = BaseHTMLAttributes & { @@ -26,8 +26,6 @@ const Menu = ({ sections, ...props }: NavMenuProps) => { const { activeSection, direction, handleSectionChange, isOpen } = useNavMenu(sections) - const MenuContent = dynamic(() => import("./MenuContent")) - return (
{ const { direction } = useRtlFlip() - const menuColors = useNavMenuColors() const [activeSection, setActiveSection] = useState(null) // Focus corresponding nav section when number keys pressed @@ -72,7 +70,6 @@ export const useNavMenu = (sections: NavSections) => { direction, handleSectionChange, isOpen, - menuColors, onClose, } } diff --git a/src/components/Nav/Menu/useSubMenu.ts b/src/components/Nav/Menu/useSubMenu.ts index 7d99f4ae67e..b44b39e7999 100644 --- a/src/components/Nav/Menu/useSubMenu.ts +++ b/src/components/Nav/Menu/useSubMenu.ts @@ -1,14 +1,10 @@ import type { MotionProps } from "framer-motion" import { useRouter } from "next/router" -import { useNavMenuColors } from "@/hooks/useNavMenuColors" import { useRtlFlip } from "@/hooks/useRtlFlip" -const PADDING = 4 // Chakra-UI space token - export const useSubMenu = () => { const { asPath, locale } = useRouter() - const menuColors = useNavMenuColors() const { isRtl } = useRtlFlip() const menuVariants: MotionProps["variants"] = { @@ -19,8 +15,6 @@ export const useSubMenu = () => { return { asPath, locale, - menuColors, menuVariants, - PADDING, } } diff --git a/src/components/Nav/Mobile/HamburgerButton.tsx b/src/components/Nav/Mobile/HamburgerButton.tsx index 3722c1c4617..1bb8c2c484d 100644 --- a/src/components/Nav/Mobile/HamburgerButton.tsx +++ b/src/components/Nav/Mobile/HamburgerButton.tsx @@ -37,7 +37,7 @@ const HamburgerButton = forwardRef( > void } +const subtextColorPerLevel = { + 1: "text-menu-1-subtext", + 2: "text-menu-2-subtext", + 3: "text-menu-3-subtext", + 4: "text-menu-4-subtext", +} + +const backgroundColorPerLevel = { + 1: "bg-menu-1-background", + 2: "bg-menu-2-background", + 3: "bg-menu-3-background", + 4: "bg-menu-4-background", +} + const LvlAccordion = ({ lvl, items, @@ -34,7 +46,6 @@ const LvlAccordion = ({ onToggle, }: LvlAccordionProps) => { const { asPath, locale } = useRouter() - const menuColors = useNavMenuColorsTw() const [value, setValue] = useState("") return ( @@ -84,7 +95,9 @@ const LvlAccordion = ({

{label} @@ -93,8 +106,8 @@ const LvlAccordion = ({ className={cn( "text-sm font-normal", isActivePage - ? menuColors.active - : menuColors.lvl[lvl].subtext + ? "text-primary-high-contrast" + : subtextColorPerLevel[lvl] )} > {description} @@ -114,7 +127,7 @@ const LvlAccordion = ({ > { trackCustomEvent({ eventCategory: "Mobile navigation menu", @@ -127,18 +140,13 @@ const LvlAccordion = ({ >

-

+

{label}

{description} @@ -147,7 +155,7 @@ const LvlAccordion = ({ void linkSections: NavSections @@ -26,7 +24,6 @@ type MenuBodyProps = { const MenuBody = ({ linkSections, onToggle }: MenuBodyProps) => { const { locale } = useRouter() - const menuColors = useNavMenuColorsTw() const [value, setValue] = useState("") return ( @@ -48,7 +45,7 @@ const MenuBody = ({ linkSections, onToggle }: MenuBodyProps) => { className="border-b border-body-light first:border-t" > { trackCustomEvent({ eventCategory: "Mobile navigation menu", @@ -67,9 +64,8 @@ const MenuBody = ({ linkSections, onToggle }: MenuBodyProps) => { import("./Mobile")) +const Menu = dynamic(() => import("./Menu"), { + ssr: false, + loading: () =>

, +}) +const MobileNavMenu = dynamic(() => import("./Mobile"), { ssr: false }) // TODO display page title on mobile const Nav = () => { const { toggleColorMode, linkSections } = useNav() const { t } = useTranslation("common") - const searchModalDisclosure = useDisclosure() const navWrapperRef = useRef(null) const isClient = useIsClient() - const isDesktopFlag = isDesktop() + const desktopScreen = useBreakpointValue({ base: false, md: true }) return ( - - + +
) } diff --git a/src/components/Nav/types.ts b/src/components/Nav/types.ts index fb78ad871b9..bdaa150547f 100644 --- a/src/components/Nav/types.ts +++ b/src/components/Nav/types.ts @@ -1,6 +1,5 @@ -import type { RefObject } from "react" +import type { FC, RefObject, SVGProps } from "react" import type { IconType } from "react-icons" -import type { IconProps } from "@chakra-ui/react" type LinkOnly = { href: string; items?: never } type ItemsOnly = { items: NavItem[]; href?: never } @@ -9,7 +8,7 @@ type LinkXorItems = LinkOnly | ItemsOnly export type NavItem = { label: string description: string - icon?: IconType | ((props: IconProps) => JSX.Element) + icon?: IconType | FC> } & LinkXorItems export type NavSectionKey = diff --git a/src/components/Nav/useNav.ts b/src/components/Nav/useNav.ts index 32759b79e9c..a996a3ac7c4 100644 --- a/src/components/Nav/useNav.ts +++ b/src/components/Nav/useNav.ts @@ -1,3 +1,4 @@ +import { useEffect } from "react" import { useTranslation } from "next-i18next" import { useTheme } from "next-themes" import { @@ -20,21 +21,17 @@ import { import { PiFlask, PiUsersFourLight } from "react-icons/pi" import { useColorMode } from "@chakra-ui/react" -import { EthereumIcon } from "@/components/icons/EthereumIcon" +import EthereumIcon from "@/components/icons/ethereum-icon.svg" import { trackCustomEvent } from "@/lib/utils/matomo" import type { NavSections } from "./types" -import useColorModeValue from "@/hooks/useColorModeValue" - export const useNav = () => { const { t } = useTranslation("common") - const { resolvedTheme, setTheme } = useTheme() + const { setTheme, resolvedTheme, systemTheme } = useTheme() const { setColorMode } = useColorMode() - const colorToggleEvent = useColorModeValue("dark mode", "light mode") // This will be inverted as the state is changing - const linkSections: NavSections = { learn: { label: t("learn"), @@ -465,13 +462,27 @@ export const useNav = () => { }, } + // Listen for changes to systemTheme and update theme accordingly + // Important if the user has not engaged the color mode toggle yet, and + // toggles system color preferences + useEffect(() => { + setTheme("system") + setColorMode(systemTheme) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [systemTheme]) + const toggleColorMode = () => { - setTheme(resolvedTheme === "dark" ? "light" : "dark") - setColorMode(resolvedTheme === "dark" ? "light" : "dark") + // resolvedTheme: "light" | "dark" = Current resolved color mode from useTheme + const targetTheme = resolvedTheme === "dark" ? "light" : "dark" + // If target theme matches the users system pref, set ls theme to "system" + const lsTheme = targetTheme === systemTheme ? "system" : targetTheme + + setTheme(lsTheme) + setColorMode(targetTheme) trackCustomEvent({ eventCategory: "nav bar", eventAction: "click", - eventName: colorToggleEvent, + eventName: `${targetTheme} mode`, }) } diff --git a/src/components/PageHero.tsx b/src/components/PageHero.tsx index b5c3ad7741b..15029253ad5 100644 --- a/src/components/PageHero.tsx +++ b/src/components/PageHero.tsx @@ -1,16 +1,17 @@ import type { ReactNode } from "react" -import { Box, Center, Flex, Heading, Wrap, WrapItem } from "@chakra-ui/react" + +import { type ImageProps, TwImage } from "@/components/Image" + +import { cn } from "@/lib/utils/cn" +import { type MatomoEventOptions } from "@/lib/utils/matomo" import { Button, ButtonLink, - type ButtonLinkProps, - type ButtonProps, -} from "@/components/Buttons" -import { Image, type ImageProps } from "@/components/Image" -import Text from "@/components/OldText" - -import { type MatomoEventOptions, trackCustomEvent } from "@/lib/utils/matomo" + ButtonLinkProps, + ButtonProps, +} from "./ui/buttons/Button" +import { Center, Flex } from "./ui/flex" type ButtonLinkType = Omit & { content: ReactNode @@ -48,113 +49,89 @@ const PageHero = ({ children, className, }: PageHeroProps) => ( - +
- - +

{title} - - +

+ +

{header} - - - {subtitle} - +

+

{subtitle}

+ {buttons && ( - + {buttons.map((button, idx) => { const isSecondary = idx !== 0 if (isButtonLink(button)) { return ( - +
- trackCustomEvent({ - eventCategory: button.matomo.eventCategory, - eventAction: button.matomo.eventAction, - eventName: button.matomo.eventName, - }) - } + customEventOptions={{ + eventCategory: button.matomo.eventCategory, + eventAction: button.matomo.eventAction, + eventName: button.matomo.eventName, + }} isSecondary={isSecondary} > {button.content} - +
) } if (button.toId) { return ( - +
- +
) } })} -
+
)} {children} - +
-
-
+
) export default PageHero diff --git a/src/components/Quiz/QuizzesStats.tsx b/src/components/Quiz/QuizzesStats.tsx index f016a822bad..0b77a3a02c0 100644 --- a/src/components/Quiz/QuizzesStats.tsx +++ b/src/components/Quiz/QuizzesStats.tsx @@ -9,7 +9,6 @@ import { Highlight, HStack, ListItem, - Progress, SimpleGrid, Stack, Text, @@ -24,6 +23,7 @@ import { ethereumBasicsQuizzes, usingEthereumQuizzes } from "../../data/quizzes" import { Button } from "../Buttons" import { TrophyIcon } from "../icons/quiz" import Translation from "../Translation" +import { Progress } from "../ui/progress" import { getFormattedStats, @@ -131,6 +131,7 @@ const QuizzesStats = ({ diff --git a/src/components/Search/SearchButton.tsx b/src/components/Search/SearchButton.tsx index e8e9d1e79c1..beb39f8d314 100644 --- a/src/components/Search/SearchButton.tsx +++ b/src/components/Search/SearchButton.tsx @@ -1,27 +1,28 @@ -import * as React from "react" -import { useTranslation } from "react-i18next" -import { DocSearchButton } from "@docsearch/react" +import { forwardRef } from "react" +import { useTranslation } from "next-i18next" +import { MdSearch } from "react-icons/md" + +import { cn } from "@/lib/utils/cn" import { Button, type ButtonProps } from "../ui/buttons/Button" -const SearchButton = React.forwardRef( - (props, ref) => { +const SearchButton = forwardRef( + ({ className, ...props }, ref) => { const { t } = useTranslation("common") return ( ) } diff --git a/src/components/Search/SearchInputButton.tsx b/src/components/Search/SearchInputButton.tsx new file mode 100644 index 00000000000..fc278e2ad09 --- /dev/null +++ b/src/components/Search/SearchInputButton.tsx @@ -0,0 +1,38 @@ +import * as React from "react" +import { useTranslation } from "next-i18next" +import { DocSearchButton } from "@docsearch/react" + +import { cn } from "@/lib/utils/cn" + +import { Button, type ButtonProps } from "../ui/buttons/Button" + +const SearchInputButton = React.forwardRef( + ({ className, ...props }, ref) => { + const { t } = useTranslation("common") + + return ( + + ) + } +) + +SearchInputButton.displayName = "SearchButton" + +export default SearchInputButton diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 1ff7b8e88b3..b1fefabda5c 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -1,154 +1,124 @@ -import { forwardRef, useRef } from "react" +import { useRef } from "react" import dynamic from "next/dynamic" import { useRouter } from "next/router" import { useTranslation } from "next-i18next" -import { MdSearch } from "react-icons/md" import { useDocSearchKeyboardEvents } from "@docsearch/react" import { DocSearchHit } from "@docsearch/react/dist/esm/types" -import { useComposedRefs } from "@radix-ui/react-compose-refs" import * as Portal from "@radix-ui/react-portal" import { trackCustomEvent } from "@/lib/utils/matomo" import { sanitizeHitTitle } from "@/lib/utils/sanitizeHitTitle" import { sanitizeHitUrl } from "@/lib/utils/url" -import { Button } from "../ui/buttons/Button" - -import SearchButton from "./SearchButton" - -import { type useDisclosure } from "@/hooks/useDisclosure" +import { useDisclosure } from "@/hooks/useDisclosure" const SearchModal = dynamic(() => import("./SearchModal")) -type Props = ReturnType +type Props = { + children: (props: ReturnType) => React.ReactNode +} + +const Search = ({ children }: Props) => { + const disclosure = useDisclosure() + const { isOpen, onOpen, onClose } = disclosure -const Search = forwardRef( - ({ isOpen, onOpen, onClose }, ref) => { - const { locale } = useRouter() - const searchButtonRef = useRef(null) - const mergedButtonRefs = useComposedRefs(ref, searchButtonRef) - const { t } = useTranslation("common") + const { locale } = useRouter() + const searchButtonRef = useRef(null) + const { t } = useTranslation("common") - useDocSearchKeyboardEvents({ - isOpen, - onOpen, - onClose, - searchButtonRef, + const handleOpen = () => { + onOpen() + trackCustomEvent({ + eventCategory: "nav bar", + eventAction: "click", + eventName: "search open", }) + } - const appId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "" - const apiKey = process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_KEY || "" - const indexName = - process.env.NEXT_PUBLIC_ALGOLIA_BASE_SEARCH_INDEX_NAME || "ethereumorg" + useDocSearchKeyboardEvents({ + isOpen, + onOpen: handleOpen, + onClose, + searchButtonRef, + }) - return ( - <> -
- { - onOpen() - trackCustomEvent({ - eventCategory: "nav bar", - eventAction: "click", - eventName: "search open", - }) + const appId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "" + const apiKey = process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_KEY || "" + const indexName = + process.env.NEXT_PUBLIC_ALGOLIA_BASE_SEARCH_INDEX_NAME || "ethereumorg" + + return ( + <> + {children({ ...disclosure, onOpen: handleOpen })} + + {isOpen && ( + -
-
- -
- - {isOpen && ( - - items.map((item: DocSearchHit) => { - const newItem: DocSearchHit = structuredClone(item) - newItem.url = sanitizeHitUrl(item.url) - const newTitle = sanitizeHitTitle(item.hierarchy.lvl0 || "") - newItem.hierarchy.lvl0 = newTitle - return newItem - }) - } - placeholder={t("search-ethereum-org")} - translations={{ - searchBox: { - resetButtonTitle: t("clear"), - resetButtonAriaLabel: t("clear"), - cancelButtonText: t("close"), - cancelButtonAriaLabel: t("close"), - }, - footer: { - selectText: t("docsearch-to-select"), - selectKeyAriaLabel: t("docsearch-to-select"), - navigateText: t("docsearch-to-navigate"), - navigateUpKeyAriaLabel: t("up"), - navigateDownKeyAriaLabel: t("down"), - closeText: t("docsearch-to-close"), - closeKeyAriaLabel: t("docsearch-to-close"), - searchByText: t("docsearch-search-by"), - }, - errorScreen: { - titleText: t("docsearch-error-title"), - helpText: t("docsearch-error-help"), - }, - startScreen: { - recentSearchesTitle: t( - "docsearch-start-recent-searches-title" - ), - noRecentSearchesText: t("docsearch-start-no-recent-searches"), - saveRecentSearchButtonTitle: t( - "docsearch-start-save-recent-search" - ), - removeRecentSearchButtonTitle: t( - "docsearch-start-remove-recent-search" - ), - favoriteSearchesTitle: t("docsearch-start-favorite-searches"), - removeFavoriteSearchButtonTitle: t( - "docsearch-start-remove-favorite-search" - ), - }, - noResultsScreen: { - noResultsText: t("docsearch-no-results-text"), - suggestedQueryText: t("docsearch-no-results-suggested-query"), - reportMissingResultsText: t("docsearch-no-results-missing"), - reportMissingResultsLinkText: t( - "docsearch-no-results-missing-link" - ), - }, - }} - /> - )} - - - ) - } -) - -Search.displayName = "Search" + /> + )} + + + ) +} export default Search diff --git a/src/components/Select/context.ts b/src/components/Select/context.ts deleted file mode 100644 index e579cdcf622..00000000000 --- a/src/components/Select/context.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createStylesContext, type SystemStyleObject } from "@chakra-ui/react" - -import { reactSelectAnatomyKeys } from "./innerComponents" - -const [ReactSelectStylesProvider, useReactSelectStyles] = - createStylesContext("ReactSelect") - -export const SelectStylesProvider = ReactSelectStylesProvider - -export const useSelectStyles = useReactSelectStyles as () => Record< - (typeof reactSelectAnatomyKeys)[number], - SystemStyleObject -> diff --git a/src/components/Select/innerComponents.tsx b/src/components/Select/innerComponents.tsx deleted file mode 100644 index f9ba42f5aec..00000000000 --- a/src/components/Select/innerComponents.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import * as React from "react" -import { FaChevronDown } from "react-icons/fa" -import type { - ContainerProps, - ControlProps, - DropdownIndicatorProps, - GroupBase, - GroupProps, - MenuListProps, - OptionProps, -} from "react-select" -import { Box, Center, HStack, Icon } from "@chakra-ui/react" - -import { useSelectStyles } from "./context" - -export const reactSelectAnatomyKeys = [ - "container", - "control", - "indicatorIcon", - "menuList", - "option", - "groupHeading", -] as const - -export const nullop = () => null - -/* - * Note on the Generic declarations: - * Because the custom components are being created outside of the `components` - * prop, generics sent to the respective props have to be redeclared, else type - * errors throw for incompatibility. - */ - -const SelectContainer = < - Option, - IsMulti extends boolean, - Group extends GroupBase