1652838783
Web 3.0 is a concept for the internet's future phase, which envisions a decentralized ecosystem built on blockchain technology. It would be a change from the present ecosystem's centralized mega-platforms and companies, and proponents argue it will address what's wrong with the internet today while also reversing the decline of democracy. So, this scribe video on WEB 3.0 will enlighten you about what is web and how it came into existence, and how it has evolved from web 1.0 to web 2.0 and is now transforming into web 3.0. Web 3.0 is going to revolutionize the internet and also benefit society in so many ways.
#web3 #blockchain #programming
1652838639
codedamn is back with codedamn Accelerators (30-day cohort based courses) that help you get started with an industry level skillset in the span of only 30 days. This live stream would include more details on what it is and how it would work. Sign up here while the seats last: https://codedamn.com/accelerators/web3
#web3 #programming #blockchain
1652766794
Meme Series Part 3
We have seen a lot of volatility in the past week with some stable coins like Luna melting down and going bearish...
#crypto #blockchain #web3
cc; @hashnode #TheHashnodeWriteathon
Read More👇
https://blog.octachart.com/life-of-a-crypto-trader-2
1652691082
In this week's project you're going to learn how to buy NFTs from an NPC Shop and how to create a full on-chain inventory system with Unity and Moralis Web3. Enjoy!
Timestamps:
0:00 - INTRO - Unity Web3 NFT Shop
4:25 - PROJECT STRUCTURE
10:00 - MORALIS WEB3 SERVER
11:33 - MANAGE SHOP ITEMS
29:23 - DEPLOY SMART CONTRACT
36:10 - BUY ITEMS
49:19 - GET NFTs
54:57 - RESULT - Unity Web3 NFT Shop
Download the full sample project here:
https://github.com/MoralisWeb3/youtube-tutorials/tree/main/unity/unity-web3-nft-shop
#nft #solidity #moralis #unity #web3 #programming #blockchain
1652537053
En los últimos dos años, he tratado de aprovechar mi experiencia en ingeniería con la siguiente declaración:
“Aprende cómo funcionan las cosas en las que inviertes e invierte en las cosas que conoces”.
Esto ha llevado a algunas buenas inversiones de alta convicción en tecnología que conocía desde el principio. Asimismo, me he esforzado por aprender sobre las tecnologías en las que invertí ciegamente al principio. Eventualmente, me llevaron por uno de mis mejores viajes de aprendizaje hasta el momento cuando decidí aprender cómo funcionaban las criptomonedas en el núcleo. Después de estudiar los documentos técnicos de la capa 1 (Ethereum, Bitcoin, etc.), reconocí que la forma más rápida de involucrarme sería dominar el concepto de "contratos inteligentes" a través del aprendizaje de Solidity.
Mi experiencia en ingeniería de software hizo que aprender sintaxis fuera extremadamente fácil y, con la ayuda de este gran curso y algunos conocimientos financieros, encontré una nueva disciplina que reunió más intereses que nunca.
Al comenzar a redactar contratos inteligentes e interactuar con el ecosistema web 3.0, me quedé impresionado rápidamente por la optimización de los servicios y la naturaleza colaborativa de este nuevo y valiente mundo. A veces me olvidaba que la moneda y las finanzas eran el caso de uso principal, ya que veía la solidez de las API web 2.0, la OOP, el alojamiento y la estandarización consolidada en una tecnología universal.
Mi conclusión principal: Blockchain es mucho más que una moneda; es la próxima iteración de la construcción en Internet. En este artículo, mi objetivo es proporcionar algunos términos para principiantes y dibujar similitudes en el lenguaje web 2.0 para ayudar a otros tecnólogos a ver el potencial de esta tecnología.
Billeteras, contratos inteligentes, cadenas de bloques y tokens
Comprender cómo los términos de este encabezado son el paso fundamental para comenzar a comprender la cadena de bloques. Estas definiciones solo pretenden complementar el resto de este artículo con algunas definiciones simples, por lo que animo al lector a profundizar en cada una de ellas individualmente si estas descripciones parecen vagas. Si conoce estos términos, le animo a que salte a los temas principales debajo de esta sección.
Cadenas de bloques: redes de servidores que almacenan copias de datos y funcionalidades a las que se puede acceder a través de transacciones una vez que se encuentra un consenso dentro de una cantidad significativa de servidores de que una transacción es válida. Las cadenas de bloques tienen su propia moneda nativa destinada a pagar a estos operadores de servidores por su poder de cómputo en forma de "gas". Esta es la verdadera utilidad de cualquier token de Capa 1: acceso a potencia informática.
Monederos: direcciones en una cadena de bloques a las que se les puede asignar/enviar una parte del token L1 de la red, pueden asignar/enviar el token L1 de la red y pueden firmar transacciones para interactuar con contratos inteligentes con la identidad de la dirección (veremos cómo esto permite otros tokens L2).
Contrato inteligente: una dirección en la cadena de bloques que incluye toda la funcionalidad de una billetera (enviar/recibir L1). Pueden almacenar datos a través de variables de estado (piensen en bases de datos), ejecuten funcionalidades a través de bytecode (piensen en funciones de base de datos/API) e interactúen con otros contratos como una billetera.
Tokens de capa 2: un contrato inteligente que implementa una interfaz (ERC20) con funcionalidad común para facilitar la acuñación, las transferencias, la quema y otras funciones monetarias. Una billetera no "mantiene" tokens L2 de la misma manera que tiene un L1; simplemente puede interactuar con el contrato L2 para transferir tokens, cambiando efectivamente la variable de estado de saldo para su propia dirección y la dirección a la que se está transfiriendo.
APIs en la Era Web 3.0
El flujo de una API Web 2.0 típica se parece a esto:
1. Pagar por una clave de autenticación en un sitio web
2. Escriba un código de procesamiento de cadena para crear una carga útil y/o variables en la cadena de URL
3. Use una biblioteca HTTP específica del idioma para enviar la solicitud de obtención/publicación
4. Después de aprender la estructura JSON de salida, use otra biblioteca para analizar los tipos de datos nativos del lenguaje
Para un ingeniero de software experimentado, este no es un proceso intimidante y solo incluye estos pasos. Sin embargo, la integración de API puede ser tediosa y llevar mucho tiempo con documentación deficiente, tipos de datos de salida difíciles, trabajar con claves pagas y actualizaciones o cambios de API. Un desarrollador nunca sabe realmente lo que obtendrá con algunas API comprensibles y bien documentadas, otras desactualizadas y torpes.
En Web 3.0, se accede a los datos de una manera diferente, lo que resuelve muchos de estos problemas:
1. Otro contrato, desarrollado y desplegado por otras organizaciones o individuos que proporciona algún dato o servicio publica una interfaz (similar a una biblioteca) de sus funciones públicas.
2. En nuestro propio código, podemos importar el código para su interfaz. Luego, conociendo su dirección de contrato, podemos decir con solidez que la implementación de esa interfaz está disponible en la dirección como esta:
IsomeAPI api = IsomeAPI(address);
3. Ahora, podemos usar nuestro nuevo objeto para interactuar con el otro contrato. Debido a que el contrato también tiene solidez incorporada, tanto nuestro propio código como el contrato externo usarán tipos de datos de entrada y salida nativos. Una interacción se ve y se siente como si el objeto estuviera en nuestro contrato:
uint temp = api.getTemp(latitude, longitude);
Esta nueva solución para el acceso a los datos permite una integración rápida y optimizada de tantas fuentes de datos como sea necesario para los desarrolladores. Dada la naturaleza de código abierto, la documentación sigue siendo útil, pero ya no es necesaria, ya que un desarrollador de Solidity puede simplemente mirar el código de la interfaz para responder a sus preguntas interactivas. Al mismo tiempo, permite que surjan protocolos universales. El IERC20 es la interfaz/API para tokens L2. Alimentando la dirección de cualquier token, IERC20 (dirección), los desarrolladores pueden acceder universalmente a cualquier token único y crear el suyo propio en minutos.
Los beneficios no se limitan a la escalabilidad y la reproducibilidad. Debido a los sistemas de pago integrados en L1 y L2, los desarrolladores de contratos/API pueden integrar fácilmente sistemas para cobrar a los usuarios por el uso de una función o acceso a datos. Esto significa que, como desarrollador que utiliza la API, no se requieren tarjetas de crédito, suscripciones ni modelos de precios confusos. Uno simplemente necesita entender cuánto de qué moneda mantener, y los pagos en ambos extremos siempre funcionarán sin problemas.
Finalmente, algunos pueden cuestionar esta noción debido a la incompatibilidad de las solideces con las API Web 2.0 cuyos datos siguen siendo muy necesarios. Afortunadamente, los algoritmos de Oracle basados en eventos como ChainlinkHaber emergido. Estos oráculos acceden a las API de terceros y envían estos datos al mundo de los contratos inteligentes, esencialmente envolviendo las API de la Web 2.0. En el mundo de la Web 3.0, el acceso a estas API ahora es tan fácil como crear un objeto y usar funciones simples para recuperar datos.
Para demostrar la eficacia de las API de la Web 3.0, consideremos cómo se ve el proceso de depositar dinero en una cuenta de corretaje desde la perspectiva de la Web 2.0 y observemos cómo se ve esto en la Web 3.0.
Web 2.0:
1. El backend recibe la aprobación del usuario para llamar a la API de un banco determinado (requiere integración y comprensión de esta API, credenciales, etc.)
2. La API del banco activa ACH/transferencia bancaria a las cuentas de corretaje (ETA: horas a días)
3. Una vez que el corretaje recibe los fondos, el backend llama a la API del corretaje para realizar una operación (probablemente una API, un sistema de credenciales, etc. muy diferente)
4. Se produce el comercio y los resultados deben registrarse explícitamente para la búsqueda
. Aquí hay un ejemplo de código Web 3.0:
contract Swap {
address private constant UNISWAP_V2_ROUTER =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
function swap(
address _tokenIn,
address _tokenOut,
uint _amountIn,
uint _amountOutMin,
) external {
//1. We transfer the users tokens(ERC20) to ourselves after user has approved
IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
//2. We tell the bank/token that the broker can move our funds
IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
//3. We call the Uniswap contract/API which facilitates our trade
IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
_amountIn,
_amountOutMin,
path,
msg.sender,
block.timestamp
);
}
Adaptado de https://solidity-by-example.org/
Como puede ver, hacer una transferencia monetaria compleja con dos servicios distintos crea un dolor de cabeza para los desarrolladores en el trabajo de la Web 2.0 debido a las integraciones de API, las credenciales y los tiempos de espera. En el contrato inteligente Web 3.0 anterior, esto se puede hacer con dos servicios distintos (el token/banco de origen y Uniswap /broker) en unas pocas líneas de código muy legible. Además, esta transacción compleja de FinTech ocurriría en segundos en lugar de días, aunque esto está más allá del alcance de este artículo.
En total, la realización de los beneficios de alojar API en la era de los contratos inteligentes es numerosa. Hemos notado cómo cualquier dato o servicio se puede ver como un objeto con funciones nativas del idioma, los protocolos estándar pueden surgir debido a la naturaleza reproducible de las interfaces con una dirección única y los pagos de API se pueden optimizar. Finalmente, como beneficio adicional, estas API de próxima generación no requieren configuraciones de servidor, mantenimiento o pagos en la nube. Una vez que se implementen, los miles de operadores de blockchain se encargarán de esto y se les pagará a través de las tarifas de gas de cada transacción.
OOP va en línea
La última sección cubre lo que veo como la gran oportunidad para la Web 3.0. Hay una cosa más que quiero resaltar que puede parecer notablemente similar, bueno, es lo mismo, pero la perspectiva proporciona otra forma divertida de ver la Web 3.0. OOP u programación orientada a objetos se refiere al uso de objetos en código que contiene variables y funciones para crear código dinámico y escalable.
Las variables y funciones suenan muy similares al tema principal de este artículo. Los contratos inteligentes son, en efecto, objetos en lenguaje orientado a objetos, y el andamio de su código no se ve diferente a una clase de Java, Python o C# con variables, funciones y un constructor. Entonces, ¿qué significa esto cuando lo juntamos? Los objetos se han conectado.
Esto significa que podemos implementar objetos, con controles de acceso, por supuesto, a los que múltiples "servicios" en forma de contratos pueden acceder y manipular directamente para que otros servicios hagan lo mismo. Tal vez queramos crear un sistema para el historial y la titulación de automóviles complejos. Podemos implementar objetos/contratos para cada vehículo y crear infinitos microservicios en forma de otros contratos inteligentes para realizar muchas acciones diferentes en los mismos objetos y, al mismo tiempo, brindar cierta visibilidad a todos los usuarios. O tal vez solo queremos una forma más limpia de acceder a nuestras propias bases de datos en otros servicios, que podría parecer tan fácil como esto:
interface IDataBase{
//we define some basic functions a database would have
//"contract Database is IDatabase" would implment these functions and hold the data
function setData(bytes data) external returns(bool);
function getData(uint id) external view returns(bytes);
}
contract Service1 {
IDatabase someDatabase;
constructor(address _dbAddress){
//Inform contract that an IDataBase contract will be at _dbAddress
someDatabase = IDataBase(_dbAddress);
}
function data(uint id) public view returns(bytes){
return someDatabase.getData(id);
}
}
contract Service2{
IDatabase someDatabase;
constructor(address _dbAddress){
someDatabase = IDataBase(_dbAddress);
}
}
En este ejemplo, nuestra base de datos está alojada de forma segura en la cadena de bloques con una interfaz que podemos incluir en cualquiera de nuestros servicios. Esto no es muy diferente de la mayoría de las bibliotecas de base de datos basadas en lenguaje de terceros, pero sigo creyendo que la inicialización, la capacidad de comprender el código y trabajar con tipos de datos es mucho más sólida.
Conclusión
En este artículo, esperaba mostrar el potencial de la cadena de bloques y los contratos inteligentes más allá de las criptomonedas. Si bien todavía estoy interesado en el lado criptográfico de esta tecnología, estoy tratando de alejar mi punto de vista de los Tokens, NFT y los clichés asociados con la palabra "Blockchain".
Es importante que cualquier tecnólogo recuerde que crypto es Blockchain, pero Blockchain no es crypto para permitir el flujo de nuevos casos de uso de este poderoso fenómeno global. Actualmente, mis ideas se centran en los flujos de ingeniería de software en la Web 3.0, la estandarización del acceso a los datos y los contratos inteligentes como un futuro marco de back-end. ¡Estoy emocionado de ver a dónde te llevan tus ideas a medida que comienzas a pensar en Blockchain más allá de las criptomonedas!
Recursos
[1] https://www.udemy.com/course/ethereum-and-solidity-the-complete-developers-guide/
[2] https://docs.openzeppelin.com/contracts/2.x/api/token/erc20
[3] https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02
[5] https://solidez-por-ejemplo.org/
Fuente: https://betterprogramming.pub/a-web-2-0-developers-guide-to-web-3-0-18447da4325d
1652536922
過去2年間、私は次のステートメントでエンジニアリングのバックグラウンドを活用しようとしました。
「あなたが投資するものがどのように機能し、あなたが知っているものに投資するかを学びましょう。」
これは、私がコアで知っていたテクノロジーへのいくつかの優れた、確信のある投資につながりました。同様に、私は最初は盲目的に投資したテクノロジーについて学ぶ努力をしました。最終的に、暗号通貨がコアでどのように機能するかを学ぶことを決心したとき、私はこれまでで最大の学習の旅の1つに導かれました。レイヤー1(イーサリアム、ビットコインなど)のホワイトペーパーを学習した後、参加する最も速い方法は、Solidityを学習して「スマートコントラクト」の概念を習得することであると認識しました。
ソフトウェアエンジニアリングの私のバックグラウンドは構文の学習を非常に簡単にしました、そしてこの素晴らしいコースといくつかの金融知識の助けを借りて、私はこれまで以上に多くの興味を集めた新しい分野を見つけました。
スマートコントラクトを書き始め、Web 3.0エコシステムと対話し始めたとき、私はサービスの合理化とこの勇敢な新しい世界の協調的な性質にすぐに驚かされました。Web 2.0 API、OOP、ホスティング、および標準化の分厚いものがユニバーサルテクノロジーに統合されているのを見て、通貨と財務が主なユースケースであることを忘れることがありました。
私の主なポイント:ブロックチェーンは通貨以上のものです。これは、インターネット上での構築の次の反復です。この記事では、初心者向けにいくつかの用語を提供し、他の技術者がこのテクノロジーの可能性を理解できるように、Web2.0言語で類似点を描くことを目指しています。
ウォレット、スマートコントラクト、ブロックチェーン、トークン
この見出しの用語がブロックチェーンを理解し始めるための基本的なステップである方法を理解する。これらの定義は、この記事の残りの部分をいくつかの簡単な定義で補足することのみを目的としているため、これらの説明があいまいに見える場合は、読者がそれぞれを個別に掘り下げることをお勧めします。これらの用語をご存知の場合は、このセクションの下のメイントピックにスキップすることをお勧めします。
ブロックチェーン—トランザクションが有効であるというコンセンサスが多数のサーバー内で見つかると、トランザクションを介してアクセスできるデータと機能のコピーを格納するサーバーのネットワーク。ブロックチェーンには独自の自国通貨があり、これらのサーバーオペレーターに「ガス」の形でコンピューティング能力を支払うことを目的としています。これは、あらゆるレイヤー1トークンの真のユーティリティです。つまり、コンピューティング能力へのアクセスです。
ウォレット—ネットワークのL1トークンの一部を割り当て/送信でき、ネットワークのL1トークンを割り当て/送信でき、アドレスのIDを使用してスマートコントラクトと対話するトランザクションに署名できるブロックチェーン上のアドレス(これにより他のL2トークンがどのように可能になるか)。
スマートコントラクト—ウォレットのすべての機能(L1の送信/受信)を含むブロックチェーン上のアドレス。状態変数を介してデータを格納し(データベースを考える)、バイトコードを介して機能を実行し(データベース/ API関数を考える)、ウォレットなどの他のコントラクトと対話できます。
レイヤー2トークン—ミンティング、転送、書き込み、およびその他の通貨機能を容易にする共通機能を備えたインターフェイス(ERC20)を実装するスマートコントラクト。ウォレットは、L1を保持するのと同じ方法でL2トークンを「保持」しません。L2コントラクトと対話してトークンを転送するだけで、自身のアドレスと転送先のアドレスのバランス状態変数を効果的に変更できます。
Web3.0時代のAPI
典型的なWeb2.0APIのフローは次のようになります。
1.Webサイトで認証キーの支払いを行う
2. URL文字列にペイロードや変数を作成するために、文字列処理コードを記述します
3.言語固有のHTTPライブラリを使用して、get/postリクエストを送信します
4.出力JSON構造を学習した後、別のライブラリを使用して言語のネイティブデータ型に解析します
経験豊富なソフトウェアエンジニアにとって、これは威圧的なプロセスではなく、これらのステップのみが含まれています。ただし、APIの統合は、ドキュメントが不十分で、出力データ型が難しく、有料キーを操作し、アップグレードやAPIを変更するため、面倒で時間がかかる可能性があります。開発者は、一部のAPIが理解可能で十分に文書化されている場合や、他のAPIが古くて不格好な場合に、何が得られるかを実際に知ることはありません。
Web 3.0では、データはこれらの問題の多くを解決する別の方法でアクセスされます。
1.他の組織または個人によって開発および展開され、データまたはサービスを提供する別の契約は、パブリック機能のインターフェイス(ライブラリと同様)を公開します。
2.独自のコードで、インターフェースのコードをインポートできます。次に、彼らの契約アドレスを知ることで、そのインターフェースの実装が次のようなアドレスで利用可能であることが確実にわかります。
IsomeAPI api = IsomeAPI(address);
3.これで、新しいオブジェクトを使用して他のコントラクトと対話できます。コントラクトも組み込みのSolidityであるため、独自のコードと外部コントラクトの両方で、ネイティブの入力データ型と出力データ型が使用されます。インタラクションは、オブジェクトがコントラクト内にあるかのように見え、感じます。
uint temp = api.getTemp(latitude, longitude);
データアクセスに対するこの新しいソリューションにより、開発者が必要とする数のデータソースを迅速かつ合理的に統合できます。オープンソースの性質を考えると、ドキュメントは依然として役立ちますが、1人のSolidity開発者がインターフェースコードを見るだけで相互作用する質問に答えることができるため、もはや必要ありません。同時に、ユニバーサルプロトコルの出現を可能にします。IERC20は、L2トークンのインターフェイス/APIです。開発者は、任意のトークンのアドレスであるIERC20(address)をフィードすることで、任意の一意のトークンに普遍的にアクセスできるだけでなく、数分で独自のトークンを作成できます。
メリットは、スケーラビリティと再現性だけにとどまりません。L1とL2に組み込まれた支払いシステムにより、契約/ APIの開発者は、機能またはデータアクセスの使用に対してユーザーに課金するシステムを簡単に組み込むことができます。これは、APIを使用する開発者として、クレジットカード、サブスクリプション、または紛らわしい価格設定モデルが必要ないことを意味します。どの通貨をどれだけ保有するかを理解するだけで、両端での支払いは常に問題なく機能します。
最後に、データが依然として非常に必要なWeb 2.0 APIとの堅牢性の非互換性のために、この概念に異議を唱える人もいるかもしれません。幸いなことに、 Chainlinkのようなイベント駆動型のオラクルアルゴリズム出現しました。これらのオラクルはサードパーティのAPIにアクセスし、このデータをスマートコントラクトの世界にプッシュして、基本的にWeb2.0APIをラップします。Web 3.0の世界では、これらのAPIへのアクセスは、オブジェクトを作成し、単純な関数を使用してデータを取得するのと同じくらい簡単になりました。
Web 3.0 APIの有効性を示すために、仲介アカウントにお金を入金するプロセスがWeb 2.0の観点からどのように見えるかを考え、これがWeb3.0でどのように見えるかを見てみましょう。
Web 2.0:
1.バックエンドは、特定の銀行のAPIを呼び出すためのユーザー承認を受け取ります(このAPI、クレデンシャルなどの統合と理解が必要です)
2.銀行APIが証券口座へのACH/電信送金をトリガーします(ETA:数時間から数日)
3。証券が資金を受け取ると、バックエンドは証券のAPIを呼び出して取引を実行します(おそらく非常に異なるAPI、資格情報システムなど)。
4.取引が発生し、検索のために結果を明示的にログに記録する必要があります。Web3.0
のコード例を次に示します。
contract Swap {
address private constant UNISWAP_V2_ROUTER =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
function swap(
address _tokenIn,
address _tokenOut,
uint _amountIn,
uint _amountOutMin,
) external {
//1. We transfer the users tokens(ERC20) to ourselves after user has approved
IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
//2. We tell the bank/token that the broker can move our funds
IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
//3. We call the Uniswap contract/API which facilitates our trade
IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
_amountIn,
_amountOutMin,
path,
msg.sender,
block.timestamp
);
}
https://solidity-by-example.org/から適応
ご覧のとおり、2つの異なるサービスを使用して複雑な金銭的転送を行うと、API統合、資格情報、および待機時間が原因で、Web2.0作業の開発者にとって頭痛の種になります。上記のWeb3.0スマートコントラクトでは、これは2つの異なるサービス(ソーストークン/銀行とユニスワップ/ブローカー)を使用して、数行の非常に読みやすいコードで実行できます。さらに、この複雑なFinTechトランザクションは数日ではなく数秒で発生しますが、これはこの記事の範囲を超えています。
全体として、スマートコントラクト時代にAPIをホストすることの利点の実現は数多くあります。データやサービスを言語ネイティブ機能を備えたオブジェクトと見なす方法、一意のアドレスを持つインターフェースの再現性により標準プロトコルが出現する方法、API支払いを合理化できる方法について説明しました。最後に、ボーナスとして、これらの次世代APIは、サーバー構成、メンテナンス、またはクラウド支払いを必要としません。それらが展開されると、何千ものブロックチェーンオペレーターがこれを処理し、各トランザクションのガス料金を介して支払われます!
OOPがオンラインになります
最後のセクションでは、私がWeb3.0の大きなブレークと見なしていることについて説明します。非常に似ているように見えるかもしれないもう1つ強調したいことがあります。それは同じことですが、パースペクティブはWeb3.0を表示する別の楽しい方法を提供します。OOPまたはオブジェクト指向プログラミングとは、動的でスケーラブルなコードを作成するための変数と関数を保持するコード内のオブジェクトの使用を指します。
変数と関数は、この記事のメイントピックと非常によく似ています。スマートコントラクトは、事実上、OOPのオブジェクトであり、それらのコードのスキャフォールドは、変数、関数、およびコンストラクターを備えたJava、Python、またはC#クラスと同じように見えます。それで、これをまとめるとどういう意味ですか?オブジェクトがオンラインになりました。
これは、アクセス制御を使用してオブジェクトを展開できることを意味します。もちろん、コントラクトの形式の複数の「サービス」が他のサービスに直接アクセスして操作し、同じことを行うことができます。複雑な車の履歴とタイトル付けのためのシステムを作成したいと思うかもしれません。車両ごとにオブジェクト/コントラクトをデプロイし、他のスマートコントラクトの形で無限のマイクロサービスを作成して、同じオブジェクトに対して多くの異なるアクションを実行すると同時に、すべてのユーザーにある程度の可視性を提供できます。あるいは、他のサービスで自分のデータベースにアクセスするためのよりクリーンな方法が必要な場合もあります。これは、次のように簡単に見える可能性があります。
interface IDataBase{
//we define some basic functions a database would have
//"contract Database is IDatabase" would implment these functions and hold the data
function setData(bytes data) external returns(bool);
function getData(uint id) external view returns(bytes);
}
contract Service1 {
IDatabase someDatabase;
constructor(address _dbAddress){
//Inform contract that an IDataBase contract will be at _dbAddress
someDatabase = IDataBase(_dbAddress);
}
function data(uint id) public view returns(bytes){
return someDatabase.getData(id);
}
}
contract Service2{
IDatabase someDatabase;
constructor(address _dbAddress){
someDatabase = IDataBase(_dbAddress);
}
}
この例では、データベースは、任意のサービスに含めることができるインターフェイスを使用して、ブロックチェーン上で安全にホストされています。これは、ほとんどのサードパーティの言語ベースのDBライブラリと大差ありませんが、初期化、コードを理解する機能、およびデータ型を操作する機能の方がはるかに堅牢であると私は信じています。
結論
この記事では、暗号通貨を超えたブロックチェーンとスマートコントラクトの可能性を紹介したいと思いました。私はまだこのテクノロジーの暗号化の側面に興味を持っていますが、トークン、NFT、および「ブロックチェーン」という言葉に関連する決まり文句から自分の見方を遠ざけようとしています。
技術者にとって、暗号はブロックチェーンであることを覚えておくことが重要ですが、この強力なグローバル現象の新しいユースケースの流れを可能にするために、ブロックチェーンは暗号ではありません。私のアイデアは現在、Web 3.0のソフトウェアエンジニアリングフロー、データアクセスの標準化、および将来のバックエンドフレームワークとしてのスマートコントラクトを中心としています。あなたが暗号を超えたブロックチェーンについて考え始めるとき、あなたのアイデアがあなたをどこに連れて行くのかを見るのを楽しみにしています!
資力
[1] https://www.udemy.com/course/ethereum-and-solidity-the-complete-developers-guide/
[2] https://docs.openzeppelin.com/contracts/2.x/api/token/erc20
[3] https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02
[5] https://solidity-by-example.org/
ソース:https ://betterprogramming.pub/a-web-2-0-developers-guide-to-web-3-0-18447da4325d
1652497664
In this video we will go over all the steps to build a full web3 mint website
Chapters:
0:00 Build a Flashy Web3 Mint Website
0:25 React, Ethers, Hardhat, and Web3 Setup
4:00 Writing a NFT Mint Smart Contract
26:50 How to Deploy Smart Contract to Test Network
32:20 Creating a Full Mint Website
53:00 Give Mint Website some Life with CSS Styling
1:08:00 Fully Built a Frontend Mint Website
assets file download: https://1drv.ms/u/s!Al1l2sA-axg8gep2j3h4WqOXh-N4Ug?e=MPsEP9
create-react-app: https://create-react-app.dev/
hardhat: https://hardhat.org/
infura: https://infura.io/
etherscan: https://etherscan.io/
node: https://nodejs.org/en/download/
chakra ui: https://chakra-ui.com/docs/getting-started
Subscribe: https://www.youtube.com/c/EdRohDev/featured
1652422407
Want to get hired in Web3 and Blockchain fast? Learn React. It's one of the easiest and most lucrative Crypto career paths. This course will get you set.
Web3 needs front-end developers urgently. Learn how to make awesome Web3 apps (+dApps) that users will love with Zsolt. After this course, you'll be able to build and deploy your own React web applications.
Zsolt Nagy started as a Backend Web Developer in 2006, but turned to Frontend development some years later. Zsolt has spent the last ten years working with JavaScript. As a team lead, tech lead, and engineering manager, he has conducted hundreds of tech interviews and has hired multiple world class engineers. Besides coding in JavaScript, Zsolt is also a mentor and bootcamp instructor at various coding schools. His tech blog on zsoltnagy.eu focuses on developing maintainable web applications.
#react #web3 #blockchain #dapp #programming
1652415199
This course will teach you everything you need to create and deploy your own dApps - the backbone of Web3.
Filip will teach you the end-to-end dApp development process for Ethereum. You'll get to build and test your own dApps and Smart Contracts too! After this course, you'll have practical knowledge of Web3.js, MetaMask, Truffle, and Ganache, and your very own dApp.
Filip has a background in Computer Science within the Swedish Banking sector and was an early adopter of Bitcoin. He is the "other half" behind Ivan on Tech Academy and a true programming mastermind. Previously, he was the CEO of Stockholm Blockchain Group and has worked as a Blockchain Consultant with clients from all over the world. During his free time he enjoys reading non-fiction books and long walks.
Ivan runs Ivan on Tech - one of the most successful and trusted blockchain channels on Youtube and is also an international blockchain speaker and educator. Millions of people all around the world have listened, learned and been inspired by Ivan. Now he has created a course for his followers and subscribers, so that they can get the same knowledge as the big corporations.
#web3 #nft #blockchain #dapp #nonfungibletoken #ethereum
1652413182
Do you want to develop dApps with JavaScript only? In this course we will teach you how to do that step by step using Moralis.
The goal of this course is to allow you to build Web3 dApps with Web2 programming tools. After it you will be able to develop dApps like DEXs, NFT marketplaces, and more. Perfect course for a building Web3 developer's portfolio and CV.
Chris is a professional developer since 2001, after hearing about blockchain in 2017 he didn't waste a minute and used his decades of experience in front-end design to learn Web3 Programming. Since then he has been working in the space nonstop, and helped us create Moralis as it is right now.
#web3 #blockchain #javascript #dapp #programming
1652411834
Learn Javascript from SCRATCH by building real-world projects. No programming experience knowledge required.
Web3 programming isn't rocket science, and you don't need to be a math genius. Zsolt will introduce you to programming, and show you how to build your own DEX using JavaScript, HTML, CSS, and of course... Moralis. After this course, you'll be ready to dive deeper into Web3 development.
6 - JavaScript and the DOM
Zsolt Nagy started as a Backend Web Developer in 2006, but turned to Frontend development some years later. Zsolt has spent the last ten years working with JavaScript. As a team lead, tech lead, and engineering manager, he has conducted hundreds of tech interviews and has hired multiple world class engineers. Besides coding in JavaScript, Zsolt is also a mentor and bootcamp instructor at various coding schools. His tech blog on zsoltnagy.eu focuses on developing maintainable web applications.
#javascript #blockchain #defi #web3 #dapp #programming #html #css #moralis
1652409401
Do you want to develop dApps on Solana, but you don't have any Rust knowledge? Don't worry. In this course, you will learn how to build smart contracts on Solana from complete basics. No prior Rust knowledge is required.
The goal of this course is to introduce you to the basics of Rust and allow you to build smart contracts on Solana even if you didn't have any prior Rust knowledge. This is the perfect course for anyone that wants to get into Solana development.
Zsolt Nagy started as a Backend Web Developer in 2006, but turned to Frontend development some years later. Zsolt has spent the last ten years working with JavaScript. As a team lead, tech lead, and engineering manager, he has conducted hundreds of tech interviews and has hired multiple world class engineers. Besides coding in JavaScript, Zsolt is also a mentor and bootcamp instructor at various coding schools. His tech blog on zsoltnagy.eu focuses on developing maintainable web applications.
#rust #solana #programming #blockchain #web3 #moralis #dapp #smartcontracts
1652182260
The goal of ethereum.rb is to make interacting with the Ethereum blockchain from Ruby as fast and easy as possible (but not easier!).
Project is currently maintained by @kurotaky.
Before installing the gem make sure you meet all prerequisites, especially that you have:
Before you run a program check that the node is running and accounts you want to spend from are unlocked.
To install gem simply add this line to your application's Gemfile:
gem 'ethereum.rb'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ethereum.rb
You can create a contract from solidity source and deploy it to the blockchain, with the following code:
contract = Ethereum::Contract.create(file: "greeter.sol")
address = contract.deploy_and_wait("Hello from ethereum.rb!")
Deployment may take up to a couple of minutes. Once deployed you can start interacting with the contract, e.g. calling it's methods:
contract.call.greet # => "Hello from ethereum.rb!"
You can see example contract greeter here.
If contract method name uses camel case you must convert it to snake case when use call:
call.your_method
.
If you want to complie multiple contracts at once, you can create new instances using newly declared ruby clasess:
Ethereum::Contract.create(file: "mycontracts.sol", client: client)
contract = MyContract1.new
contract = contract.deploy_and_wait
contract2 = MyContract2.new
contract2 = contract.deploy_and_wait
All names used to name contract in solidity source will translate to name of classes in ruby (camelized).
Note: If class of given name exist it will be undefined first to avoid name collision.
The other way to obtain a contract instance is to get one that already exists on the blockchain. To do so you need a contract name, contract address and ABI definition.
contract = Ethereum::Contract.create(name: "MyContract", address: "0x01a4d1A62F01ED966646acBfA8BB0b59960D06dd ", abi: abi)
Note that you need to specify a contract name, that will be used to define new class in ruby, as it is not a part of the ABI definition.
Alternatively you can obtain the abi definition and name from a contract source file:
contract = Ethereum::Contract.create(file: "MyContract.sol", address: "0x01a4d1A62F01ED966646acBfA8BB0b59960D06dd ")
If you want to create a new contract, that is not yet deployed from ABI definition you will need also to supply binary code:
contract = Ethereum::Contract.create(name: "MyContract", abi: abi, code: "...")
If you use Truffle to build and deploy contracts, you can pick up the Truffle artifacts to initialize a contract. For example, if you have a MyContract in the Truffle directory at /my/truffle/project
:
contract = Ethereum::Contract.create(name: "MyContract", truffle: { paths: [ '/my/truffle/project' ] }, client: client, address: '0x01a4d1A62F01ED966646acBfA8BB0b59960D06dd')
The contract factory will attempt to load the deployed address from the Truffle artifacts if the client's network is present:
contract = Ethereum::Contract.create(name: "MyContract", truffle: { paths: [ '/my/truffle/project' ] }, client: client)
Functions defined in a contract are exposed using the following conventions:
contract.transact.[function_name](params)
contract.transact_and_wait.[function_name](params)
contract.call.[function_name](params)
Example Contract in Solidity
contract SimpleRegistry {
event LogRegister(bytes32 key, string value);
mapping (bytes32 => string) public registry;
function register(bytes32 key, string value) {
registry[key] = value;
LogRegister(key, value);
}
function get(bytes32 key) public constant returns(string) {
return registry[key];
}
}
For contract above here is how to access it's methods:
contract.transact_and_wait.register("performer", "Beastie Boys")
Will send transaction to the blockchain and wait for it to be mined.
contract.transact.register("performer", "Black Eyed Peas")
Will send transaction to the blockchain return instantly.
contract.call.get("performer") # => "Black Eyed Peas"
Will call method of the contract and return result. Note that no transaction need to be send to the network as method is read-only. On the other hand register
method will change contract state, so you need to use transact
or transact_and_wait
to call it.
Using the example smart contract described above, one can listen for LogRegister
events by using filters.
You can get a list of events from a certain block number to the latest:
require 'ostruct'
event_abi = contract.abi.find {|a| a['name'] == 'LogRegister'}
event_inputs = event_abi['inputs'].map {|i| OpenStruct.new(i)}
decoder = Ethereum::Decoder.new
filter_id = contract.new_filter.log_register(
{
from_block: '0x0',
to_block: 'latest',
address: '0x....',
topics: []
}
)
events = contract.get_filter_logs.log_register(filter_id)
events.each do |event|
transaction_id = event[:transactionHash]
transaction = ethereum.eth_get_transaction_receipt(transaction_id)
args = decoder.decode_arguments(event_inputs, entry['data'])
puts "#{transaction.inspect} with args: #{args}"
end
By default methods interacting with contracts will use default Json RPC Client that will handle connection to ethereum node. Default client communicate via IPC. If you want to create custom client or use multiple clients you can create them yourself.
To create IPC client instance of simply create Ethereum::IpcClient:
client = Ethereum::IpcClient.new
You can also customize it with path to ipc file path and logging flag:
client = Ethereum::IpcClient.new("~/.parity/mycustom.ipc", false)
If no ipc file path given, IpcClient looks for ipc file in default locations for parity and geth. The second argument is optional. If it is true then logging is on.
By default logging is on and logs are saved in "/tmp/ethereum_ruby_http.log".
To create Http client use following:
client = Ethereum::HttpClient.new('http://localhost:8545')
You can supply client when creating a contract:
contract = Ethereum::Contract.create(client: client, ...)
You can also obtain default client:
client = Ethereum::Singleton.instance
Ethereum.rb allows you to interact directly with Ethereum node using json rpc api calls. Api calls translates directly to client methods. E.g. to call eth_gasPrice
method:
client.eth_gas_price # => {"jsonrpc"=>"2.0", "result"=>"0x4a817c800", "id"=>1}
Note: methods are translated to underscore notation using metaprogramming (See client.rb
for more information).
Full list of json rpc methods is available here
Ethereum.rb supports signing transactions with key using ruby-eth gem.
To create a new key simply do the following:
key = Eth::Key.new
Then you can use the key to deploy contracts and send transactions, i.e.:
contract = Ethereum::Contract.create(file: "...")
contract.key = key
contract.deploy_and_wait("Allo Allo!")
contract.transact_and_wait.set("greeting", "Aloha!")
You can also transfer ether transfer using custom keys:
client.transfer(key, "0x342bcf27DCB234FAb8190e53E2d949d7b2C37411", amount)
client.transfer_and_wait(key, "0x949d7b2C37411eFB763fcDCB234FAb8190e53E2d", amount)
You can change gas price or gas limit in the client:
client.gas_limit = 2_000_000_
client.gas_price = 24_000_000_000
or per contract:
contract.gas_limit = 2_000_000_
contract.gas_price = 24_000_000_000
Often in the application you want to link to blockchain explorer. This can be problematic if you want links to work with different networks (ropsten, mainnet, kovan) depending on environment you're working on. Following helpers will generate link according to network connected:
link_to_tx("See the transaction", "0x3a4e53b01274b0ca9087750d96d8ba7f5b6b27bf93ac65f3174f48174469846d")
link_to_address("See the wallet", "0xE08cdFD4a1b2Ef5c0FC193877EC6A2Bb8f8Eb373")
They use etherscan.io as a blockexplorer.
Note: Helpers work in rails environment only, works with rails 5.0+.
There are couple of rake tasks to help in wallet maintenance, i.e.:
rake ethereum:contract:deploy[path] # Compile and deploy contract
rake ethereum:contract:compile[path] # Compile a contract
rake ethereum:transaction:byhash[id] # Get info about transaction
rake ethereum:transaction:send[address,amount] # Send [amount of] ether to an account
Logs from communication between ruby app and node are available under following path:
/tmp/ethereum_ruby_http.log
Run bin/console
for an interactive prompt that will allow you to experiment.
Make sure rake ethereum:test:setup
passes before running tests.
Then, run rake spec
to run the tests.
Test that do send transactions to blockchain are marked with blockchain
tag. Good practice is to run first fast tests that use no ether and only if they pass, run slow tests that do spend ether. To do that use the following line:
$ bundle exec rspec --tag ~blockchain && bundle exec rspec --tag blockchain
You need ethereum node up and running for tests to pass and it needs to be working on testnet (Ropsten).
This library has been forked from ethereum-ruby by DigixGlobal Pte Ltd (https://dgx.io).
The gem is available as open source under the terms of the MIT License.
Download Details:
Author: EthWorks
Source Code: https://github.com/EthWorks/ethereum.rb
License: MIT license
1652152860
A php interface for interacting with the Ethereum blockchain and ecosystem.
Set minimum stability to dev
"minimum-stability": "dev"
Then
composer require sc0vu/web3.php dev-master
Or you can add this line in composer.json
"sc0vu/web3.php": "dev-master"
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://localhost:8545')));
// timeout
$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://localhost:8545', 0.1)));
$web3->clientVersion(function ($err, $version) {
if ($err !== null) {
// do something
return;
}
if (isset($version)) {
echo 'Client version: ' . $version;
}
});
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
$eth = $web3->eth;
Or
use Web3\Eth;
$eth = new Eth('http://localhost:8545');
use Web3\Web3;
$web3 = new Web3('http://localhost:8545');
$net = $web3->net;
Or
use Web3\Net;
$net = new Net('http://localhost:8545');
web3
$web3->batch(true);
$web3->clientVersion();
$web3->hash('0x1234');
$web3->execute(function ($err, $data) {
if ($err !== null) {
// do something
// it may throw exception or array of exception depends on error type
// connection error: throw exception
// json rpc error: array of exception
return;
}
// do something
});
eth
$eth->batch(true);
$eth->protocolVersion();
$eth->syncing();
$eth->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
net
$net->batch(true);
$net->version();
$net->listening();
$net->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
personal
$personal->batch(true);
$personal->listAccounts();
$personal->newAccount('123456');
$personal->provider->execute(function ($err, $data) {
if ($err !== null) {
// do something
return;
}
// do something
});
use Web3\Contract;
$contract = new Contract('http://localhost:8545', $abi);
// deploy contract
$contract->bytecode($bytecode)->new($params, $callback);
// call contract function
$contract->at($contractAddress)->call($functionName, $params, $callback);
// change function state
$contract->at($contractAddress)->send($functionName, $params, $callback);
// estimate deploy contract gas
$contract->bytecode($bytecode)->estimateGas($params, $callback);
// estimate function gas
$contract->at($contractAddress)->estimateGas($functionName, $params, $callback);
// get constructor data
$constructorData = $contract->bytecode($bytecode)->getData($params);
// get function data
$functionData = $contract->at($contractAddress)->getData($functionName, $params);
Due to callback is not like javascript callback, if we need to assign value to outside scope, we need to assign reference to callback.
$newAccount = '';
$web3->personal->newAccount('123456', function ($err, $account) use (&$newAccount) {
if ($err !== null) {
echo 'Error: ' . $err->getMessage();
return;
}
$newAccount = $account;
echo 'New account: ' . $account . PHP_EOL;
});
To run examples, you need to run ethereum blockchain local (testrpc).
If you are using docker as development machain, you can try ethdock to run local ethereum blockchain, just simply run docker-compose up -d testrpc
and expose the 8545
port.
git clone https://github.com/sc0Vu/web3.php.git && cd web3.php && composer install
2. Run test script.
vendor/bin/phpunit
git clone https://github.com/sc0Vu/web3.php.git
2. Copy web3.php to web3.php/docker/app directory and start container.
cp files docker/app && docker-compose up -d php ganache
3. Enter php container and install packages.
docker-compose exec php ash
4. Change testHost in TestCase.php
/**
* testHost
*
* @var string
*/
protected $testHost = 'http://ganache:8545';
5. Run test script
vendor/bin/phpunit
Install packages
Enter container first
docker-compose exec php ash
6. gmp
apk add gmp-dev
docker-php-ext-install gmp
7. bcmath
docker-php-ext-install bcmath
Remove extension
Move the extension config from /usr/local/etc/php/conf.d/
mv /usr/local/etc/php/conf.d/extension-config-name to/directory
API
Todo.
Download Details:
Author: sc0Vu
Source Code: https://github.com/sc0Vu/web3.php
License: MIT license
1652145360
A Python library for interacting with Ethereum, inspired by web3.js.
Get started in 5 minutes or take a tour of the library.
For additional guides, examples, and APIs, see the documentation.
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our guidelines for contributing, then check out issues that are labeled Good First Issue.
Download Details:
Author: ethereum
Source Code: https://github.com/ethereum/web3.py
License: MIT license
#blockchain #python #web3 #solidity #ethereum #smartcontract