Jack  C

Jack C

1664166491

Top 10 Asset Management projects on Polygon Network

Asset management has a double-barreled goal: increasing value while mitigating risk. That is, the client's tolerance for risk is the first question to be posed. A retiree living on the income from a portfolio, or a pension fund administrator overseeing retirement funds, is (or should be) risk-averse. A young person, or any adventurous person, might want to dabble in high-risk investments.

Most of us are somewhere in the middle, and asset managers try to identify just where that is for a client.

The asset manager's role is to determine what investments to make, or avoid, to realize the client's financial goals within the limits of the client's risk tolerance. The investments may include stocks, bonds, real estate, commodities, alternative investments, and mutual funds, among the better-known choices.

The asset manager is expected to conduct rigorous research using both macro and microanalytical tools. This includes statistical analysis of prevailing market trends, reviews of corporate financial documents, and anything else that would aid in achieving the stated goal of client asset appreciation.

In this article, you will see Top 10 Asset Management projects on Polygon Network

1. MetaMask

NameDescribeLink
MetaMask

MetaMask is a popular cryptocurrency wallet known for its ease of use, availability on both desktops and mobile devices, the ability to buy, send, and receive cryptocurrency from within the wallet, and collect non-fungible tokens (NFTs) across two blockchains. While experienced crypto users will appreciate the simplicity and fast transactions, those new in the space are at a higher risk of losing their tokens from lost secret phrases, malicious websites, and other cryptocurrency scams.

Pros

Easy download and setup across devices

No signup process involving personally identifiable information

Create multiple wallets inside one app

Supports all ERC-20 tokens, NFTs, and multiple blockchains

Cons

No password reset option

Limited technical support

Doesn’t support Bitcoin

Website

2. Trust Wallet

NameDescribeLink
Trust Wallet

Trust Wallet is a user-friendly wallet app that supports most major cryptocurrencies, as well as many smaller tokens. While some wallets are strictly for crypto storage, this one includes several other features, including staking to earn crypto rewards.

Pros

Trustwallet allows to store and manage crypto in an efficient, secure and very simple way. Creating an account is easy and its security processes are satisfactory.

Cons

This wallet does not have many of coins. They could add many more in the future.

Website

3. Enzyme

NameDescribeTokenExchangeLink
Enzyme

Enzyme is a decentralised asset management infrastructure built on Ethereum. Using Enzyme Smart Vaults, individuals and communities can build, scale and monetise investment (or execution) strategies that employ the newest innovations in decentralised finance.

Enzyme enables Depositors to interact with Vaults in a way which is non-custodial and requires minimal trust between parties. Vault Managers can be bound to performing certain actions or forbidden from others. Furthermore, live accounting is available for both performance and fees which is provable with on-chain data using the Enzyme subgraph. 

MLNBinanceWebsite


 

4. XDEFI Wallet

NameDescribeTokenExchangeLink
XDEFI Wallet

XDEFI is a non-custodial wallet that allows you to securely swap, store, and send NFTs and crypto across 14 blockchains.

One wallet for all of Web3: Swap, send and store more than 10,500 assets on Ethereum, THORChain, Avalanche, Fantom, Arbitrum, Polygon, Bitcoin, Binance Chain, Binance Smart Chain, Doge, Litecoin, Luna2, Luna Classic, and Bitcoin Cash.

A single gallery for all of your NFTs: A single, customizable gallery for your Ethereum, Avalanche, Polygon, Binance Chain and Luna2 NFTs.

XDEFIGateWebsite

5. dHEDGE

NameDescribeTokenExchangeLink
dHEDGE

dHedge is described to be a project that focuses on non-custodial mimetic trading for synthetic assets on Ethereum. The project focuses on the following areas:

Non-custodial: users retain ownership over their funds, investment managers cannot run away with investor funds

Mimetic trading: investors can mime the trades of top-performing managers

Synthetic assets on Ethereum: dHedge portfolios are powered by the Synthetix derivatives liquidity protocol

dHedge further claims to be a one-stop location for managing investment activities on the Ethereum blockchain where users can put their capital to work in different strategies based on a track record of performance.

DHTHuobiWebsite

6. TokenPocket

NameDescribeTokenExchangeLink
TokenPocketTokenPocket is a multi-chain cryptocurrency wallet on both mobile and desktop with built in dApp browsers. Launched in 07/14/2020, TPT refers to TokenPocket Token, an applicational token representing TP users and developers’ rights in the TP ecosystem. TPT is also an important link among the wallet, users, and developers.TPTGateWebsite

7. Stake DAO

NameDescribeTokenExchangeLink
Stake DAO

Stake DAO is a non-custodial platform that enables anyone to easily grow their crypto portfolio. It is built on top of decentralized blockchain protocols, offering a seamless way for people to grow, track, and control assets right from their wallet.

The Stake Dao Token (or SDT) is a governance token which allows users to vote and earn fees generated on Stake DAO via products such as staking and automated investment strategies.

Stake DAO is a new multi-service DeFi platform built by the community which leverages the entire DeFi ecosystem to give users access to the most effective investment strategies.

Token holders can stake their earned SDT to receive a share of the DAO fees.

SDTUniswapWebsite

8. Instadapp

NameDescribeTokenExchangeLink
InstadappInstadapp is a platform providing users and developers with a single point of integration to access all the DeFi protocolsINSTMEXCWebsite

9. Zerion

NameDescribeLink
ZerionZerion is an investment interface for decentralized finance, providing users with a single place to manage their entire DeFi portfolio in a non-custodial wayWebsite

10. Zapper

NameDescribeLink
ZapperZapper is a system focused on abstracting away the complexities of composing and accessing the most innovative opportunities in open financeWebsite

Top exchanges for token-coin trading ☞ BinancePoloniexBitfinexHuobiMXCProBITGate.io

Read more: Data Analytics projects on Polygon Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #polygon #matic 

Top 10 Asset Management projects on Polygon Network
Jack  C

Jack C

1663659180

Top 5 Yield Aggregators projects on Polygon Network

Yield aggregators, also known as ‘auto-compounders’ or ‘yield optimisers’ are tools that hunt for protocols/pools to maximise yields on invested capital. They also automatically re-invest interest gained on yields, which for an individual user, would be inefficient due to gas fees. By doing this process in batches across all participants, gas fees become negligible and the protocol as a whole makes a profit.

In this article, you will see tTop 5 Yield Aggregators projects on Polygon Network

1. Autofarm

Autofarm is a DeFi yield farming optimizer. It aggregates other yield farming sites on its own platform, letting you farm/stake on those platforms while Autofarm’s smart contracts automatically harvest yields at optimal times to increase your APY.

Farm APY is the interest you earn from the coin you’ve staked in the vault (ie. BNB, BTC, ETH, etc.) and is automatically added to your vault when harvested. So if you’ve staked 10 BNB to start, every day you’ll notice that stack grows a little.

AUTO APY is the interest on top of the Farm APY you earn for using the Autofarm platform. AUTO is Autofarm’s native token that can only be mined through platform’s vaults. More on the AUTO token later.

Autofarm works with these users and organization types: Mid Size Business, Small Business, Enterprise, Freelance, Nonprofit, and Government.

Autofarm supports these languages: English.

Autofarm offers support via online.

Autofarm integrates with: Avalanche, Binance Wallet, BNB Chain, Celo, Deri, Fantom, HECO Chain, MetaMask, Moonriver, Multifarm, OKC, Polygon (Matic), Token Terminal, and WalletConnect.

Visit: ☞ Website


2. Harvest

NameDescribeTokenExchangeLink
HarvestHarvest is described to automatically farm the highest yield available from the newest DeFi protocols, and optimizes the yields that are received using the latest farming techniques. FARM is the governance token for Harvest. It is claimed that FARM holders can vote on proposals for the FARM operational treasury and receive the 5% fee from Harvest operations.FARMBinanceWebsite

3. Beefy Finance

NameDescribeTokenExchangeLink
Beefy Finance

Beefy.finance is a yield optimization tool on Binance smart chain, that helps to maximize the return from yield farming.

Just to give you a better perspective, Bakerysoup.org is a yield farming platform, and so is Venus.io. You can farm directly using these two platforms, but when you use something like Beefy.finance or its alternative such as autofarm.network, you are basically optimizing and maximizing your yield farming effort automatically. How it is done, we will look into the further section of this guide.

A little background, one of the first aggregators in this ecosystem is Yearn Finance, which was also a great option for Yield Farming. But, Yearn Finance operates on the Ethereum Network whose transaction cost (Ethereum GAS fees) has skyrocketed in the recent past. As a lucrative alternative, Beefy Finance runs on Binance Smart Chain and with a lower transaction fee. This opens up doors for much more involved strategies that can rebalance frequently and use an increased number of transactions to maximize APY’s (more on APY later).

BIFIBinanceWebsite

4. Pickle

NameDescribeTokenExchangeLink
Pickle

Pickle Finance is a yield aggregator that compounds LPs across various chains. Users realise the power of compounding, while saving time and money compared to manual farming. Pickle Finance has Jars, and Farms. Jars compound returns from other protocols, creating a pToken. Farms provide extra Pickle rewards for staking a jars pToken.

The Pickle Protocol is governed by DILL holders (users that stake PICKLE) who are able to create and vote on proposals for changes to the protocol. DILL holders also get to share in 45% of protocol revenues, as well as boost the PICKLE rewards on their farms.

PICKLEGateWebsite

5. Idle

Idle is a decentralized finance project that lives by one simple motto: “Money should never sit still.”

Through Idle, crypto investors can establish a portfolio that best manages their risk appetite. Once users make a deposit, funds are automatically distributed among a range of DeFi protocols, enabling them to earn interest. Portfolios are regularly rebalanced when better opportunities come along, and a dashboard offers at an at-a-glance insight into how funds are performing.

One of Idle’s unique selling points lies in how users don’t need to move their money manually between the plethora of DeFi protocols that exist today. This is achieved through holding IDLE tokens.

But another distinctive attribute concerns the fact that Idle Finance’s team have aimed to make their product as easy to use as possible. Blockchain complexity is an insurmountable hurdle for many investors who would otherwise be interested in learning more about what crypto has to offer.

Visit: ☞ Website

Top exchanges for token-coin trading ☞ BinancePoloniexBitfinexHuobiMXCProBITGate.io

Read more: Decentralized exchanges projects on Polygon Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #polygon #matic 

Top 5 Yield Aggregators projects on Polygon Network
Jack  C

Jack C

1663654722

Data Analytics projects on Polygon Network

In this article, you will see top 5 Data Analytics projects on Polygon Network

1. DefiLlama 

DefiLlama is committed in providing accurate data, without ads or sponsored content, and transparency. All chains are listed in DeFi projects. The majority of adapters on DefiLlama are contributed and maintained by their respective communities, with all changes being coordinated through the DefiLlama/DefiLlama-Adapters github repo. Calls some endpoints or makes some blockchain calls to collect data about a protocol. Calculates the TVL of a protocol, and returns it.

SDK currently supports EVM chains. If your project is in one of these chains, you should create a SDK-based adaptationer. However, if your project belongs to another chain, a fetch adapter will work. The adapter is a function that returns the balances of tokens in your protocol's smart contract at that time and takes a timestamp (on Ethereum).

PROS

  • Helps you keep track of the entire DeFi space(1750+ protocols and 130+ chains).
  • You can conduct in-depth research into all the major DeFi protocols.
  • TVL data for different chains and protocols is available.
  • Free to use.
  • Free to integrate API.

CONS

  • The user interface can be a bit confusing for new users.
  • An overload of data that a user will have to search through.

Visit: ☞ Website


2. Dune Analytics

Dune Analytics is a data platform that crypto-asset analysts and investors use to research specific projects such as NFTs, DeFi platforms, or blockchain ecosystems. Anyone can query the data and create visualizations using Dune.

The platform currently supports data from Ethereum — including layer-2 solutions such as Polygon, Optimism — Binance Smart Chain, and Gnosis Chain.

Dune Analytics was created with the express purpose of making Web 3.0 data available to all. Dune Analytics allows anyone to publish and gain access to crypto trends in real-time. It is a community-based open-source data provider, and it is freely available, so anyone can access and publish data without registering or paying.

What Dune Analytics brings new to the crypto world is the fact that it makes on-chain crypto data available and consumable. Initially, the creators intended to create a tool that allowed anyone with an internet connection to analyze a few dozen smart contracts products.

The service’s name, Dune, comes from the fact that their data charts look like dunes, and it is also related to Frank Herbert’s science fiction novel, Dune. It recently rebranded from Dune Analytics to just Dune.

Pros.

  • Access to all ETH databases.
  • Visualization of data.
  • Premade dashboard and written queries.

Cons.

  • Hard to use.
  • No chart editing.
  • Poor UI

Visit: ☞ Website


3. Nansen

Nansen is an analytics platform for blockchain, combining on-chain data with a massive and constantly growing database containing millions of wallet labels. Moreover, traders can use Nansen to access this data via user-friendly dashboards, direct SQL queries, or APIs.


Pros.

  • Analyzes huge number of wallets
  • Supports stablecoins and tokens
  • Simple and interactive UI

Cons.

  • There’s no free plan. However, you can still apply for a demo account.

Visit: ☞ Website


4. APY.Vision

APY.Vision is an analytics platform that provides clarity for liquidity providers contributing capital on Automated Market Making (AMM) protocols. Innovations in blockchain technology and Decentralized Finance (DeFi) have opened the gates to allow anyone, with any amount of spare capital, to contribute liquidity to markets and earn a fee from doing so.

VISION is the membership token that is used for accessing the PRO edition of the tool. We provide our PRO members with additional analytics. Furthermore, token holders can vote on new features to determine the roadmap of the product. In the future, when we expand to other DeFi verticals such as decentralized options and derivatives, VISION holders can gain access to those analytics modules.

Visit: ☞ Website


5. DeBank

DeBank is an extremely useful tool for tracking your on-chain crypto portfolio across all Ethereum compatible blockchains like Binance Chain, Polygon, Avalanche, Arbitrum, and dozens of others. While connecting your Web3 wallet to DeBank is an easy way to view your holdings and manage smart contract permissions, anyone can see what's in your wallet by navigating to your address or ENS domain.

DeBank comes in handy because it organizes all your assets according to blockchain network and which protocols they're being used on. DeBank also features a history tab where you can view past transactions and another tab to view your NFTs from popular collections on Ethereum and Polygon. Overall, DeBank comes in handy for investors who want to track their exposure to multiple DeFi protocols all in one place.

Pros

  • Comprehensive DeFi tracking across a large variety of protocols and blockchains with rapid updates.
  • Protocol data are available for tracking statistics such as TVL (Total Value Locked).

Cons

  • Inaccuracy in extracting protocol data such as users.

Visit: ☞ Website


Top exchanges for token-coin trading ☞ BinancePoloniexBitfinexHuobiMXCProBITGate.io

Read more: Decentralized exchanges projects on Polygon Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #polygon #matic 

Data Analytics projects on Polygon Network
Jack  C

Jack C

1663210082

Decentralized exchanges projects on Polygon Network

In this article, you will see top 10 (Decentralized exchanges) DEX projects on Polygon Network

1. 1inch.exchange

NameDescribeTokenExchangeLink
1inch.exchange

The 1inch Network unites decentralized protocols whose synergy enables the most lucrative, fastest, and protected operations in the DeFi space.

The 1inch Network's first protocol is a decentralized exchange (DEX) aggregator solution that searches deals across multiple liquidity sources, offering users better rates than any individual exchange. The 1inch Aggregation Protocol incorporates the Pathfinder algorithm for finding the best paths across over 240+ liquidity sources on Ethereum, BNB Chain, Polygon, Avalanche, Optimistic Ethereum, Arbitrum, Fantom and Gnosis Chain. In just over two years the 1inch DEX aggregator has reached 1M users and surpassed $150B in overall volume on the Ethereum network alone.

The 1inch Liquidity Protocol is a next-generation automated market maker (AMM) that protects users from front-running attacks and offers attractive opportunities to liquidity providers.

The 1inch Limit Order Protocol facilitates the most innovative and flexible limit order swap opportunities in DeFi. The protocol’s features, such as dynamic pricing, conditional orders, and extra RFQ support, power various implementations, including stop-loss and trailing stop orders, as well as auctions.

1INCHBinanceWebsite

2. Uniswap

NameDescribeTokenExchangeLink
Uniswap

Uniswap is a popular decentralized trading protocol, known for its role in facilitating automated trading of decentralized finance (DeFi) tokens.

An example of an automated market maker (AMM), Uniswap launched in November 2018, but has gained considerable popularity this year thanks to the DeFi phenomenon and associated surge in token trading.

Uniswap aims to keep token trading automated and completely open to anyone who holds tokens, while improving the efficiency of trading versus that on traditional exchanges.

Uniswap creates more efficiency by solving liquidity issues with automated solutions, avoiding the problems which plagued the first decentralized exchanges.

UNIBinanceWebsite

3. SushiSwap

NameDescribeTokenExchangeLink
SushiSwap

SushiSwap (SUSHI) is an example of an automated market maker (AMM). An increasingly popular tool among cryptocurrency users, AMMs are decentralized exchanges which use smart contracts to create markets for any given pair of tokens.

SushiSwap launched in September 2020 as a fork of Uniswap, the AMM which has become synonymous with the decentralized finance (DeFi) movement and associated trading boom in DeFi tokens.

SushiSwap aims to diversify the AMM market and also add additional features not previously present on Uniswap, such as increased rewards for network participants via its in-house token, SUSHI.

SUSHIBinanceWebsite

4. DODO

NameDescribeTokenExchangeLink
DODO

DODO is a DeFi protocoldecentralized finance (DeFi) protocol and on-chain liquidity provider whose unique proactive market maker (PMM) algorithm aims to offer better liquidity and price stability than automated market makers (AMM).

The PMM pricing mechanism, which mimics human trading, utilizes oracles to gather highly accurate market prices for assets. It then provides enough liquidity close to these prices in order to stabilize the portfolios of liquidity providers (LP), lower price slippage and negate impermanent loss by allowing arbitrage trading as reward.

DODO also caters for new crypto projects with a free ICO listing through its Initial DODO Offering (IDO) which requires issuers to only deposit their own tokens.

DODOBinanceWebsite

5. Balancer

NameDescribeTokenExchangeLink
Balancer

A Balancer Pool is an automated market maker with certain key properties that cause it to function as a selfbalancing weighted portfolio and price sensor

Balancer turns the concept of an index fund on its head: instead of paying fees to portfolio managers to rebalance your portfolio, you collect fees from traders, who rebalance your portfolio by following arbitrage opportunities.

Balancer protocol functions as a self-balancing weighted portfolio, price sensor and liquidity provider. It allows users to earn profits through its recently introduced token ($BAL) by contributing to customizable liquidity pools.

BALBinanceWebsite

6. KyberSwap

NameDescribeTokenExchangeLink
KyberSwap

KyberSwap is the best place to trade more than 23,000 tokens on networks at the best rates, and earn more with your token assets.

Make multi-chain swaps (Ethereum, Polygon, BNB Chain, Avalanche, Cronos, Fantom, Arbitrum, BTTC & more) without needing to check rates across multiple platforms. Earn by providing liquidity to earn fees efficiently & securely.

Use the world’s first Trending Soon token tool to spot new gems. Convert your tokens directly from your wallet instantly, securely and privately.

KNCBinanceWebsite

7. Multichain

NameDescribeTokenExchangeLink
Multichain

Multichain(previously Anyswap) is a fully decentralized cross chain swap protocol, based on Fusion DCRM technology, with automated pricing and liquidity system.

As a cross-chain router protocol (CRP), Multichain is an infrastructure for on-chain asset interoperability, envisioned to be the ultimate router for Web3.

The solutions developed by Multichain allow almost all blockchains to inter-operate. There is no restriction to Ethereum like chains, or different Layer 2 chains requiring finality to Ethereum, or a network of Parachains, or Bitcoin types of chain, or COSMOS chains. These are either now all integrated, or on course for integration. With support for all ECDSA and EdDSA encrypted chains, Multichain is almost universally applicable as an interoperable layer.

MULTIBinanceWebsite

8. QuickSwap

NameDescribeTokenExchangeLink
QuickSwap

QuickSwap is a permissionless decentralized exchange based on Polygon Layer 2 scalability infrastructure.

QuickSwap is a fork of the originator of Automated Market Makers in the now rapidly expanding DeFi sector of the Cryptocurrency industry, Uniswap. Both, of course, are magical. Only, rather than settling for the magic of unicorns, we’ve opted for the magic of dragons. It’s a much faster kind of magic, currently only available in a land far far away, known by the locals as Layer 2.

Although it’s very very far far away, to get there requires only a few clicks on a mouse, via the magical MATIC portal.

QUICKBinanceWebsite

9. Idex

NameDescribeTokenExchangeLink
Idex

Idex tuyên bố là DEX thanh khoản hỗn hợp đầu tiên kết hợp mô hình sổ lệnh với một nhà tạo lập thị trường tự động. Nó kết hợp hiệu suất và các tính năng của mô hình sổ lệnh truyền thống với tính bảo mật và tính thanh khoản của AMM. Idex thực hiện một cách tiếp cận sáng tạo đối với các sàn giao dịch phi tập trung bằng cách kết hợp một công cụ giao dịch ngoài chuỗi với thanh toán thương mại trên chuỗi. Người dùng được hưởng lợi từ điều đó theo một số cách.

First, this approach does away with failed trades and wasted money on gas fees, making the trading experience more pleasant and efficient. The instant trade execution means front-running or sandwich attacks are not possible and users can trade without waiting for previous trades to settle. As a result, more advanced order types and trading strategies can be executed since limit orders are possible, opening up arbitrage opportunities with other exchanges.

IDEXBinanceWebsite

10. DexGuru

NameDescribeLink
DexGuruDexGuru is a trading platform for modern traders where on-chain analytics combined with trading capabilities.Website

Top exchanges for token-coin trading ☞ BinancePoloniexBitfinexHuobiMXCProBITGate.io

Read more: DEX projects on Ethereum Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #polygon #matic 

Decentralized exchanges projects on Polygon Network

Decentralized Badminton Centered Dapp on IPFS and Polygon Blockchain

Web Badminton

Web Badminton - decentralized badminton centered dapp on IPFS and Polygon Blockchain. 

With Decentralized Storage provider IPFS and blockchain technology, we build a decentralized platform for you to learn about playing Badminton.

We Updated the App to include new Chain: Lukso L14 testnet. The contract on the new chain follows LSP-8 standard. A standard interface for identifiable digital assets, allowing for tokens to be uniquely traded and given metadata using ERC725Y.

What it does

Web Badminton Dapp introduces users to the sport of Badminton as well as contains item store to track and ledger the delivery of badminton equipment.

Each real equipment item is ledgered via a digital one with a smart contract logic system in place to determine the demand and track iteam. When delivery is completed the DApp ERC1155 NFTs should be exchanged for the physical items.

A great win for the producers is a potential to save on costs with improved inventory tracking and demand management.

Web Badminton DApp succeeds where off-chain software ledgering system products fail because they may go out of service, need updates, crash with data losses. Web Badminton DApp is a very low cost business systems management product/tool.

While competing software based ledgering products carry monthly and or annual base fees, the only new costs accrued by the business utilizing the DApp are among new contract deployments. A new contract for new batch of items only is needed every few months based on demand and delivery schedule.

In addition, we created Decentralized Newsletter subscription List that we connected to web3.storage.

How we built it

We built the application using JavaScript, NextJS, React, Tailwind Css and Wagmi library, IPFS, nft.storage and web3.storage. The application is hosted on vercel. The newsletter list data is stored on ipfs with web3.storage.

The contract is built with solidity, hardhat and polygon blockchain mumbai testnet. Meanwhile the Ipfs data is stored using nft.storage.

Getting started

To get started with this Dapp, first install the npm dependencies:

yarn

Next, run the development server:

yarn dev

Links

Devpost Page

Learn more

To learn more about the technologies used in this site template, see the following resources:

Download details:

Author: BadmWe
Source code: https://github.com/BadmWe/WebBadminton 
License: View license

#nextjs #reactjs #web3 #dapp #solidity #polygon

Decentralized Badminton Centered Dapp on IPFS and Polygon Blockchain
Castore  DeRose

Castore DeRose

1661494820

Polygon Ecosystem Overview | Top 100 Project Built on Polygon (MATIC)

In this article, you'll learn what is Polygon, Polygon Ecosystem Overview | Top 100 Project Built on Polygon (MATIC)

Visit site: https://polygon.technology/

1. What is Polygon?

Polygon is a stack of protocols designed to fix Ethereum’s scalability issues. The Polygon network addresses the network’s challenges by handling transactions on a separate Ethereum-compatible blockchain. 

Polygon then returns transactions to the main Ethereum blockchain post-processing. This approach lowers the network load on Ethereum. In doing so, Polygon can speed up transactions and lower transaction costs to less than a cent.

In other words, Polygon, formerly known as Matic network, provides an easy framework for new and existing blockchain projects to build on Ethereum without scalability issues.

Using Polygon, users can interact with any decentralized application (DApp) without ever having to worry about network congestion.

This guide delves into everything there is to know about the Polygon Matic network, how Polygon works and how this innovative solution is making Ethereum easier to use.



How Does Polygon Work?

Polygon works similarly to other Proof of Stake (PoS) protocols in terms of network nodes, governance, staking, and other functionalities.

Proof of Stake Consensus

The platform leverages the Proof of Stake consensus, which relies on a set of node validators to verify and validate transaction blocks on the network, instead of relying on the classic Proof of Work (PoW), which consumes an enormous amount of processing power to create new blocks.

The main difference comes in that instead of having to do the work (computing work in PoW algorithms), in PoS, token holders validate and verify transactions.

The PoS ecosystem of Polygon works by rewarding users with MATIC, the protocol’s native token. To earn MATIC, you can choose one of the following options:

Become a validator and commit to the network by running a full node to validate transactions on the blockchain. As a node validator, you receive a cut of fees and newly created MATIC. However, if you act maliciously, make a mistake, or even if your internet connection is slow, your MATIC rewards will be slashed as punishment.

Become a delegator, which is a type of public node. As a delegator, you receive other people’s MATIC and use it to help the network conduct PoS validation. The larger the delegated stake, the higher the delegator’s voting power. This is easier than being a node validator, but it also comes with its challenges.

Polygon Bridge

If you want to transfer funds from the Ethereum network to Polygon’s, you need to use the PoS bridge, which is a set of smart contracts that help to conduct assets from the Ethereum mainnet to the Polygon sidechain.

The PoS bridge is the backbone to transfer assets from Ethereum to Polygon and then use these funds to interact with the apps and blockchains on the Polygon ecosystem. You’ll have to pay a transaction fee in ETH, of course, which can be expensive, but once you’re in the Polygon network, transactions are very cheap — less than a dollar.

Polygon Protocol

The Polygon Protocol connects all Polygon-based blockchains with each other and the Ethereum network. It also allows chains to tap into Ethereum to inherit its security model.

Polygon’s Software Development Kit (SDK)

In May 2021, Polygon announced the Polygon Software Development Kit (SDK), a collection of plug-and-play software tools that allows developers to launch their own fully customizable blockchains and DeFi apps.

The main idea is to make Ethereum a fully-fledged multi-chain system, which it already is, but the current limitations and the lack of structure on the Ethereum ecosystem makes it harder for developers to work on their projects.

Polygon aims to give the ecosystem a boost with Polygon SDK, based on three major concepts: Ethereum-compatibility, modularity, and extensibility, making it a flexible framework for developers keen to work on Ethereum scaling and infrastructure solutions.

Polygon SDK is divided into two iterations. The first version supports Ethereum-compatible stand-alone chains, which are sovereign blockchains in charge of their modules and security. These chains can use the Polygon bridge to communicate with Ethereum (e.g., transferring assets or sending arbitrary messages) while keeping their independence.

On the second version, we’ll see support for other types of chains, such as Layer 2, with their own set of modules and tools to further empower developers.

Polygon (MATIC) vs. Ethereum Layer 1

At first glance, layer-2 scaling solutions may appear to be complex. In simple terms, layer 1 describes the underlying base blockchain architecture. Layer 2, on the other hand, lies on top of the underlying blockchain as an overlaying network.

Layer-2 solutions are external protocols that interact with the base blockchain to increase speed and efficiency. Moreover, with layer-2 solutions like Polygon, protocols that are already running on top of Ethereum can become even faster and cheaper. 

Why use Polygon over Ethereum layer 1?

Ethereum was designed with an auction-based model, thus encouraging users to bid for their transaction to be included in the next block. Therefore, by design, more network congestion leads to increasingly prohibitive costs. 

Polygon has major ambitions for the future, and they don’t just include speed or transaction costs. The protocol aims to link all Ethereum Virtual Machine (EVM)-compatible blockchains with each other, allowing developers to access the benefits of other blockchain platforms with minimal friction.

Doesn’t Ethereum 2.0 kill the need for Polygon?

Ethereum 2.0 will be a major upgrade to the Ethereum blockchain, but it will only provide a limited solution to the scalability challenge. As more and more decentralized platforms and DApps use on-chain solutions like Eth2, demand may start to creep up against the limits of scalability.

As mentioned, this results in a buildup of network traffic. Gas fees begin to spike and the network ends up under the same load conditions as before. This is where Polygon comes in by providing the Ethereum blockchain with an additional layer of scalability.

Layer 2s like the Polygon network will further improve the experience Eth2 will have to offer. Any Ethereum upgrade can be made even faster with layer 2. In this manner, Polygon ensures that the end-user receives the best experience. 

Ethereum 2.0 is still some time away, but scalability has been an issue that was long acknowledged by Ethereum founder Vitalik Buterin as the Trilemma challenge. A solution like Polygon brings some of the benefits of Eth2 to users so that they may take advantage of the increased speed and transparency as well as lower costs, all without having to wait for the release of Eth2.

What makes Polygon so special?

What makes Polygon stand out from its layer 2 competitors? Polygon is the only network that allows its token, MATIC, to be staked on the Polygon blockchain. Staking allows its users to earn interest annually for helping validate transactions on the blockchain.

Polygon has solutions for everyday users, developers and enterprises alike. Polygon’s primary objective is to create an Internet of Things (IoT) for the Ethereum blockchain. The project aims to scale Ethereum to one billion users without sacrificing decentralization or security.

What sets Polygon apart from other L2 solutions is its approach. Polygon offers developers a stack of solutions on a single network. This approach grants developers higher levels of control and customization when choosing a scaling solution best suited to their application. 

On Polygon, a developer can choose between zk-rollups or optimistic rollups. They may opt to use Polygon Avail instead, an extremely secure data availability blockchain for standalone chains, sidechains and off-chain scaling solutions.

In May 2021, the Polygon network announced the launch of the Polygon SDK, which makes the process of building a multichain network much easier for developers. With the Polygon SDK, developers can create standalone chains that are fully responsible for their own security. These standalone sidechains will have a dedicated PoS bridge network connecting them to Ethereum.

Polygon also has other scaling approaches like its PoS commit chain. For convenience, the commit chain is often simply referred to as Polygon or the Polygon blockchain. Polygon’s PoS sidechain has been the project's most popular product. To date, the Polygon blockchain has processed roughly one billion transactions and counting, according to data from polygonscan.com.

The PoS commit chain is EVM-compatible and, thus, works flawlessly with many Ethereum protocols. Consequently, moving DApps across platforms is simple for developers.

Unlike other EVM sidechains, Polygon commits checkpoints to Ethereum. Specifically, each time Polygon processes a transaction, it creates a few checkpoints on Ethereum. These checkpoints ensure that all the data that has been processed on Polygon up to that point is valid and safe for the Ethereum blockchain. Note that other EVM sidechains do not use checkpoints. 

The MATIC Token

The MATIC token is an ERC-20 token that powers the entire Polygon ecosystem. It’s used to pay for gas fees, for staking, and for governance. As per CoinMarketCap, there’s a current circulating supply of 7.48 billion MATIC tokens, with a max supply of 10 billion.

After being rebranded to Polygon and implementing new features for developers and users on the ecosystem, the MATIC token saw explosive growth in price due to an increased use case. At the time of writing this, t’s the 14th largest cryptocurrency by means of total market capitalization.

The MATIC token supply distribution is as follows:

  • Advisors: 4%
  • Private Sale: 4%
  • Network Operations: 12%
  • Team: 16%
  • Launchpad Sale: 19%
  • Ecosystem: 23%
  • Foundation: 22%

2. Polygon Ecosystem Overview

TypeNameDescribeTokenExchangeLink
PolygonMaticMatic Network is a blockchain scalability platform which provides secure, scalable and instant transactions powered by PoS side chains and an adapted version of PlasmaMATICBinanceWebsite
BehindAnkrAnkr is a decentralized blockchain infrastructure provider that operates an array of nodes globally distributed across over 50 Proof-of-Stake networks. This infrastructure helps drive the growth of the crypto economy while powering a full suite of multi-chain tools for Web3 users:ANKRBinanceWebsite
GolemThe Golem Network is a decentralized computation network, a new way of distributing redundant computing power to those who are in need of it, on-demandGLMBinanceWebsite
StablecoinsDAIDAI is a crypto-backed stablecoin soft-pegged to USD, built on the Ethereum and governed by the MakerDAO system.DAIBinanceWebsite
FraxThe Frax Protocol is the first fractional-algorithmic stablecoin system.FRAXBinanceWebsite
MarketplacesOpenSeaOpenSea is a peer to peer marketplace for crypto collectibles  Website
Decentralized LendingAaveAave is an Open Source and Non-Custodial protocol that let you earn interest on deposits & borrow assets on multiple chains.AAVEBinanceWebsite
Cream FinanceC.R.E.A.M Finance is a decentralized DeFi lending protocol for individuals, institutions and protocols to access financial services. Part of the yearn.finance ecosystem, C.R.E.A.M. Finance is a permissionless, open source and blockchain agnostic protocol serving users on Ethereum, Binance Smart Chain Polygon and Fantom.CREAMBinanceWebsite
Decentralized exchanges1inch.exchange1inch.exchange split the order to several decentralized exchanges like UniswapExchange, KyberNetwork, Bancor and RadarRelay to avoid high price slippage1INCHBinanceWebsite
UniswapUniswap is an automated fully decentralized token exchange on EthereumUNIBinanceWebsite
SushiSwapThe SushiSwap exchange allows users to swap any ERC20 token into any other ERC20 token through automated liquidity poolsSUSHIBinanceWebsite
DODODODO is a on-chain liquidity provider which leverages the Proactive Market Maker algorithm (PMM) to provide on-chain and contract-fillable liquidity for everyoneDODOBinanceWebsite
BalancerBalancer Exchange allow you to swap ERC20 tokens trustlessly across all Balancer’s liquidity pools.BALBinanceWebsite
KyberSwapKyberSwap allows anyone to convert tokens directly from their wallet in an instant, convenient and secure wayKNCBinanceWebsite
MultichainMultichain(previously Anyswap) is a fully decentralized cross chain swap protocol, based on Fusion DCRM technology, with automated pricing and liquidity system.MULTIBinanceWebsite
QuickSwapQuickSwap is a permissionless decentralized exchange based on Polygon Layer 2 scalability infrastructureQUICKBinanceWebsite
IdexIDEX is a non-custodial exchange that integrates with any custody solution and allows users to trade with one another without giving up control to a third-party custodianIDEXBinanceWebsite
DexGuruDexGuru is a trading platform for modern traders where on-chain analytics combined with trading capabilities.  Website
SlingshotSlingshot is a web3 trading platform aggregating DEX liquidity.  Website
MatchaMatcha is a crypto trading platform with smart order routing powered by 0x. Matcha aggregates liquidity from multiple sources, including 0x, Kyber, Uniswap, Oasis, Curve, and others  Website
Decentralized Insurance PlatformsInsurAceInsurAce is a multi-chain protocol that provides insurance services to DeFi users, allowing them to protect their investment funds against various risksINSURBybitWebsite
Opium InsuranceOpium Insurance offers tradable, tokenized insurance position against smart-contract hacking or against stablecoin default.OPIUMGateWebsite
Asset Management ToolsMetaMaskMetaMask is a browser extension that allows users to run Ethereum dApps and interacting with smart contracts.  Website
Trust WalletMulti cryptocurrency wallet to store your favorite BEP2, ERC20 and ERC721, tokens.  Website
EnzymeEnzyme Finance formerly known as Melon Protocol, is a user interface that allows interaction with on-chain funds.MLNBinanceWebsite
XDEFI WalletXDEFI is a non-custodial wallet that allows you to securely swap, store, and send NFTs and crypto across 14 blockchains.XDEFIGateWebsite
dHEDGEdHEDGE is a platform for managing investment activities on the Ethereum blockchain where you can put your capital to work in different strategies based on a transparent track record.DHTHuobiWebsite
TokenPocketTokenPocket is a multi-chain cryptocurrency wallet on both mobile and desktop with built in dApp browsers.TPTGateWebsite
RainbowRainbow is a fun, simple, and secure Ethereum wallet that makes managing your assets a joy.RAINBOWPancakeSwapWebsite
Stake DAOStake DAO is a non-custodial platform that enables anyone to easily grow their crypto portfolio. It is built on top of decentralized blockchain protocols, offering a seamless way for people to grow, track, and control assets right from their wallet.SDTUniswapWebsite
InstadappInstadapp is a platform providing users and developers with a single point of integration to access all the DeFi protocolsINSTMEXCWebsite
ZerionZerion is an investment interface for decentralized finance, providing users with a single place to manage their entire DeFi portfolio in a non-custodial way  Website
ZapperZapper is a system focused on abstracting away the complexities of composing and accessing the most innovative opportunities in open finance  Website
TokenSetsTokenSets is the asset management platform with tokenized trading strategies facilitated by Set Protocol’s smart contract system  Website
DeFi Infrastructure & Dev ToolingThe GraphThe Graph is a decentralized protocol for indexing and querying data from blockchains.GRTBinanceWebsite
ChainlinkChainlink is a decentralized oracle that can provide external data to smart contracts.LINKBinanceWebsite
UMAUMA is a decentralized financial contracts platform built to enable Universal Market AccessUMABinanceWebsite
QuikNodeQuikNode is a RPC node service provider with APIs & dedicated nodes available.  Website
Prediction MarketsAugurAugur is a decentralized oracle and peer to peer protocol for prediction markets.REPBinanceWebsite
PlotXPlotX is a cross-chain prediction market protocol that enables crypto traders to make crypto-asset price predictions in hourly, daily & weekly time frames.PLOTUniswapWebsite
PolymarketPolymarket is an information markets platform, where you can bet on the highly-debated topics and earn for being right.  Website
Yield AggregatorsHarvestHarvest automatically farms the highest yield available from the newest DeFi protocols, and optimizes the yields that are received using the latest farming techniques.FARMBinanceWebsite
VesperVesper provides a suite of yield-generating products, focused on accessibility, optimization, and longevityVSPGateWebsite
Beefy FinanceBeefy Finance is a Multi Chain Yield Optimizer that enables users to get maximal return on their assets while removing the cost and hassle of daily harvest.BIFIBinanceWebsite
PicklePickle allow users to deposit tokens from liquidity pools such as Uniswap or Curve, and then execute sophisticated strategies that maximize the returns of the depositorPICKLEGateWebsite
IdleIdle enables tokenizing the best interest rate among Ethereum money marketsIDLE Website
AutofarmAutofarm is a cross-chain yield aggregator that enables users to get the return on their assets from yield farming pools by simply staking in Autofarm vaults.  Website
AnalyticsDefiLlamaDefiLlama is a multi-chain TVL stats dashboard, where data connectors contributed and maintained by a community  Website
Dune AnalyticsDune Analytics allows you to instantly create and share analysis of Ethereum data. Smart contract data is converted to a human-readable format that can be queried with SQL  Website
NansenNansen is an analytics platform for Ethereum, which combines on-chain data with a massive and constantly growing database containing millions of wallet labels  Website
APY.VisionAPY.Vision is an all-in-one analytics dashboard for liquidity providers and yield farmers  Website
DeBankDeBank is a dashboard for tracking your DeFi portfolio, with data and analytics for decentralized lending protocols, stablecoins, margin trading platforms and DEXes.  Website

Learn more: https://polygon.technology/ecosystem/

I hope this article will help you. Don't forget to leave a like, comment and sharing it with others. Thank you!

Read more: Ethereum Ecosystem Overview | Top 200 Project Built on Ethereum (ETH)

#blockchain #bitcoin #cryptocurrency #polygon #matic  

Polygon Ecosystem Overview | Top 100 Project Built on Polygon (MATIC)

A Blockchain Freelance Platform Built With Solidity, React, Polygon

MeDo

MeDo is a prototype of a freelancing platform which stores it's data on blockchain.

Application deployed on Spheron Network at https://medo-5jefp3.spheron.app/, currently running on Mumbai testnet. Smart Contract deployed at address 0x3aD0caD9E7Fb1A7A46F6F0665bbC97BdfDdaD740.

Introduction

The idea of MeDo is to ease the difficulties faced by freelancers nowadays such as unsurity about payments and high fees charged by middlemen. Blockchain can help by guaranteeing payments with help of smart contracts, providing security and an integrated payment system which can save time delays and fees in cases of international payments and its decentralized nature mean there is no middleman.

Install

  1. Run npm install at the root of your directory
  2. Run yarn at the client directory to install the client dependencies

Test

Run npx hardhat test at the smart_contract directory to run smart contract tests

Deploy contract

Run npx hardhat run scripts/deploy.js --network matic at the smart_contract directory to deploy the smart contract

Prepare the client

  1. Replace the cotract address in the utils/constants.js with the new deployed one
  2. Replace conractABI.json with the contract json from smart_contract/artifacts/contracts/{your_contract}/{your_contract}.json

Run client

Run yarn dev at the client directory to run the client locally

Download details:

Author: vadkutsen
Source code: https://github.com/vadkutsen/medo

#solidity #smartcontract #ethereum #blockchain #polygon

A Blockchain Freelance Platform Built With Solidity, React, Polygon

Building Decentralized Twitter Prototype using Polygon, GraphQL, Next

Titter - Web3 Social chat

beta as fuck

🛠 Built with Next.js, Arweave, Bundlr, Ceramic, GraphQL, & Polygon

Titter

How it works

This is a working prototype of a basic web3-native social application. Features include:

  • Permanent post storage (Arweave)
  • Editable, self-sovereign user profiles (Ceramic self.id)
  • GraphQL queries
  • Filtering at protocol level (not on client)
  • Fund and check balance of Bundlr with Matic on Polygon
  • Pagination can also be implemented fairly easily with a few extra lines of code at protocol level

Caveats:

Right now there is an issue with Bundlr + Arweave in that the gateway can miss Bundlr txs and think that it never hit Arweave (when it does). Hopefully this gets fixed soon.

The extent to which you can query is limited by what is offered at the protocol level. The Graph Arweave integration will unlock a lot more flexibility and power at some point in the near future.

Deploying the app

To deploy this project, follow these steps:

  1. Clone the project & change into the new directory
git clone git@github.com:dabit3/titter.git

cd titter

2.   Install dependencies

yarn

# or

npm install

3.   Run the app

yarn dev

# or

npm run dev

4.   To interact with the application, switch your wallet to Polygon Network

Download details:
Author: dabit3
Source code: https://github.com/dabit3/titter
License: MIT license

#next #nextjs #react #javascript #web3 #bundlr #arweave #polygon  #graphql #blockchain

Building Decentralized Twitter Prototype using Polygon, GraphQL, Next

Building NFT Badge for staking on Polygon, Solidity, Javascript

Introduction of the NFT Badge for staking

  • This repo is the smart contract for NFT Badge for staking.
    • This smart contract give a staker a NFT depends on staking period (= vesting period ) which a staker chose.
      • Staking period that a staker can choose are 3 options: 3 months, 6 months, 1 year)
      • Each NFT works as a proof of deposit and represents staking period (= vesting period ) which a staker chose.
      • A staker can not unstake until chosen-period. (When a staker try to unstake, smart contract check whether staking period is passed or not by a NFT which a staker has)
  • This smart contract has been deployed on Polygon (mumbai).
    • By deploying on Polygon, a staker can reduce cost for each transactions and get a higher speed transaction.

Workflow

  • Diagram of workflow 【Diagram】NFT Badge for staking

 

Remarks

  • Version
    • Solidity (Solc): v0.6.11
    • Truffle: v5.1.60
    • web3.js: v1.2.9
    • @openzeppelin/contracts: v3.4.0
    • ganache-cli: v6.9.1 (ganache-core: 2.10.2)

Setup

① Install modules

  • Install npm modules in the root directory
npm install

② Compile contracts

  • on Polygon (Matic) mumbai testnet
npm run compile:polygon_mumbai

Script for demo on Polygon (Matic) mumbai testnet

① Get API-key from Infura
https://infura.io/

② Add .env to the root directory.

  • Please reference how to write from .env.example . (Please write 3 things below into .env )
  • ③ In advance, Please check MATIC token balance of executor's (user's) wallet address .
  • ③ Execute script on Polygon (Matic) mumbai testnet (※ This script uses deployed-contract addresses on Polygon mumbai)
npm run script:StakingManager

Deployed-contract addresses

  • Smart contract addresses below are deployed on Polygon mumbai testnet:
    • LP Token: 0xCB9e421b1bF2f20E3EEbd3d16A8F44D50B7f56ad
    • Reward Token: 0xD68cE6B14d4E5f8ed28F6eb9b92A63f48FFDc0a7
    • StakingNFTBadgeFor3Months: 0x19bC3A74BB8de091fE4a76af093b031395cE17f2
    • StakingNFTBadgeFor6Months: 0xe5273E5D1bf82e60125968B6C9c3476A70E1FCaF
    • StakingNFTBadgeFor1Year: 0xBF3463C0def89691d765aB95d456402463310Ef3
    • StakingPool: 0xB8faeCcdF3Ce5Dc470720B212b7056113dbA386f
    • StakingManager: 0x404735352a45fc40fb1d10316e037219e1ADe25B
    • Fancet: 0xB786Ee2f65C6fec7568CA565Be9958713Ac24C18

Demo

References

Download Details:
Author: masaun
Source Code: https://github.com/masaun/NFT-badge-for-staking
License:

#blockchain #solidity #smartcontract #polygon #staking

Building NFT Badge for staking on Polygon, Solidity, Javascript

Fullstack NFT Marketplace Built with Polygon, Solidity, IPFS, & Nextjs

This is the codebase to go along with tbe blog post Building a Full Stack NFT Marketplace on Ethereum with Polygon

Running this project

Gitpod

To deploy this project to Gitpod, follow these steps:

  1. Click this link to deploy: Here

2.   Import the RPC address given to you by GitPod into your MetaMask wallet

This endpoint will look something like this:

https://8545-copper-swordtail-j1mvhxv3.ws-eu18.gitpod.io/

The chain ID should be 1337. If you have a localhost rpc set up, you may need to overwrite it.

MetaMask RPC Import

Local setup

To run this project locally, follow these steps.

  1. Clone the project locally, change into the directory, and install the dependencies:
git clone https://github.com/dabit3/polygon-ethereum-nextjs-marketplace.git

cd polygon-ethereum-nextjs-marketplace

# install using NPM or Yarn
npm install

# or

yarn

2.   Start the local Hardhat node

npx hardhat node

3.   With the network running, deploy the contracts to the local network in a separate terminal window

npx hardhat run scripts/deploy.js --network localhost

4.   Start the app

npm run dev

Configuration

To deploy to Polygon test or main networks, update the configurations located in hardhat.config.js to use a private key and, optionally, deploy to a private RPC like Infura.

require("@nomiclabs/hardhat-waffle");
const fs = require('fs');
const privateKey = fs.readFileSync(".secret").toString().trim() || "01234567890123456789";

// infuraId is optional if you are using Infura RPC
const infuraId = fs.readFileSync(".infuraid").toString().trim() || "";

module.exports = {
  defaultNetwork: "hardhat",
  networks: {
    hardhat: {
      chainId: 1337
    },
    mumbai: {
      // Infura
      // url: `https://polygon-mumbai.infura.io/v3/${infuraId}`
      url: "https://rpc-mumbai.matic.today",
      accounts: [privateKey]
    },
    matic: {
      // Infura
      // url: `https://polygon-mainnet.infura.io/v3/${infuraId}`,
      url: "https://rpc-mainnet.maticvigil.com",
      accounts: [privateKey]
    }
  },
  solidity: {
    version: "0.8.4",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  }
};

If using Infura, update .infuraid with your Infura project ID.

Download Details:
Author: dabit3
Source Code: https://github.com/dabit3/polygon-ethereum-nextjs-marketplace
License: MIT license

#nextjs #react #javascript #fullstack #ethereum #polygon #solidity

Fullstack NFT Marketplace Built with Polygon, Solidity, IPFS, & Nextjs
Lawrence  Lesch

Lawrence Lesch

1656467340

D3-geo-polygon: Clipping & Geometric Operations for Spherical Polygons

d3-geo-polygon

Clipping and geometric operations for spherical polygons.

Installing

If you use NPM, npm install d3-geo-polygon. Otherwise, download the latest release. You can also load directly from unpkg. AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3 global is exported:

<script src="https://unpkg.com/d3-geo@3"></script>
<script src="https://unpkg.com/d3-geo-polygon@1"></script>
<script>

// new projection
var projection = d3.geoDodecahedral();

// polyhedral projections don’t need SVG or canvas clipping anymore
var projection = d3.geoPolyhedralCollignon();

// arbitrary polygon clipping on any projection
var projection = d3.geoEquirectangular()
    .preclip(d3.geoClipPolygon({
      type: "Polygon",
      coordinates: [[[-10, -10], [-10, 10], [10, 10], [10, -10], [-10, -10]]]
    }));

</script>

API Reference

d3.geoClipPolygon(polygon) · Source, Examples

Given a GeoJSON polygon or multipolygon, returns a clip function suitable for projection.preclip.

clip.polygon()

Given a clipPolygon function, returns the GeoJSON polygon.

d3.geoIntersectArc(arcs) · Source, Examples

Given two spherical arcs [point0, point1] and [point2, point3], returns their intersection, or undefined if there is none. See “Spherical Intersection”.

Projections

d3-geo-polygon adds polygon clipping to the polyhedral projections from d3-geo-projection. Thus, it supersedes the following symbols:

d3.geoPolyhedral(tree, face) · Source, Examples

Defines a new polyhedral projection. The tree is a spanning tree of polygon face nodes; each node is assigned a node.transform matrix. The face function returns the appropriate node for a given lambda and phi in radians.

polyhedral.tree() returns the spanning tree of the polyhedron, from which one can infer the faces’ centers, polygons, shared edges etc.

d3.geoPolyhedralButterfly() · Source

The gnomonic butterfly projection.

d3.geoPolyhedralCollignon() · Source

The Collignon butterfly projection.

d3.geoPolyhedralWaterman() · Source

A butterfly projection inspired by Steve Waterman’s design.

New projections are introduced:

d3.geoPolyhedralVoronoi([parents], [polygons], [faceProjection], [faceFind]) · Source

Returns a polyhedral projection based on the polygons, arranged in a tree according to the parents list. polygons are a GeoJSON FeatureCollection of geoVoronoi cells, which should indicate the corresponding sites (see d3-geo-voronoi). An optional faceProjection is passed to d3.geoPolyhedral() -- note that the gnomonic projection on the polygons’ sites is the only faceProjection that works in the general case.

The .parents([parents]), .polygons([polygons]), .faceProjection([faceProjection]) set and read the corresponding options. Use .faceFind(voronoi.find) for faster results.

d3.geoCubic() · Source, Examples

The cubic projection.

d3.geoDodecahedral() · Source, Examples

The dodecahedral projection.

d3.geoIcosahedral() · Source, Examples

The icosahedral projection.

d3.geoAirocean() · Source, Examples

Buckminster Fuller’s Airocean projection (also known as “Dymaxion”), based on a very specific arrangement of the icosahedron which allows continuous continent shapes. Fuller’s triangle transformation, as formulated by Robert W. Gray (and implemented by Philippe Rivière), makes the projection almost equal-area.

d3.geoCahillKeyes() · Source, Examples 
d3.geoCahillKeyes

The Cahill-Keyes projection, designed by Gene Keyes (1975), is built on Bernard J. S. Cahill’s 1909 octant design. Implementation by Mary Jo Graça (2011), ported to D3 by Enrico Spinielli (2013).

d3.geoImago() · Source, Examples

The Imago projection, engineered by Justin Kunimune (2017), is inspired by Hajime Narukawa’s AuthaGraph design (1999).

imago.k([k])

Exponent. Useful values include 0.59 (default, minimizes angular distortion of the continents), 0.68 (gives the closest approximation of the Authagraph) and 0.72 (prevents kinks in the graticule).

imago.shift([shift])

Horizontal shift. Defaults to 1.16.

d3.geoTetrahedralLee() · Source, Examples 
d3.geoLeeRaw

Lee’s tetrahedral conformal projection.

Default angle is +30°, apex up (-30° for base up, apex down).

Default aspect uses projection.rotate([30, 180]) and has the North Pole at the triangle’s center -- use projection.rotate([-30, 0]) for the South aspect.

d3.geoCox() · Source, Examples 
d3.geoCoxRaw

The Cox conformal projection.

d3.geoComplexLog([planarProjectionRaw[, cutoffLatitude]]) · Source, Example 
d3.geoComplexLogRaw([planarProjectionRaw])

Complex logarithmic view. This projection is based on the papers by Joachim Böttger et al.:

The specified raw projection planarProjectionRaw is used to project onto the complex plane on which the complex logarithm is applied. Recommended are azimuthal equal-area (default) or azimuthal equidistant.

cutoffLatitude is the latitude relative to the projection center at which to cutoff/clip the projection, lower values result in more detail around the projection center. Value must be < 0 because complex log projects the origin to infinity.

complexLog.planarProjectionRaw([projectionRaw])

If projectionRaw is specified, sets the planar raw projection. See above. If projectionRaw is not specified, returns the current planar raw projection.

complexLog.cutoffLatitude([latitude])

If latitude is specified, sets the cutoff latitude. See above. If latitude is not specified, returns the current cutoff latitude.

Author: d3
Source Code: https://github.com/d3/d3-geo-polygon 
License: View license

#javascript #3d #polygon #map 

D3-geo-polygon: Clipping & Geometric Operations for Spherical Polygons
Best of Crypto

Best of Crypto

1656201660

Curve.fi Exchange Implementation for Polygon

curve-contract-polygon

Curve.fi exchange implementation for Polygon.

Testing and Development

Dependencies

Setup

  1. To get started, first create and initialize a Python virtual environment.
  2. clone the repo and install the developer dependencies:
git clone https://github.com/curvefi/curve-contract-polygon.git
cd curve-contract-polygon
pip install -r requirements.txt

3.   Add Polygon to your local brownie networks:

brownie networks import network-config.yaml

Running the Tests

Testing is done against a forked mainnet. To run the entire suite:

brownie test

To run tests on a specific pool:

brownie test --pool <POOL NAME>

Valid pool names are the names of the subdirectories within contracts/pools.

You can optionally include the --coverage flag to view a coverage report upon completion of the tests.

Download Details:
Author: curvefi
Source Code: https://github.com/curvefi/curve-contract-polygon
License: View license

#curve #dao #blockchain #smartcontract #polygon #python

Curve.fi Exchange Implementation for Polygon
Saul  Alaniz

Saul Alaniz

1655776800

Creación De Una Aplicación DeFi De Pila Completa Con Polygon

DeFi es ahora un tema importante de discusión en el espacio de las criptomonedas. DeFi significa "finanzas descentralizadas", lo que significa que no hay una autoridad central que vigile y controle la transferencia de fondos. Esto también significa que las transacciones en DeFi son P2P (peer to peer), lo que significa que ninguna autoridad central es responsable de la transferencia y los fondos se envían directamente de una entidad a otra.

En este artículo, aprenderemos cómo comenzar con DeFi creando una aplicación DeFi de pila completa en la cadena Polygon utilizando Next.js como interfaz. Esta aplicación venderá y comprará OKToken (un token ficticio) del usuario. Sin embargo, cada transacción de compra reduce un token de la cantidad de tokens que puede obtener por MATIC (la venta aumenta este número en uno). Esta no es una demostración ideal, pero de esta manera puede comprender cómo usar su propia lógica en los contratos inteligentes de Solidity y aprender a crear su propia aplicación DeFi de pila completa usando Polygon.

Requisitos

Para comenzar con este tutorial, asegúrese de tener lo siguiente:

Ahora que ha verificado los requisitos, procedamos a crear nuestro proyecto Hardhat para que funcione con nuestros contratos inteligentes de Solidity .

Creación de un proyecto de casco

Navegue a un directorio seguro y ejecute el siguiente comando en la terminal para inicializar su proyecto Hardhat:

npx hardhat

Una vez que ejecute el comando, debería ver el siguiente asistente de inicialización de Hardhat en su terminal.

En la lista, elija Crear un proyecto de ejemplo avanzado . Luego se le preguntará dónde desea inicializar el proyecto Hardhat; no cambie el campo, simplemente presione Entrar para que el proyecto se inicialice en el directorio actual.

Luego se le preguntará si desea o no instalar las dependencias requeridas para que se ejecute su proyecto Hardhat. Presiona y porque necesitaremos estas dependencias, e instalarlas ahora mismo es la mejor idea.

Se iniciará la instalación de las dependencias y puede tardar unos segundos o minutos, según el equipo que esté ejecutando. Ahora, ejecute el siguiente comando en la terminal para instalar otra dependencia que necesitaremos para facilitar el desarrollo de nuestro contrato Solidity:

npm install @openzeppelin/contracts

OpenZeppelin proporciona estándares de contratos inteligentes que podemos usar en nuestros propios contratos inteligentes para crear fácilmente contratos Ownable, ERC-20 y ERC-721, y más.

Una vez que las dependencias se hayan instalado correctamente, abra el directorio en un editor de código. Usaré VS Code para este tutorial.

Crearemos dos contratos inteligentes: el primero será nuestro propio token ERC-20 y el segundo será un contrato de proveedor, lo que facilitará la compra y venta de estos tokens.

Creando nuestros contratos inteligentes

Ahora, vaya a la contractscarpeta y cree un nuevo archivo Solidity llamado OKToken.sol, que contendrá nuestro contrato de token ERC-20.

Use el siguiente código para este archivo:

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract OKToken is ERC20 {
    constructor() ERC20("OKT", "OKToken"){
        _mint(msg.sender, 10000 * 10 ** 18);
    }
}

En el código anterior, estamos importando el ERC20.solarchivo desde @openzeppelin/contractsel cual nos ayudará a comenzar fácilmente con un token ERC-20. Luego, en el constructor, proporcionamos el símbolo "OKT"y el nombre "OKToken"de nuestro token.

¡Eso es todo por el contrato simbólico! Ahora, trabajemos en el contrato de proveedor. Debajo de la contractscarpeta, cree un nuevo archivo llamado OKVendor.solcon el siguiente código:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./OKToken.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract OKVendor is Ownable {
  OKToken yourToken;
  uint256 public tokensPerNativeCurrency = 100;
  event BuyTokens(address buyer, uint256 amountOfNativeCurrency, uint256 amountOfTokens);
  constructor(address tokenAddress) {
    yourToken = OKToken(tokenAddress);
  }

  function buyTokens() public payable returns (uint256 tokenAmount) {
    require(msg.value > 0, "You need to send some NativeCurrency to proceed");
    uint256 amountToBuy = msg.value * tokensPerNativeCurrency;

    uint256 vendorBalance = yourToken.balanceOf(address(this));
    require(vendorBalance >= amountToBuy, "Vendor contract has not enough tokens to perform transaction");

    (bool sent) = yourToken.transfer(msg.sender, amountToBuy);
    require(sent, "Failed to transfer token to user");
    tokensPerNativeCurrency = tokensPerNativeCurrency - 1;

    emit BuyTokens(msg.sender, msg.value, amountToBuy);
    return amountToBuy;
  }
  function sellTokens(uint256 tokenAmountToSell) public {

    require(tokenAmountToSell > 0, "Specify an amount of token greater than zero");

    uint256 userBalance = yourToken.balanceOf(msg.sender);
    require(userBalance >= tokenAmountToSell, "You have insufficient tokens");

    uint256 amountOfNativeCurrencyToTransfer = tokenAmountToSell / tokensPerNativeCurrency;
    uint256 ownerNativeCurrencyBalance = address(this).balance;
    require(ownerNativeCurrencyBalance >= amountOfNativeCurrencyToTransfer, "Vendor has insufficient funds");
    (bool sent) = yourToken.transferFrom(msg.sender, address(this), tokenAmountToSell);
    require(sent, "Failed to transfer tokens from user to vendor");

    (sent,) = msg.sender.call{value: amountOfNativeCurrencyToTransfer}("");
    tokensPerNativeCurrency = tokensPerNativeCurrency + 1;
    require(sent, "Failed to send NativeCurrency to the user");
  }
  function getNumberOfTokensInNativeCurrency() public view returns(uint256) {
    return tokensPerNativeCurrency;
  }

  function withdraw() public onlyOwner {
    uint256 ownerBalance = address(this).balance;
    require(ownerBalance > 0, "No NativeCurrency present in Vendor");
    (bool sent,) = msg.sender.call{value: address(this).balance}("");
    require(sent, "Failed to withdraw");
  }
}

Esto nos ayudará a facilitar la compra y venta de tokens.

En el contrato anterior, primero importamos nuestro contrato de token, que necesitamos para interactuar con nuestro contrato de token mediante el contrato de proveedor y las funciones de llamada.

También estamos importando Ownable.soldesde @openzeppelin/contracts. Esto significa que el propietario del contrato inteligente puede transferir su propiedad y tener acceso a funciones exclusivas para propietarios.

Después de inicializar el contrato inteligente, definimos la variable tokensPerNativeCurrencyque indica la cantidad de tokens que se pueden comprar con 1 MATIC. Modificaremos este número en función de las transacciones realizadas.

Luego tenemos un constructor que tomará la dirección del contrato de OKToken para que podamos comunicarnos con el contrato implementado y realizar funciones en él.

En la buyTokens()función, estamos realizando verificaciones para garantizar que se envíe la cantidad adecuada de MATIC al contrato inteligente y que el contrato del proveedor tenga la cantidad requerida de tokens. Luego llamamos a la función transfer()desde la instancia de OKToken que creamos previamente para transferir los tokens al remitente de la solicitud.

En la sellTokens()función, estamos realizando comprobaciones para asegurarnos de que el remitente de la solicitud tenga suficientes tokens y si el contrato del proveedor tiene suficiente MATIC para devolver al remitente de la solicitud. Luego, usamos la transferFrom()función de la instancia de OKToken que creamos previamente para transferir los tokens de la billetera del remitente de la solicitud al contrato inteligente. Sin embargo, el remitente debe aprobar esta transacción; realizamos esta aprobación del lado del cliente antes de realizar la solicitud. Cubriremos esta parte cuando hagamos el front-end de esta aplicación.

Por último, tenemos la withdraw()función, a la que solo puede acceder el propietario de los contratos. Les permite retirar todas las MATIC presentes en el contrato.

Ahora que tenemos listos los contratos inteligentes, ¡vamos a implementarlos en la red de prueba de Polygon Mumbai!

Desplegando nuestros contratos inteligentes

Crearemos un script para implementar nuestro contrato en Polygon Mumbai. Una vez que se implementen los contratos, enviaremos mediante programación todos los tokens almacenados en la billetera del implementador al contrato del proveedor.

Primero vaya a hardhat.config.jsy debajo module.exports, agregue el siguiente objeto para que Hardhat sepa a qué red conectarse:

networks: {
  mumbai: {
    url: "https://matic-mumbai.chainstacklabs.com",
    accounts: ["PRIVATE KEY HERE"],
  }
}

Estamos proporcionando un nombre a la red ( mumbaien este caso) y proporcionando una URL de RPC. La URL de RPC mencionada es para Polygon Mumbai. Si desea utilizar Polygon Mainnet, puede elegir su URL de RPC . Recuerde ingresar su propia clave privada de billetera con alguna prueba MATIC para pagar las tarifas de gas involucradas en el proceso de implementación del contrato inteligente.

Ahora, debajo de la scriptscarpeta, cree un nuevo archivo llamado deploy.js. Pega lo siguiente:

const { BigNumber, utils } = require("ethers");
const hardhat = require("hardhat");
async function main() {
  const OKToken = await hardhat.ethers.getContractFactory("OKToken");
  const oktoken = await OKToken.deploy();
  await oktoken.deployed();
  console.log("[] OKToken deployed to address: " + oktoken.address);
  const OKVendor = await hardhat.ethers.getContractFactory("OKVendor");
  const okvendor = await OKVendor.deploy(oktoken.address);
  console.log("[] OKVendor deployed to address: " + okvendor.address);
  await oktoken.deployed();
  // Transfer oktokens to vendor
  await oktoken.functions.transfer(okvendor.address, utils.parseEther("10000"));
  console.log("[] Tokens transferred to OKVendor");
}
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
});

En el archivo anterior, le indicamos a Hardhat cómo implementar nuestro contrato. La main()función es el punto de entrada aquí. Primero, obtenemos el OKTokencontrato y lo implementamos. Luego, obtenemos el OKVendorcontrato, proporcionamos OKTokenla dirección del contrato en el constructor e implementamos el contrato. Luego, transferimos todos los fondos de OKTokencontrato a OKVendorcontrato.

Ejecute el siguiente comando en la terminal para ejecutar el script e implementar nuestros contratos en la red de Polygon Mumbai:

npx hardhat run --network mumbai scripts/deploy.js --show-stack-traces

Tenga en cuenta que el nombre de la red debe coincidir con el mencionado en hardhat.config.js. Después de ejecutar el script, los contratos deberían implementarse y debería ver lo siguiente en su terminal:

Si ve un resultado similar a este, sus contratos inteligentes se implementaron y configuraron correctamente. Ahora, procedamos a crear nuestra aplicación Next.js.

Creación de una aplicación DeFi Next.js

En el mismo directorio, ejecute el siguiente comando en la terminal para crear su aplicación Next.js:

npx create-next-app frontend

El comando anterior creará una nueva aplicación e instalará automáticamente las dependencias necesarias.

Navegue a la frontendcarpeta y use el siguiente comando en la terminal para instalar dependencias adicionales, que nos ayudarán a interactuar con nuestros contratos inteligentes:

yarn add @thirdweb-dev/react @thirdweb-dev/sdk ethers web3

Estamos instalando @thirdweb-dev/reacty @thirdweb-dev/sdkpara que podamos autenticar fácilmente al usuario y conectar sus billeteras a nuestra aplicación usando MetaMask . etherses una dependencia necesaria para ThirdWeb, por lo que también debemos instalarla. Finalmente, estamos instalando web3para que podamos interactuar con nuestro contrato inteligente.

Agregar el tercer proveedor web

Para comenzar, debemos envolver nuestra aplicación dentro de un thirdwebProviderpara que Thirdweb pueda funcionar correctamente.

Vaya a su _app.jsarchivo en la pagescarpeta y agregue lo siguiente:

import { thirdwebProvider, ChainId } from "@thirdweb-dev/react";
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
  return (
    <thirdwebProvider desiredChainId={ChainId.Mumbai}>
      <Component {...pageProps} />
    </thirdwebProvider>
  );
}
export default MyApp;

En el código anterior, estamos importando thirdwebProvidery adjuntando nuestra aplicación dentro de él. También proporcionamos una desiredChainIdidentificación de cadena de Polygon Mumbai. También puede usar la identificación de la cadena para Polygon Mainnet si lo desea.

Cree un nuevo archivo en la raíz de su aplicación Next.js llamado contracts.jsy agregue el siguiente contenido:

export const oktoken = {
  contractAddress: "0xE83DD81890C76BB8c4b8Bc6365Ad95E5e71495E5",
  abi: [
    {
      inputs: [],
      stateMutability: "nonpayable",
      type: "constructor",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "owner",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        },
      ],
      name: "Approval",
      type: "event",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "from",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        },
      ],
      name: "Transfer",
      type: "event",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "owner",
          type: "address",
        },
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
      ],
      name: "allowance",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "approve",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "account",
          type: "address",
        },
      ],
      name: "balanceOf",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "decimals",
      outputs: [
        {
          internalType: "uint8",
          name: "",
          type: "uint8",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "subtractedValue",
          type: "uint256",
        },
      ],
      name: "decreaseAllowance",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "addedValue",
          type: "uint256",
        },
      ],
      name: "increaseAllowance",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "name",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "symbol",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "totalSupply",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "transfer",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "from",
          type: "address",
        },
        {
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "transferFrom",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
  ],
};
export const okvendor = {
  contractAddress: "0xAa3b8cbB24aF3EF68a0B1760704C969E57c53D7A",
  abi: [
    {
      inputs: [
        {
          internalType: "address",
          name: "tokenAddress",
          type: "address",
        },
      ],
      stateMutability: "nonpayable",
      type: "constructor",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: false,
          internalType: "address",
          name: "buyer",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "amountOfNativeCurrency",
          type: "uint256",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "amountOfTokens",
          type: "uint256",
        },
      ],
      name: "BuyTokens",
      type: "event",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "previousOwner",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "newOwner",
          type: "address",
        },
      ],
      name: "OwnershipTransferred",
      type: "event",
    },
    {
      inputs: [],
      name: "buyTokens",
      outputs: [
        {
          internalType: "uint256",
          name: "tokenAmount",
          type: "uint256",
        },
      ],
      stateMutability: "payable",
      type: "function",
    },
    {
      inputs: [],
      name: "getNumberOfTokensInNativeCurrency",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "owner",
      outputs: [
        {
          internalType: "address",
          name: "",
          type: "address",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "renounceOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "uint256",
          name: "tokenAmountToSell",
          type: "uint256",
        },
      ],
      name: "sellTokens",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "tokensPerNativeCurrency",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "newOwner",
          type: "address",
        },
      ],
      name: "transferOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "withdraw",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
  ],
};

Recuerde reemplazar las direcciones del contrato con las suyas para que la aplicación Next.js intente conectarse al contrato inteligente correcto.

Ahora comencemos a codificar nuestra aplicación. Abra index.jsel archivo en la pagescarpeta y agregue lo siguiente:

import { useAddress, useContract, useMetamask } from "@thirdweb-dev/react";
import Head from "next/head";
import Image from "next/image";
import { oktoken, okvendor } from "../contracts";
import styles from "../styles/Home.module.css";
import { useEffect, useState } from "react";
import Web3 from "web3";
const web3 = new Web3(Web3.givenProvider);
export default function Home() {
  const [tokensPerCurrency, setTokensPerCurrency] = useState(0);
  const [tokens, setTokens] = useState(0);
  const address = useAddress();
  const connectUsingMetamask = useMetamask();
  const account = web3.defaultAccount;
  const purchase = async () => {
    const contract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const ethToSend = tokens / tokensPerCurrency;
    const purchase = await contract.methods.buyTokens().send({
      from: address,
      value: web3.utils.toWei(ethToSend.toString(), "ether"),
    });
    console.log(purchase);
    await fetchPrice();
  };
  const sell = async () => {
    const vendorContract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const tokenContract = new web3.eth.Contract(
      oktoken.abi,
      oktoken.contractAddress
    );
    const approve = await tokenContract.methods
      .approve(
        okvendor.contractAddress,
        web3.utils.toWei(tokens.toString(), "ether")
      )
      .send({
        from: address,
      });
    const sellTokens = await vendorContract.methods.sellTokens(tokens).send({
      from: address,
    });
    await fetchPrice();
  };
  const fetchPrice = async () => {
    const contract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const priceFromContract = await contract.methods
      .getNumberOfTokensInNativeCurrency()
      .call();
    setTokensPerCurrency(priceFromContract);
  };
  useEffect(() => {
    fetchPrice();
  }, []);
  return (
    <div>
      <Head>
        <title>Exchange OKTokens</title>
      </Head>
      {address ? (
        <div>
          <p>Tokens per currency: {tokensPerCurrency}</p>
          <div>
            <input
              type="number"
              value={tokens}
              onChange={(e) => setTokens(e.target.value)}
            />
          </div>
          <button onClick={purchase}>Purchase</button>
          <button onClick={sell}>Sell</button>
        </div>
      ) : (
        <div>
          <button onClick={connectUsingMetamask}>Connect using MetaMask</button>
        </div>
      )}
    </div>
  );
}

Este es un bloque de código largo, así que veamos qué está haciendo el código paso a paso:

  • Inicializar el web3paquete usando un proveedor configurado por thirdweb
  • Usar enlaces de terceros useMetamask()para autenticarse y useAddress()verificar el estado de autenticación, luego mostrar el botón de inicio de sesión si el usuario no tiene una billetera conectada usando MetaMask
  • Configuración de varios estados para mapear cuadros de texto en nuestra aplicación
  • Crear una fetchPrice()función para interactuar con nuestro contrato inteligente y verificar cuántos tokens puede obtener un MATIC, al mismo tiempo que crea un useEffectpara verificar este precio cada vez que se carga la página
  • Creando una purchase()función, que inicializa nuestro contrato de proveedor y llama a la buyTokens()función desde el contrato, luego envía algo de MATIC junto con esta transacción. Luego, llamamos fetchPrice()para que se muestre el último precio .

Finalmente, estamos creando una sell()función que inicializa tanto el token como el contrato de proveedor. Primero, interactuamos con la approve()función del contrato de token y permitimos que el contrato del proveedor transfiera fondos en nuestro nombre. Luego estamos llamando sellTokens()a la función del contrato del proveedor para finalmente vender los tokens y recibir MATIC. También estamos llamando fetchPrice()para obtener el último precio después de la transacción.

¡Nuestra sencilla aplicación DeFi está completa! Puede ver esta aplicación en su navegador ejecutando el siguiente comando:

yarn dev

Ahora, una vez que visite http://localhost:3000 , debería ver la siguiente pantalla y debería poder realizar transacciones.

Conclusión

Este fue un tutorial simple sobre cómo crear su propia aplicación DeFi de pila completa basada en Polygon. Puede implementar su propia lógica en los contratos inteligentes para hacerlo aún mejor según su organización. Sugiero jugar con el código para que puedas aprender de la mejor manera posible.

Esta historia se publicó originalmente en https://blog.logrocket.com/creating-full-stack-defi-app-polygon/

#defi #polygon #nextjs 

Creación De Una Aplicación DeFi De Pila Completa Con Polygon

Polygonを使用したフルスタックDeFiアプリの作成

DeFiは現在、暗号通貨の分野での主要な議論のトピックです。DeFiは「分散型ファイナンス」の略で、資金の移動を監視および制御する中央機関がないことを意味します。これは、DeFiのトランザクションがP2P(ピアツーピア)であることも意味します。つまり、転送に責任を持つ中央機関はなく、資金はあるエンティティから別のエンティティに直接送られます。

この記事では、Next.jsをフロントエンドとして使用してPolygonチェーン上にフルスタックのDeFiアプリを作成することにより、DeFiの使用を開始する方法を学習します。このアプリは、ユーザーからOKToken(架空のトークン)を売買します。ただし、購入トランザクションごとに、 MATICごとに取得できるトークンの量から1つのトークンが減少します(販売すると、この数が1つ増えます)。これは理想的なデモンストレーションではありませんが、この方法で、Solidityスマートコントラクトで独自のロジックを使用する方法を理解し、Polygonを使用して独自のフルスタックDeFiアプリを作成する方法を学ぶことができます。

要件

このチュートリアルを開始するには、次のものがあることを確認してください。

要件を確認したので、Solidityスマートコントラクトと連携するHardhatプロジェクトの作成に進みましょう。

Hardhatプロジェクトの作成

安全なディレクトリに移動し、ターミナルで次のコマンドを実行して、Hardhatプロジェクトを初期化します。

npx hardhat

コマンドを実行すると、ターミナルに次のHardhat初期化ウィザードが表示されます。

リストから、[高度なサンプルプロジェクトの作成]を選択します。次に、Hardhatプロジェクトを初期化する場所を尋ねられます。フィールドを変更せずに、Enterキーを押すだけで、プロジェクトが現在のディレクトリで初期化されます。

次に、Hardhatプロジェクトの実行に必要な依存関係をインストールするかどうかを尋ねられます。これらの依存関係が必要になるため、 yを押します。今すぐインストールするのが最善の方法です。

依存関係のインストールが開始され、実行しているマシンによっては数秒または数分かかる場合があります。次に、ターミナルで次のコマンドを実行して、Solidityコントラクトの開発を容易にするために必要な別の依存関係をインストールします。

npm install @openzeppelin/contracts

OpenZeppelinは、独自のスマートコントラクトで使用できるスマートコントラクト標準を提供し、Ownable、ERC-20およびERC-721コントラクトなどを簡単に作成できます。

依存関係が正常にインストールされたら、コードエディタでディレクトリを開きます。このチュートリアルではVSCodeを使用します。

2つのスマートコントラクトを作成します。1つはERC-20トークン自体で、もう1つはベンダーコントラクトです。これにより、これらのトークンの売買が容易になります。

スマートコントラクトの作成

次に、フォルダーに移動して、ERC-20トークンコントラクトを含むcontractsという名前の新しいSolidityファイルを作成します。OKToken.sol

このファイルには次のコードを使用します。

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract OKToken is ERC20 {
    constructor() ERC20("OKT", "OKToken"){
        _mint(msg.sender, 10000 * 10 ** 18);
    }
}

上記のコードでは、ERC-20トークンの使用を簡単に開始するのに役立つERC20.solファイルをインポートしています。@openzeppelin/contracts次に、コンストラクターで、トークンのシンボル"OKT"と名前を指定します。"OKToken"

トークン契約は以上です!それでは、ベンダー契約に取り組みましょう。フォルダの下に、次のコードでcontracts名前を付けた新しいファイルを作成します。OKVendor.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./OKToken.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract OKVendor is Ownable {
  OKToken yourToken;
  uint256 public tokensPerNativeCurrency = 100;
  event BuyTokens(address buyer, uint256 amountOfNativeCurrency, uint256 amountOfTokens);
  constructor(address tokenAddress) {
    yourToken = OKToken(tokenAddress);
  }

  function buyTokens() public payable returns (uint256 tokenAmount) {
    require(msg.value > 0, "You need to send some NativeCurrency to proceed");
    uint256 amountToBuy = msg.value * tokensPerNativeCurrency;

    uint256 vendorBalance = yourToken.balanceOf(address(this));
    require(vendorBalance >= amountToBuy, "Vendor contract has not enough tokens to perform transaction");

    (bool sent) = yourToken.transfer(msg.sender, amountToBuy);
    require(sent, "Failed to transfer token to user");
    tokensPerNativeCurrency = tokensPerNativeCurrency - 1;

    emit BuyTokens(msg.sender, msg.value, amountToBuy);
    return amountToBuy;
  }
  function sellTokens(uint256 tokenAmountToSell) public {

    require(tokenAmountToSell > 0, "Specify an amount of token greater than zero");

    uint256 userBalance = yourToken.balanceOf(msg.sender);
    require(userBalance >= tokenAmountToSell, "You have insufficient tokens");

    uint256 amountOfNativeCurrencyToTransfer = tokenAmountToSell / tokensPerNativeCurrency;
    uint256 ownerNativeCurrencyBalance = address(this).balance;
    require(ownerNativeCurrencyBalance >= amountOfNativeCurrencyToTransfer, "Vendor has insufficient funds");
    (bool sent) = yourToken.transferFrom(msg.sender, address(this), tokenAmountToSell);
    require(sent, "Failed to transfer tokens from user to vendor");

    (sent,) = msg.sender.call{value: amountOfNativeCurrencyToTransfer}("");
    tokensPerNativeCurrency = tokensPerNativeCurrency + 1;
    require(sent, "Failed to send NativeCurrency to the user");
  }
  function getNumberOfTokensInNativeCurrency() public view returns(uint256) {
    return tokensPerNativeCurrency;
  }

  function withdraw() public onlyOwner {
    uint256 ownerBalance = address(this).balance;
    require(ownerBalance > 0, "No NativeCurrency present in Vendor");
    (bool sent,) = msg.sender.call{value: address(this).balance}("");
    require(sent, "Failed to withdraw");
  }
}

これにより、トークンの売買が容易になります。

上記のコントラクトでは、最初にトークンコントラクトをインポートします。これは、ベンダーコントラクトと呼び出し関数を使用してトークンコントラクトと対話するために必要です。

Ownable.solからもインポートしてい@openzeppelin/contractsます。これは、スマートコントラクトの所有者がその所有権を譲渡し、所有者のみの機能にアクセスできることを意味します。

tokensPerNativeCurrencyスマートコントラクトを初期化した後、 1つのMATICを使用して購入できるトークンの数を示す変数を定義します。行われた取引に基づいて、この数を変更します。

次に、デプロイされたコントラクトと通信してそれらに対して機能を実行できるように、OKTokenのコントラクトアドレスを取得するコンストラクターがあります。

In the buyTokens() function, we are performing checks to ensure the proper amount of MATIC is sent to the smart contract, and that the vendor contract has the required amount of tokens. Then we call the function transfer() from the OKToken instance we previously created to transfer the tokens to the request sender.

このsellTokens()関数では、リクエストの送信者に十分なトークンがあることと、ベンダー契約にリクエストの送信者に送り返すのに十分なMATICがあるかどうかを確認するためのチェックを実行しています。次に、transferFrom()前に作成したOKTokenインスタンスの関数を使用して、リクエスト送信者のウォレットからスマートコントラクトにトークンを転送します。ただし、送信者はこのトランザクションを承認する必要があります。リクエストを行う前に、クライアント側でこの承認を実行します。このアプリケーションのフロントエンドを作成するときに、この部分について説明します。

最後にwithdraw()、契約の所有者のみがアクセスできる機能があります。それは彼らが契約に存在するすべてのMATICを撤回することを可能にします。

スマートコントラクトの準備ができたので、それらをPolygonMumbaiテストネットにデプロイしましょう!

スマートコントラクトの展開

契約をPolygonMumbaiにデプロイするためのスクリプトを作成します。コントラクトがデプロイされると、デプロイヤーのウォレットに保存されているすべてのトークンがベンダーコントラクトにプログラムで送信されます。

まず、に移動しhardhat.config.jsmodule.exports次のオブジェクトを追加して、Hardhatが接続するネットワークを認識できるようにします。

networks: {
  mumbai: {
    url: "https://matic-mumbai.chainstacklabs.com",
    accounts: ["PRIVATE KEY HERE"],
  }
}

ネットワークに名前(mumbaiこの場合)とRPCURLを提供しています。上記のRPCURLは、PolygonMumbai用です。Polygon Mainnetを使用する場合は、RPCURLを選択できます。スマートコントラクトの展開プロセスに関連するガス料金を支払うために、テストMATICを使用して独自のウォレット秘密鍵を入力することを忘れないでください。

次に、フォルダの下に、scriptsという名前の新しいファイルを作成しますdeploy.js。次のように貼り付けます。

const { BigNumber, utils } = require("ethers");
const hardhat = require("hardhat");
async function main() {
  const OKToken = await hardhat.ethers.getContractFactory("OKToken");
  const oktoken = await OKToken.deploy();
  await oktoken.deployed();
  console.log("[] OKToken deployed to address: " + oktoken.address);
  const OKVendor = await hardhat.ethers.getContractFactory("OKVendor");
  const okvendor = await OKVendor.deploy(oktoken.address);
  console.log("[] OKVendor deployed to address: " + okvendor.address);
  await oktoken.deployed();
  // Transfer oktokens to vendor
  await oktoken.functions.transfer(okvendor.address, utils.parseEther("10000"));
  console.log("[] Tokens transferred to OKVendor");
}
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
});

上記のファイルでは、Hardhatに契約の展開方法を指示しています。main()関数はここでのエントリポイントです。まず、OKToken契約を取得して展開します。次に、OKVendorコントラクトを取得OKTokenし、コンストラクターでコントラクトアドレスを指定して、コントラクトをデプロイします。次に、すべての資金をOKToken契約から契約に移しますOKVendor

ターミナルで次のコマンドを実行してスクリプトを実行し、契約をPolygonMumbaiネットワークに展開します。

npx hardhat run --network mumbai scripts/deploy.js --show-stack-traces

ネットワーク名は、で説明されているものと一致する必要があることに注意してくださいhardhat.config.js。スクリプトを実行した後、コントラクトがデプロイされ、ターミナルに次のように表示されます。

これに似た出力が表示された場合は、スマートコントラクトが正常にデプロイおよび構成されています。それでは、Next.jsアプリケーションの作成に進みましょう。

Next.jsDeFiアプリの作成

同じディレクトリで、ターミナルで次のコマンドを実行してNext.jsアプリを作成します。

npx create-next-app frontend

上記のコマンドは、新しいアプリを作成し、必要な依存関係を自動的にインストールします。

フォルダに移動frontendし、ターミナルで次のコマンドを使用して追加の依存関係をインストールします。これにより、スマートコントラクトを操作できます。

yarn add @thirdweb-dev/react @thirdweb-dev/sdk ethers web3

MetaMaskを使用してユーザーを簡単に認証し、ウォレットをアプリに接続できるように、をインストール@thirdweb-dev/reactしています。はthirdwebに必須の依存関係であるため、これもインストールする必要があります。最後に、スマートコントラクトとやり取りできるようにインストールします。@thirdweb-dev/sdkethersweb3

thirdwebプロバイダーの追加

thirdwebProvider開始するには、thirdwebが正しく機能できるように、アプリを内包する必要があります。

_app.jsフォルダの下のファイルに移動しpages、以下を追加します。

import { thirdwebProvider, ChainId } from "@thirdweb-dev/react";
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
  return (
    <thirdwebProvider desiredChainId={ChainId.Mumbai}>
      <Component {...pageProps} />
    </thirdwebProvider>
  );
}
export default MyApp;

上記のコードでは、アプリをインポートしthirdwebProviderてその中に囲んでいます。desiredChainIdポリゴンムンバイのチェーンIDもご用意しております。必要に応じて、PolygonMainnetのチェーンIDを使用することもできます。

Next.jsアプリのルートにという新しいファイルを作成しcontracts.js、次のコンテンツを追加します。

export const oktoken = {
  contractAddress: "0xE83DD81890C76BB8c4b8Bc6365Ad95E5e71495E5",
  abi: [
    {
      inputs: [],
      stateMutability: "nonpayable",
      type: "constructor",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "owner",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        },
      ],
      name: "Approval",
      type: "event",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "from",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        },
      ],
      name: "Transfer",
      type: "event",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "owner",
          type: "address",
        },
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
      ],
      name: "allowance",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "approve",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "account",
          type: "address",
        },
      ],
      name: "balanceOf",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "decimals",
      outputs: [
        {
          internalType: "uint8",
          name: "",
          type: "uint8",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "subtractedValue",
          type: "uint256",
        },
      ],
      name: "decreaseAllowance",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "addedValue",
          type: "uint256",
        },
      ],
      name: "increaseAllowance",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "name",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "symbol",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "totalSupply",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "transfer",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "from",
          type: "address",
        },
        {
          internalType: "address",
          name: "to",
          type: "address",
        },
        {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        },
      ],
      name: "transferFrom",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        },
      ],
      stateMutability: "nonpayable",
      type: "function",
    },
  ],
};
export const okvendor = {
  contractAddress: "0xAa3b8cbB24aF3EF68a0B1760704C969E57c53D7A",
  abi: [
    {
      inputs: [
        {
          internalType: "address",
          name: "tokenAddress",
          type: "address",
        },
      ],
      stateMutability: "nonpayable",
      type: "constructor",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: false,
          internalType: "address",
          name: "buyer",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "amountOfNativeCurrency",
          type: "uint256",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "amountOfTokens",
          type: "uint256",
        },
      ],
      name: "BuyTokens",
      type: "event",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "previousOwner",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "newOwner",
          type: "address",
        },
      ],
      name: "OwnershipTransferred",
      type: "event",
    },
    {
      inputs: [],
      name: "buyTokens",
      outputs: [
        {
          internalType: "uint256",
          name: "tokenAmount",
          type: "uint256",
        },
      ],
      stateMutability: "payable",
      type: "function",
    },
    {
      inputs: [],
      name: "getNumberOfTokensInNativeCurrency",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "owner",
      outputs: [
        {
          internalType: "address",
          name: "",
          type: "address",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "renounceOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "uint256",
          name: "tokenAmountToSell",
          type: "uint256",
        },
      ],
      name: "sellTokens",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "tokensPerNativeCurrency",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [
        {
          internalType: "address",
          name: "newOwner",
          type: "address",
        },
      ],
      name: "transferOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "withdraw",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
  ],
};

Next.jsアプリが正しいスマートコントラクトに接続しようとするように、コントラクトアドレスを自分のものに置き換えることを忘れないでください。

それでは、アプリのコーディングを始めましょう。index.jsフォルダの下のファイルを開きpages、以下を追加します。

import { useAddress, useContract, useMetamask } from "@thirdweb-dev/react";
import Head from "next/head";
import Image from "next/image";
import { oktoken, okvendor } from "../contracts";
import styles from "../styles/Home.module.css";
import { useEffect, useState } from "react";
import Web3 from "web3";
const web3 = new Web3(Web3.givenProvider);
export default function Home() {
  const [tokensPerCurrency, setTokensPerCurrency] = useState(0);
  const [tokens, setTokens] = useState(0);
  const address = useAddress();
  const connectUsingMetamask = useMetamask();
  const account = web3.defaultAccount;
  const purchase = async () => {
    const contract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const ethToSend = tokens / tokensPerCurrency;
    const purchase = await contract.methods.buyTokens().send({
      from: address,
      value: web3.utils.toWei(ethToSend.toString(), "ether"),
    });
    console.log(purchase);
    await fetchPrice();
  };
  const sell = async () => {
    const vendorContract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const tokenContract = new web3.eth.Contract(
      oktoken.abi,
      oktoken.contractAddress
    );
    const approve = await tokenContract.methods
      .approve(
        okvendor.contractAddress,
        web3.utils.toWei(tokens.toString(), "ether")
      )
      .send({
        from: address,
      });
    const sellTokens = await vendorContract.methods.sellTokens(tokens).send({
      from: address,
    });
    await fetchPrice();
  };
  const fetchPrice = async () => {
    const contract = new web3.eth.Contract(
      okvendor.abi,
      okvendor.contractAddress
    );
    const priceFromContract = await contract.methods
      .getNumberOfTokensInNativeCurrency()
      .call();
    setTokensPerCurrency(priceFromContract);
  };
  useEffect(() => {
    fetchPrice();
  }, []);
  return (
    <div>
      <Head>
        <title>Exchange OKTokens</title>
      </Head>
      {address ? (
        <div>
          <p>Tokens per currency: {tokensPerCurrency}</p>
          <div>
            <input
              type="number"
              value={tokens}
              onChange={(e) => setTokens(e.target.value)}
            />
          </div>
          <button onClick={purchase}>Purchase</button>
          <button onClick={sell}>Sell</button>
        </div>
      ) : (
        <div>
          <button onClick={connectUsingMetamask}>Connect using MetaMask</button>
        </div>
      )}
    </div>
  );
}

これは長いコードブロックなので、コードが何をしているのかを段階的に見てみましょう。

  • web3thirdwebによって設定されたプロバイダーを使用してパッケージを初期化する
  • thirdwebフックuseMetamask()を使用して認証とuseAddress()認証状態の確認を行い、ユーザーがMetaMaskを使用してウォレットを接続していない場合はログインボタンをレンダリングします
  • アプリのテキストボックスをマップするためのさまざまな状態の設定
  • fetchPrice()スマートコントラクトと対話し、1つのMATICが取得できるトークンの数を確認する関数を作成すると同時にuseEffect、ページが読み込まれるたびにこの価格を確認する関数を作成します
  • purchase()ベンダーコントラクトを初期化し、コントラクトから関数を呼び出す関数を作成し、buyTokens()このトランザクションと一緒にMATICを送信します。fetchPrice()次に、最新の価格が表示されるように呼び出します

最後に、sell()トークンとベンダー契約の両方を初期化する関数を作成しています。まず、トークンコントラクトのapprove()機能を操作し、ベンダーコントラクトが私たちに代わって資金を転送できるようにします。sellTokens()次に、ベンダー契約から関数を呼び出して、最終的にトークンを販売し、MATICを受け取ります。fetchPrice()また、取引後の最新の価格を取得するために呼び出しています。

シンプルなDeFiアプリが完成しました!次のコマンドを実行すると、ブラウザでこのアプリを表示できます。

yarn dev

これで、 http:// localhost:3000にアクセスすると、次の画面が表示され、トランザクションを実行できるようになります。

結論

これは、Polygonに基づいて独自のフルスタックDeFiアプリを作成する方法に関する簡単なチュートリアルでした。スマートコントラクトに独自のロジックを実装して、組織によってはさらに優れたものにすることができます。可能な限り最善の方法で学習できるように、コードをいじくり回すことをお勧めします。

このストーリーは、もともとhttps://blog.logrocket.com/creating-full-stack-defi-app-polygon/で公開されました

#defi #polygon #nextjs 

Polygonを使用したフルスタックDeFiアプリの作成

Sol Trace: Trace Runtime Failures for Solidity

sol-trace

Trace runtime failures for solidity

Inspired by 0x-monorepo https://github.com/0xProject/0x-monorepo/pull/705

Installation

$ npm install --save sol-trace # or yarn add sol-trace

Usage

Add following code in your truffle test cases:

import { injectInTruffle } from "sol-trace";
injectInTruffle(web3, artifacts);

if your node_modules path need correct you do bellow:

export MODULE_RELATIVE_PATH=../ && truffle test

Demo

Download Details:
Author: maticnetwork
Source Code: https://github.com/maticnetwork/sol-trace
License: MIT license

#polygon  #blockchain  #smartcontract  #web3  #ethereum #javascript 

Sol Trace: Trace Runtime Failures for Solidity