<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Nwa-eddy]]></title><description><![CDATA[Nwa-eddy]]></description><link>https://nwa-eddy84.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 22:22:19 GMT</lastBuildDate><atom:link href="https://nwa-eddy84.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Using Memes To Illustrate The Mina Blockchain]]></title><description><![CDATA[Learn about wallets you can use to send and receive MINA. The Mina community has created various wallets. You can send and receive MINA using any of these…]]></description><link>https://nwa-eddy84.hashnode.dev/using-memes-to-illustrate-the-mina-blockchain</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/using-memes-to-illustrate-the-mina-blockchain</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Fri, 21 Feb 2025 23:00:00 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-interactions-on-how-to-deploy-a-zksapp-on-mina-protocol">Interactions on how to deploy a zksapp on mina protocol</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739649848166/b303e713-bba9-4338-9c7d-3ab721e49e99.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739649927129/83e1cd44-70d7-4a3a-8460-6de2a82127aa.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650039802/e12a3a0c-e3d1-408a-abac-cb2ba680c332.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650105132/83692341-4a78-4aba-8068-dfac8a9143dd.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650155504/71a525ed-0c74-44a7-ad7f-76f10f24ab37.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650202820/98fa8895-e36d-4a94-9df9-a4b55be3e22e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650337543/367b1ca5-a0de-4f69-9c09-ba71b5b77623.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650431411/743220f7-1be2-4fa3-9e98-f6894dd44ae4.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-firstly-install-a-wallet">Firstly, Install a Wallet</h3>
<p>Learn about wallets you can use to send and receive MINA.</p>
<p>The Mina community has created various wallets. You can send and receive MINA using any of these wallets. Currently, Auro Wallet for Chrome and MinaPortal support interactions with zkApps.</p>
<h3 id="heading-secondly-wallet-for-node-operators">Secondly, Wallet for Node Operators</h3>
<p>The Mina CLI allows storing, sending, and receiving MINA. However, this method is intended only for Mina node operators and is not recommended as a wallet for typical users</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650525569/1b3e9e00-f1dd-4278-9aea-1c2647d35b79.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650636910/bffa219b-01ec-4099-8a5d-a17f3ae02f9b.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650708622/03372c3c-fc78-4761-b127-7286cebc25d9.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650771073/c41f957b-0a03-4c4c-8b90-d0bf70ca6e46.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739650941012/9e98d5b4-0b51-41f2-888c-1277bfd6ee28.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739651003032/57b2f43a-be60-4c93-b3bc-29a5131e6f9f.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739651078928/510d415a-cfed-4593-9ced-23989a4fe6d5.png" alt class="image--center mx-auto" /></p>
<p>for more info:<a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/introduction-to-zkapps/how-to-deploy-a-zkapp">https://docs.minaprotocol.com/zkapps/writing-a-zkapp/introduction-to-zkapps/how-to-deploy-a-zkapp</a></p>
<p>#Minamemes</p>
]]></content:encoded></item><item><title><![CDATA[Kaiaポータルエコシステムチュートリアル]]></title><description><![CDATA[KAIA PORTAL Kaia Portalは、Kaiaエコシステム内でのユーザー体験を向上させるために設計されたオールインワンのDeFiハブです。ユーザーは、デスクトップおよびモバイルで使いやすいインターフェースを通じて、資産のスワップ、ブリッジ、ステーキング、オンランプを簡単に行うことができ、今後LIN…]]></description><link>https://nwa-eddy84.hashnode.dev/kaia</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/kaia</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Thu, 13 Feb 2025 14:54:37 GMT</pubDate><content:encoded><![CDATA[<p>KAIA PORTAL</p>
<p>Kaia Portalは、Kaiaエコシステム内でのユーザー体験を向上させるために設計されたオールインワンのDeFiハブです。ユーザーは、デスクトップおよびモバイルで使いやすいインターフェースを通じて、資産のスワップ、ブリッジ、ステーキング、オンランプを簡単に行うことができ、今後LINE Messengerとの統合も予定されています。 Kaia Portalの主な特徴は、ミッションというポイントベースの報酬システムで、ユーザーはエコシステムに参加することでインセンティブを獲得します。エポック1では、KaiaのDeFiパートナーとのインタラクションに対してトークン報酬が提供され、エポック2では、Kaia Waveプログラムの参加者が対象に追加されます。今後のエポックでは、Kaiaホルダーにとってさらに多くの報酬の機会が提供されることを目指しています。 Kaia Portalは、Web3のインタラクションを効率化し、シームレスなDeFiアクセスを提供することで、ブロックチェーンの利用をよりアクセスしやすくし、非暗号ネイティブのユーザーにも開かれています。</p>
<p>Kaia Portal Mission Epoch #1 Kaia Portal Mission Epoch #1は、最大5000万KAIAトークンを割り当て、参加プロジェクトからの貢献も含めて、Kaiaエコシステム内での流動性とユーザーエンゲージメントを高めることを目的としています。ユーザーはミッションを完了することでポイントを獲得し、エポック終了後にこれらのポイントをKAIAおよびプロジェクトトークンに転換することができます。 エポック1では、Kaia DeFiプロトコルへの流動性提供に焦点を当て、次のような報酬を提供します： • Kaiaポイント • 参加プロジェクトからのポイント • D2Iプログラムの報酬 • DeFiプロトコルからの利回り 新しいアプリケーションとDeFiユースケースの登場により、エコシステムはより多くの資産と取引量をサポートし、流動性提供者にとって高い手数料を生成し、全体的な活動を促進します。これにより、流動性とエンゲージメントが増加し、Kaiaエコシステム全体を強化するフライホイール効果が生まれます。</p>
<p>Kaia Portal Missions: 最大の透明性 Kaia Portal Missionsは、キャンペーンの期間からポイント計算式に至るまで、すべての詳細について完全な透明性を提供し、ユーザーが自信を持って参加できるようにします。</p>
<p>キャンペーン期間 • ミッションは9月26日に開始し、少なくとも3ヶ月間実施されます。 • 各エポックでは、新しいエアドロップ機会、参加プロジェクト、資産のブーストが紹介されます。</p>
<p>早期参加者ボーナス • 8月29日から9月26日までに参加したユーザーは、早期参加者ボーナスを受け取る資格があります。 • リストされたDeFiプロトコルに$1を預けるだけで、以降獲得するすべてのポイントに対して1.2倍のボーナスマルチプライヤーが適用されます。</p>
<p>Kaia報酬 • 一般参加者には最大2000万KAIA（マイルストーンに基づく）。 • FGP-23でFinschiaエコシステム内で投票したウォレット専用に3000万KAIA。 • 長期的なオンチェーン貢献を行ったユーザーには1000万KAIA、Kaia Portal Missionへの参加に基づいて配布。</p>
<p>エアドロップおよびTVLベースのアンロック • 2500万KAIAがポイントエアドロップ用に割り当てられます： o 一般参加者には1000万KAIA。 o FGP-23参加者には1500万KAIA。 • 100百万TVLで追加1250万KAIAがアンロック： o 一般参加者には500万、FGP-23参加者には750万。 • 150百万TVLでさらに1250万KAIAがアンロックされ、同様の分配が行われます。 （FGP-23報酬プールは一般参加者プールとは別です。）</p>
<p>権利確定および即時報酬 • キャンペーン終了時に転換されるKAIAトークンには6ヶ月の権利確定期間があります。 • 参加者はKaiaポイント → Kaiaトークンを請求できますが、トークンは6ヶ月間で徐々にリリースされます。 • D2Iプログラムでは、参加者は権利確定なしでKaia報酬およびプロジェクトポイントを即座に受け取ることができます。</p>
<p>パートナープロジェクトの報酬 • 参加者は、それぞれのPortal Missionで各パートナーからポイントを獲得します。 • ポイントの配布基準はパートナーによって異なり、近日中に更新されます。 • すべての参加プロジェクトは、専門的な監査を受けており、安全で確認された参加が保証されます。</p>
<p>参加プロジェクト（アルファベット順） Avalon（DeFi Lending） • ウェブサイト | Twitter | ドキュメント • バック：Matrixport Ventures、SNZ Holding、Spark Digital Capital、Summer Capitalなど。 • 監査：Salus。 • 概要： o Bitcoinを中心とした融資エコシステム、DeFi、CeDeFi、RWA融資を架け橋。 o Bitcoin担保による過剰担保ローンでフィアット流動性を提供。 o DeFi融資にBitcoinを統合することで機関投資家の導入を支援。 o TVL$10B+、効率的でスケーラブルな融資ソリューションを先駆け。 Capybara（DEX） • ウェブサイト | Twitter | ドキュメント • 開発：Wombatチーム（バック：Binance Labs、Animoca、Shima、Jump Crypto）。 • 監査：Hacken、Peckshield、Zokyo。 • 概要： o Kaiaチェーンの最初のローンチパッド、Kaiaをグローバルユーザーに接続。 o ゲーム化されたポイントシステム、エアドロッププレイグラウンド、安定したスワップを統合。 o カバレッジ比率に基づく安定スワップメカニズムを導入し、スケーラビリティの障壁とインパーマネントロスのリスクを排除。 o 最小スリッページで単一トークンLPサポート、融資および取引のためのDEX統合。 o Kaiaエコシステムの成長を促進する$CAPYトークンの近日発行。 Dragonswap（DEX） • ウェブサイト | Twitter | Medium • 開発：Dragonswapチーム。 • 監査：KALOS。 • 概要： o Kaiaでの主要DEX、V2＆V3流動性提供。 o 持続可能性、コミュニティエンゲージメント、高い流動性に焦点。 o ネイティブトークンなし—KAIAインセンティブとポイントシステムで参加を促進。 o $9M+の流動性、$4Mの初期戦略的投資を支援。 o 最適化されたV3流動性サービスで高速な取引＆低手数料。 o Kaia FoundationのD2Iプログラムに積極的に参加し、ユーザー利益を向上。 Kaiaswap（DEX） • ウェブサイト | Twitter • 開発：iZUMi Financeチーム（バック：Mirana、HASHKEY、IOSG、BIXIN Venturesなど）。 • 監査：Certik、BlockSec。 • 概要： o Kaiaチェーンの最初のネイティブDLAMM（Discretized-Liquidity AMM）DEX。 o iZUMi Financeの技術を使用して開発され、技術革新とユーザー体験を重視。 o 特定の価格ポイントで集中流動性を使用し、資本効率を向上。 o 透明性、安全性、スムーズなオンチェーン体験を保証。 o DEX-as-a-Service（DaaS）、DLAMM、アカウント抽象化、マルチシグセキュリティを提供。 o Kaiaの高性能ブロックチェーンで低ガス費用と向上したアクセス性。</p>
<p>注：参加プロジェクトのリストは継続的に更新される場合があります。</p>
<p>インセンティブ設計：ポイント定義 概要 • Kaiaポイントは、DEXおよび融資プラットフォームへの流動性貢献を通じて獲得されます。 • ユーザーは、流動性提供時にKaiaポイントとプロジェクトポイントを同時に獲得します。 • 紹介ポイントは他者を招待することで得られる追加報酬です。</p>
<p>Kaiaポイント式（非公式） Kaiaポイントは次のように決定されます： Kaiaポイント = 流動性プール乗数 × 資産ブースト乗数 × その他のブースト乗数 × ユーザーの流動性貢献（TVL） × 時間 + 紹介ポイント</p>
<p>Kaiaポイント式（公式） Pu,kaia=∫0T(∑v∈Vmlp,t⋅At⋅Bt⋅TVLpr,v,t+110∑r∈RPr,p′)dtP_{u,kaia} = \int_0^T \left( \sum_{v \in V} m_{lp,t} \cdot A_t \cdot B_t \cdot TVL_{pr,v,t} + \frac{1}{10} \sum_{r \in R} P_{r,p'} \right) dt</p>
<p>式の説明： • Pu,pP_{u,p}Pu,p = ユーザーのプロジェクトpにおける総ポイント。 • mlp,tm_{lp,t}mlp,t = 時間tにおける流動性プール乗数。 • AtA_tAt = 時間tにおける資産乗数。 • BtB_tBt = 時間tにおけるNFT/その他の乗数。 • TVLp,lp,tTVL_{p,lp,t}TVLp,lp,t = 時間tにおけるプロジェクトpの流動性貢献額（$）。 • Pr,p′P_{r,p'}Pr,p′ = 紹介者からの紹介ポイント。</p>
<p>追加ルール • 計算時間はシステム制約により毎時計算されます。 • 紹介ポイントは直接紹介者に限定され、二次紹介の影響を防ぎます。</p>
<p>キャンペーン中に流動性プールや資産以外のさまざまな乗数が追加される予定です。</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456182617/13a79b94-8d98-4d8f-90a3-9700346bf320.png" alt class="image--center mx-auto" /></p>
<p>BinanceからウォレットにKAIAを送信するには、次の手順を実行してください：</p>
<ol>
<li><p><strong>Binanceにログイン</strong>: アカウントの認証情報を使用してBinanceにアクセスします。</p>
</li>
<li><p><strong>ウォレットに移動</strong>: ページ上部の「ウォレット」セクションに移動します。</p>
</li>
<li><p><strong>引き出しを選択</strong>: ウォレットセクションで「引き出し」をクリックします。</p>
</li>
<li><p><strong>KAIAを選択</strong>: 引き出す暗号通貨としてKAIAを選択します。</p>
</li>
<li><p><strong>ウォレットアドレスを入力</strong>: Kaiaウォレット、Klip、またはMetaMaskの個人ウォレットアドレスをコピーして、「受取人のアドレス」フィールドに貼り付けます。間違いを避けるため、アドレスが正しいことを確認してください。</p>
</li>
<li><p><strong>ネットワークを選択</strong>: 引き出しのために適切なブロックチェーンネットワーク（例：Ethereum、Kaia、または他のサポートされているネットワーク）を選択します。</p>
</li>
<li><p><strong>金額を入力</strong>: 引き出したいKAIAの金額を指定します。</p>
</li>
<li><p><strong>引き出しを確認</strong>: ウォレットアドレスと金額を再確認します。</p>
</li>
<li><p><strong>セキュリティ確認を完了</strong>: 引き出しを確認するために必要なセキュリティチェック（2FAなど）を完了します。</p>
</li>
<li><p><strong>引き出しを送信</strong>: 引き出しリクエストを確認し、送信します。</p>
</li>
</ol>
<p>送信後、KAIAトークンはあなたの個人ウォレットに送られます。すべての詳細を慎重に確認してください！</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456352609/aa19fc26-5c92-4005-9098-d5a58863dea2.png" alt class="image--center mx-auto" /></p>
<p>Binanceアプリを使用してKAIAを引き出す手順：</p>
<ol>
<li><p><strong>Binanceアプリを開く</strong>: アカウントの認証情報でログインします。</p>
</li>
<li><p><strong>「ウォレット」タブに移動</strong>: 画面下部の「ウォレット」タブを選択します。</p>
</li>
<li><p><strong>「スポット」を選択</strong>: 表示される「スポット」セクションでKAIA（KLAY）を選択します。</p>
</li>
<li><p><strong>引き出し</strong>: 「引き出し」をタップし、指示に従って手続きを完了します。</p>
</li>
</ol>
<p>正しいウォレットアドレスを確認し、引き出しに適したネットワークを選択してください。</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456479162/fc59ddd4-4533-4fad-98f6-82b811189ef9.png" alt class="image--center mx-auto" /></p>
<p>BinanceアプリのKLAYステータス画面でのKAIA引き出し手順：</p>
<ol>
<li><p><strong>「引き出し」ボタンをクリック</strong>: KLAYステータス画面にいることを確認し、「引き出し」オプションを選択します。</p>
</li>
<li><p><strong>「暗号ネットワークで送信」を選択</strong>: 引き出し方法として「暗号ネットワークで送信」オプションを選びます。</p>
</li>
</ol>
<p>指示に従って、宛先ウォレットアドレスを入力し、引き出しを完了します。KAIAに適したネットワークとウォレットアドレスを使用していることを確認してください。</p>
<p>「アドレス」フィールドに、あなたの個人ウォレットのKAIAアドレス（例：Kaiaウォレット、Metamaskなど）を貼り付けます。引き出し金額を設定した後、「引き出し」ボタンをクリックし、「確認」をクリックして引き出しリクエストを完了します。</p>
<p>ご注意ください：引き出しには、取引所のレビュープロセスにより最大30分かかる場合があります。引き出しがスムーズに処理されない場合は、取引所のカスタマーサポートに連絡して支援を受けてください。</p>
<hr />
<p><strong>他のチェーンからKaiaへのブリッジ手順：</strong></p>
<ol>
<li><p><strong>ミッションで提供する流動性を提供したいDEXプールを確認</strong>します。</p>
</li>
<li><p>例えば、「Capybara DEX」の「Stargate Pool」に流動性を提供したい場合、Stargateブリッジに基づいて資産を持ってくる必要があります。この場合、EthereumからUSDT（Stargate）資産を持ってきます。</p>
</li>
<li><p>逆に、Stable PoolのためにUSDT（ETHからのポータル）などの資産を持ってきたい場合、Wormholeブリッジを使用してEthereumからUSDTを持ってくる必要があります。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456718018/5241b9d8-50f5-4d2f-9c58-29064818c030.png" alt class="image--center mx-auto" /></p>
<p> 「ブリッジ」タブに移動し、Stargateブリッジを選択します。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456917354/4a971c0b-1c08-48ef-a9c4-b901c0665a82.png" alt class="image--center mx-auto" /></p>
<p> Stargateブリッジのウェブページで、ウォレットを接続し、USDTを持ってきたいチェーン（この場合はEthereum）を選択します。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739456990266/1c509094-bbc0-4979-9683-ab1dc959685f.png" alt class="image--center mx-auto" /></p>
<p> 受信チェーンとしてKaiaを選択します。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457083973/b65e6ebb-63c9-4013-a2f7-edf830ec0791.png" alt class="image--center mx-auto" /></p>
<p> 「転送」をクリックし、その後ウォレットで取引を承認してUSDTがStargateで使用できるようにします。その後、EthereumからKaiaへの転送が進行します。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457205004/44cabb91-554a-4ac8-9d92-5545c5d2c715.png" alt class="image--center mx-auto" /></p>
<p> 転送状況は常にLayerZero Scanで確認できます。リンク: <a target="_blank" href="https://layerzeroscan.com/">https://layerzeroscan.com/</a></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457308986/40850338-7cad-4b0b-afc0-aa995677a829.png" alt class="image--center mx-auto" /></p>
<p> もしウォレットにUSDT（Stargate）が表示されない場合は、「トークンのインポート」をクリックし、USDT（Stargate）のトークンアドレスを登録してください：0x9025095263d1e548dc890a7589a4c78038ac40ab。提供されたリンクからトークンアドレスを確認できます。</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457398590/eb56126b-f47e-427a-9823-c1eb0ed8ce72.png" alt class="image--center mx-auto" /></p>
<p> USDTがウォレットに正しく登録されていることを確認してください。 Portalブリッジは上記の手順と似たように機能し、他のチェーンからKaia（Klaytn）にトークンを送信できます。このリンクからアクセスできます：<a target="_blank" href="https://portalbridge.com/">https://portalbridge.com/</a></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457520086/15cc17b6-0766-497c-a8be-5e3315bb87df.png" alt class="image--center mx-auto" /></p>
<p> DeFiプールに入金してポイントを獲得します。<br /> Capybaraに入金してポイントを獲得します。</p>
<ol>
<li><p>最初に、Portal Missionタブのミッションリストから入金したいプールを見つけます。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457614929/1924a413-66df-480f-bae4-ccd62b87ce19.png" alt class="image--center mx-auto" /></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457679564/2a95916a-98c6-4e59-bd6d-525c84cbae50.png" alt class="image--center mx-auto" /></p>
<ol start="2">
<li><p>入金に必要なトークンを取得します。<br /> 各トークンのリンクをクリックすると、トークンを取得できるサービス（ブリッジを含む）にリダイレクトされます。<br /> ブリッジングの詳細手順については、「他のチェーンからKaiaへのブリッジ」リンクを参照してください。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457782096/8ef55af3-4286-406a-8066-3b94bd214f75.png" alt class="image--center mx-auto" /></p>
<ol start="3">
<li><p>必要なトークンをすべて取得したら、「入金」ボタンをクリックして対応するDEXに移動します。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739457890099/130ea4ee-c846-436a-9fe3-7def8b066df9.png" alt class="image--center mx-auto" /></p>
<p> <strong>Portalの「FNSA -&gt; KAIA」タブ</strong>では、既存のFinschiaウォレットとKAIAウォレットを接続して、FNSAトークンをKAIAに変換できます。変換プロセス中の最大のセキュリティを確保するため、完了までに30分以上かかる場合があります。このプロセス中は、「履歴」タブでリアルタイムに変換状況を確認できます。詳細については、「FNSA &gt; KAIAスワップ」と「FNSAオンチェーン貢献報酬ガイド」のリンクを参照してください。</p>
<p> <strong>FGP-23投票者への4,000万KAIA報酬：</strong><br /> 4,000万KAIAのオンチェーン貢献者報酬は、9月12日に分配されます。これに備えて、投票に使用したFinschiaウォレットと、オンチェーン貢献者報酬を受け取るためのKAIAウォレットをリンクする必要があります。そのためには、「Finschiaにリンク」タブにアクセスし、9月11日までにウォレットのリンクを完了してください。このリンク作業は後から解除できませんので、今後使用する予定のKAIAウォレットをリンクすることを強くお勧めします。また、9月12日以降は、このリンク作業が手動で1週間ごとに確認されますので、9月12日までにリンクを完了することを目指してください。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739458029069/16eae41b-842b-4fc5-af77-43d3b357dfb2.png" alt class="image--center mx-auto" /></p>
<p> <strong>Epoch #1報酬</strong><br /> Epoch #1は2024年12月25日15:00（UTC+9）に終了します。その後、2週間のレビューが行われ、得られたポイントが意図されたサービス目的に沿っているか確認されます。不適切な方法で得られたポイントは取り消されるため、最終的な報酬額は表示された見積もりとわずかに異なる場合があります。</p>
<p> <strong>報酬の配布</strong><br /> いよいよ最もエキサイティングな部分です！ 報酬は、1月7日から6月7日まで、毎月7日に6回に分けて配布されます。配布の内訳は以下の通りです：<br /> • 1回目〜4回目のインストール：各15%<br /> • 5回目〜6回目のインストール：各20%</p>
<p> 参加者はいつでも報酬を請求できますが、最終的な請求期間は2025年6月30日に終了します。毎月の請求が不便な場合は、6回目の配布後にすべての報酬を一度に請求することもできます。</p>
<p> 既存のFNSAの長期ステーカーに対しては、「KAIAオンチェーン貢献者報酬ガイドライン」に基づき割り当てられた1,000万KAIAがポイント報酬と組み合わせて配布されます。</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739458117570/ba16d019-77cf-4955-8dfd-99c6964e58ba.png" alt class="image--center mx-auto" /></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739458205062/b6b3f8a3-4932-4303-b7e8-cccdf8ed32e4.png" alt class="image--center mx-auto" /></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739458268854/63603faf-63b3-4730-8bcd-86f416d93d2a.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Icpエコシステムでの開発]]></title><description><![CDATA[ICPエコシステム ICP（Internet Computer Protocol）は、DFINITYによって開発されたパブリックブロックチェーンネットワークであり、従来のITスタックを置き換え、商用クラウドサービスへの依存を排除することを目的としています。これは、スケーラブルでクラウドのようなブロックチェーン…]]></description><link>https://nwa-eddy84.hashnode.dev/icp</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/icp</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Mon, 10 Feb 2025 00:45:35 GMT</pubDate><content:encoded><![CDATA[<p><strong>ICPエコシステム</strong></p>
<p>ICP（Internet Computer Protocol）は、DFINITYによって開発されたパブリックブロックチェーンネットワークであり、従来のITスタックを置き換え、商用クラウドサービスへの依存を排除することを目的としています。これは、スケーラブルでクラウドのようなブロックチェーンプラットフォームとして設計されており、外部のプライベートシステムを一切使用せずに、スマートコントラクトのみでインターネットサービス、Webサイト、金融システムをホストできます。</p>
<p>Internet Computerはデータを保存し、アプリケーション開発をサポートし、ネットワーク相互運用性を実現します。</p>
<p>ICPの構造とユースケースについて基本的な理解を深めるには、このテーマに関する入門記事を参照してください。本要約では、2021年のICPのメインネット「マーキュリー」ローンチに至る主要なイベントに焦点を当てます。</p>
<h3 id="heading-internet-computer-protocol"><strong>Internet Computer Protocolのリリース履歴</strong></h3>
<p>DFINITYは、2019年から2020年にかけていくつかのICPコンポーネントをリリースし、2021年のマーキュリーメインネットローンチへとつなげました。主なマイルストーンは以下のとおりです。</p>
<ul>
<li><p><strong>Copper（2019年第4四半期）</strong> – 初のパブリックDFINITY Canister SDK、特殊なスマートコントラクト（キャニスター）、およびWebAssembly（WASM）に着想を得た耐改ざん性ソフトウェア向けプログラミング言語「Motoko」を導入。</p>
</li>
<li><p><strong>Bronze（2020年第1四半期）</strong> – ICPの端末ベースの実行環境からデスクトップWebアプリ開発への移行を可能にし、キャニスターが自身の状態、フロントエンド、バックエンドロジックを保持できるように。</p>
</li>
<li><p><strong>Tungsten（2020年第2四半期）</strong> – ICPをサードパーティ開発者に開放し、アプリケーションやエンタープライズシステムの構築を可能に。また、デスクトップ機能の上にモバイル開発も導入。</p>
</li>
<li><p><strong>Sodium（2020年第4四半期）</strong> – プロトコル経済、サブネットガバナンス、ホスティングのための「ネットワーク・ナーバス・システム（NNS）」を導入。さらに、キャニスター相互作用のための「サイクル」や、ICPコインを活用したガバナンス・ステーキング用の「ニューロン」を導入。</p>
</li>
</ul>
<p>これらの開発が集約され、2021年のマーキュリーメインネットローンチにより、ICPの本格的な展開が実現しました。</p>
<p><strong>ICPのマーキュリーメインネット</strong></p>
<p>DFINITYは2021年5月7日にマーキュリーメインネットをローンチし、Internet Computerを完全にパブリックに提供しました。本プロジェクトは以下の主要な目標を達成することを目指しています。</p>
<ul>
<li><p><strong>パブリックネットワークの成長</strong> – ICPは、特殊なスマートコントラクト（キャニスター）を活用し、異なるコードベースやブロックチェーンシステム間の相互運用性を低コストで実現します。これは、従来のソフトウェアがライブラリを統合するのと同様の方法です。</p>
</li>
<li><p><strong>セキュリティとプライバシーに特化したシステム</strong> – 従来のITは、専有クラウドコンピューティングや中央集権型インフラに依存しており、セキュリティ上の脆弱性があります。ICPは暗号技術とChain Keyテクノロジーを活用し、ネットワーク・ナーバス・システム（NNS）を通じてネットワーク内のサブネットを安全に管理します。</p>
</li>
<li><p><strong>再設計されたスマートコントラクト</strong> – ICPのスマートコントラクト（ソフトウェアキャニスター）は、スケーラビリティと複雑性の問題を軽減し、ネットワークシステムの構築と維持にかかるコストと労力を削減します。</p>
</li>
<li><p><strong>中央集権的な仲介者の排除</strong> – 従来のブロックチェーンアプリケーションはAWSのような中央集権型クラウドサービス上でホストされますが、ICPはスマートコントラクトが直接Webブラウザにコンテンツを配信します。これにより、セキュリティ、検閲耐性、稼働時間が向上し、サードパーティサービスへの依存を減らします。</p>
</li>
<li><p><strong>ユーザビリティの向上</strong> – ICPは、取引手数料やトークンベースのユーザーインタラクションを不要にします。ユーザーはアカウント登録やKYCを行う代わりに、WebAuthnを使用して認証を行い、ノートパソコンやスマートフォンの指紋スキャンなどの暗号鍵を活用します。</p>
</li>
</ul>
<hr />
<h3 id="heading-orally"><strong>Orally</strong></h3>
<p>完全オンチェーンのオラクルは、安全で信頼性の高い分散型データフィードと自動化を複数のチェーンに提供します。リアルタイムのデータ統合をシームレスに実現し、安全で効率的なdAppsを支援します。</p>
<ul>
<li><p><strong>Sibyl</strong></p>
<ul>
<li><p>分散型データ取得</p>
</li>
<li><p>検証可能なデータを効率的にオンデマンド配信</p>
</li>
<li><p>カスタムデータフィードを提供</p>
</li>
</ul>
</li>
<li><p><strong>Pythia</strong></p>
<ul>
<li><p>オンチェーン自動化ツール</p>
</li>
<li><p>乱数生成（RNG）</p>
</li>
<li><p>Sibylからデータを取得</p>
</li>
</ul>
</li>
<li><p><strong>Apollo</strong></p>
<ul>
<li><p>EVMリクエストベースのデータ配信</p>
</li>
<li><p>乱数生成（RNG）</p>
</li>
<li><p>Sibylからデータを取得</p>
</li>
</ul>
</li>
<li><p><strong>Cassandra</strong></p>
<ul>
<li>dApps向けのGmail、Twitterなどへの分散型認証</li>
</ul>
</li>
<li><p><strong>Delphos</strong></p>
<ul>
<li>カスタムデータ処理アルゴリズムを用いた分散型データ前処理</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-kirjgrpjg7zjg4nntbhlkigqkg"><strong>コード統合</strong></h3>
<p><strong>開始</strong><br />価格フィードデータを取得：</p>
<pre><code class="lang-plaintext">javascriptCopyEditconst fetchData = async () =&gt; {
  const response = await fetch("https://wth3l-tiaaa-aaaap-aa5uq-cai.icp0.io/get_asset_data_with_proof?pair_id=ICP/USD");
  const data = await response.json();
  console.log(data);
};

fetchData();
</code></pre>
<p><strong>レスポンス例</strong></p>
<pre><code class="lang-plaintext">jsonCopyEdit{
  "symbol": "ICP/USD",
  "rate": 4902941764,
  "timestamp": 1685442778,
  "decimals": 9,
  "signature": "5d4368547f194ff784d904cc9052108894044bba7588d2447bd13f070128ef6d690e12094b5e3c6c304187587cd6ff8b4d35dfc3ea4b7165f79d2e881b446dd31c"
}
</code></pre>
<hr />
<h3 id="heading-kirjg6hjg6rjg4pjg4gqkg"><strong>メリット</strong></h3>
<ul>
<li><p><strong>圧倒的なコスト効率</strong><br />  ICPの革新的な手法を活用し、現実世界のデータに低コストでアクセス可能。</p>
</li>
<li><p><strong>完全分散型 &amp; 信頼性確保</strong><br />  HTTP Outcalls、ECDSAしきい値署名、ランダムテープなどの高度なICP機能を活用し、安全で信頼性の高いデータフィードを提供。</p>
</li>
<li><p><strong>クロスチェーン互換性</strong><br />  Orallyを複数のブロックチェーンにシームレスに統合し、dAppsの可能性を拡大。</p>
</li>
<li><p><strong>カスタムデータフィード</strong><br />  市場動向からリアルワールドのイベントまで、さまざまなdAppのニーズに対応するデータフィードを提供し、信頼性と関連性を向上。</p>
</li>
<li><p><strong>モジュール型 &amp; 組み合わせ可能なアプローチ</strong><br />  柔軟でスケーラブルなアーキテクチャにより、ブロックチェーンアプリケーションの進化に適応可能。</p>
</li>
</ul>
<hr />
<h3 id="heading-kirku5xntytjgb8qkg"><strong>仕組み</strong></h3>
<ol>
<li><p><strong>Orallyのプロダクト（SibylまたはPythia）を選択し、DAppに統合</strong></p>
</li>
<li><p><strong>オラクルサービスを購読し、データソース、取得頻度、カスタムアセット（必要に応じて）を設定</strong></p>
</li>
<li><p><strong>OrallyがICPのパワーを活用し、リアルワールドのデータを取得・処理</strong></p>
</li>
<li><p><strong>データはエンドユーザーまたは自動トランザクションを通じてDAppに安全に転送され、開発者が活用可能に</strong></p>
<h3 id="heading-kirjg6bjg7zjgrnjgrhjg7zjgrkqkg"><strong>ユースケース</strong></h3>
<ul>
<li><p><strong>分散型金融（DeFi）</strong><br />  リアルタイムの価格フィードにアクセスし、正確な価格設定や市場分析を実現。</p>
</li>
<li><p><strong>ゲーム &amp; NFT</strong><br />  ランダム性と自動化を活用し、ダイナミックで予測不可能かつ公平なゲーム体験を提供。</p>
</li>
<li><p><strong>サプライチェーン管理</strong><br />  複数のデータソースからの安全で信頼性の高い情報を活用し、商品の移動を追跡・検証。</p>
</li>
</ul>
</li>
</ol>
<hr />
<h3 id="heading-chain-fusion2024"><strong>Chain Fusionの2024年のマイルストーンと将来のビジョン</strong></h3>
<p>    2024年、Chain Fusionは本格的にマルチチェーン化を実現。まず、ckBTCに加えてckETHが追加され、ICP上での合成ツイン資産の展開が始まりました。これらの資産はスマートコントラクトロジックによって管理され、ICPのガバナンスシステムのもとで運営されています。このマイルストーンに続き、Ethereumとの完全な統合が行われ、<strong>Tritiumマイルストーン</strong>ではEthereumエコシステム（EVMやL2を含む）との完全な読み書きサポートが実装されました。</p>
<p>    この統合を可能にした技術は、<strong>HTTPSアウトコールを介したRPCエンドポイント</strong> です。この技術により、他のブロックチェーンとの統合も進み、サポート対象のチェーン数は24に達しました。Ethereum統合に伴い、署名の遅延とスループットが改善され、ERC-20トークンの "ck" バージョンの展開が可能になりました。2024年初頭には1つのckトークン（ckBTC）のみでしたが、現在は23種類に増加。特に、<strong>ckBTC、ckETH、ckUSDC、ckUSDT</strong> は最も利用されています。</p>
<p>    さらに、<strong>Deuteriumマイルストーン</strong> では<strong>しきい値Schnorr署名</strong>と<strong>Bitcoinブロックヘッダーデータ</strong>が導入されました。これにより、BRC-20トークンや「ルーン」などの新しいBitcoin関連のファンジブルトークンの可能性が広がり、分散型のBitcoinサービスやインフラの構築が加速しました。</p>
<hr />
<h3 id="heading-chain-fusion-hubs"><strong>Chain Fusion HUBS：エコシステムの統合</strong></h3>
<p>    Chain Fusion HUBSは、異なるブロックチェーンエコシステムを統合し、シームレスな相互運用性を提供することを目指しています。</p>
<ul>
<li><p><strong>Bitcoin、Ethereum、Solana</strong> などの複数のブロックチェーンを統合</p>
</li>
<li><p><strong>ECDSA、Schnorr、EdDSA</strong> などの高度な署名アルゴリズムを活用</p>
</li>
<li><p>クロスチェーン取引とデータ交換を安全かつ効率的に実現</p>
</li>
</ul>
<p>    このアプローチにより、分散型アプリケーション（dApps）やサービスの可能性が拡大し、より接続されたブロックチェーンの世界が実現します。</p>
<p>    2024年、Chain Fusion HUBSは<strong>ICPエコシステムの重要なイベントシリーズ</strong>として登場し、相互運用性とコラボレーションの理念を具現化しました。これらのイベントでは、クリプト愛好家、開発者、機関投資家が集まり、分散型未来のビジョンを共有しました。</p>
<p>    各Chain Fusion HUBSの開催により、Web3領域におけるリアルワールドのつながりが強調され、ICPとChain Fusion技術がどのように分散型アプリケーションやサービスの未来を形作るかが示されました。</p>
<h3 id="heading-ethcc-brussels-chain-fusion-hub"><strong>EthCC – Brussels: Chain Fusion HUB</strong></h3>
<p>    EthCC – BrusselsのChain Fusion HUBは、Chain Fusionのストーリーを初めて披露する場となり、Ethereumコミュニティおよび広範な暗号資産市場との関わりを深めることに成功しました。このイベントでは、ICPが<strong>第3世代ブロックチェーン技術</strong>を活用し、Ethereumエコシステムに貢献することを強調しました。</p>
<p>    イベント中にチームは様々なステークホルダーと交流し、今後のコラボレーションの可能性を探る有望な手がかりを得ました。これにより、ICPとEthereumコミュニティの関係をさらに強化するための確かな基盤が築かれました。</p>
<hr />
<h3 id="heading-bitcoin"><strong>Bitcoin統合の課題</strong></h3>
<h4 id="heading-kirlsi7lhauqkg"><strong>導入</strong></h4>
<p>    暗号資産エコシステム全体で、<strong>ユーザーの分断</strong>と<strong>流動性の分散</strong>が進んでいます。これは、以下のようなレイヤー構造全体に見られる問題です。</p>
<ul>
<li><p><strong>レイヤー1（L1）同士の分断</strong>：BTC、ETH、SOLなど</p>
</li>
<li><p><strong>L1エコシステム内での分断</strong>：ETH vs. Polygon、Arbitrum、Optimism など</p>
</li>
<li><p><strong>単一チェーン内での標準の分断</strong>：BitcoinにおけるBRC-20、Runes、Atomicals、TAPなど</p>
</li>
</ul>
<p>    開発者が新たなL1、L2、サイドチェーン、ロールアップ、トークン標準を導入し続ける限り、この分断は拡大し続けます。</p>
<p>    また、暗号資産市場には膨大なインフラストラクチャが存在し、各プロジェクトがユーザー、開発者、流動性を獲得するために競争することで、エコシステムは**独立した閉鎖的な領域（ウォールド・ガーデン）**へと分裂しています。インセンティブ・モデル、ポイント・プログラム、エアドロップ、トークン、開発者向け助成金などの仕組みが、この分断を加速させています。</p>
<p>    このような状況の中、<strong>シームレスかつ許可不要な相互運用性ソリューション</strong>がこれまで以上に求められています。</p>
<hr />
<h3 id="heading-bitcoin-1"><strong>Bitcoinの相互運用性の問題</strong></h3>
<p>    現在、Layer Zero、Wormhole、Axelar、Particle Network、Acrossなどのソリューションが「オムニチェーン」の相互運用性を目指しています。これらのソリューションは、以下の要素で構成されています。</p>
<ol>
<li><p><strong>リレーネットワーク</strong>：異なるチェーン間のメッセージ転送を担当</p>
</li>
<li><p><strong>署名サービス</strong>：クロスチェーン取引のためのデジタル署名を提供</p>
</li>
<li><p><strong>オラクルソリューション</strong>：送信元チェーンの取引の最終性を検証</p>
</li>
<li><p><strong>開発者向けツール</strong>：オムニチェーンアプリケーションを構築可能に</p>
</li>
</ol>
<p>    しかし、このモデルには<strong>Bitcoinには適用できない</strong>という大きな問題があります。</p>
<p>    Bitcoinはオムニチェーンスマートコントラクトをデプロイできないため、既存の相互運用性ソリューションに組み込むことが困難です。以下のようなBitcoin関連技術は、現在のクロスチェーンシステムに統合できません。</p>
<ul>
<li><p>BTC</p>
</li>
<li><p>Lightning Network</p>
</li>
<li><p>Ordinals</p>
</li>
<li><p>BRC-20、Runes、Tap、Pipe、Atomicals、BRC-100、RSM、OP_NET など</p>
</li>
<li><p>BitcoinサイドチェーンおよびBitcoin L2（EVM非対応のMove、SVM、WASMなど）</p>
</li>
</ul>
<p>    Polygon Agg Layerのような<strong>共有ブリッジング</strong>や、Espressoのような<strong>共有シーケンス</strong>など、一部の技術スタック内での相互運用性の試みもあります。しかし、すべての開発者が同じ技術スタックを採用するとは限らず、このアプローチには限界があります。</p>
<hr />
<h3 id="heading-bitcoinlayer-0icp"><strong>解決策：BitcoinネイティブのLayer 0をICPで構築</strong></h3>
<p>    この問題に対する解決策として、<strong>Bitcoinに特化したLayer 0相互運用プロトコル</strong>の開発が考えられます。</p>
<p>    このLayer 0プロトコルは、Bitcoinを中心としつつ、Ethereum、Ethereum L2、Solana、Cosmosなどのエコシステムも統合するものです。</p>
<h4 id="heading-kirkulvjgarmp4vmijdopohntkaqkg"><strong>主な構成要素</strong></h4>
<ol>
<li><p><strong>ノードネットワーク</strong></p>
<ul>
<li><p>ICP上の「しきい値署名サブネット」を利用</p>
</li>
<li><p>ECDSA、Schnorr、EdDSAによるクロスチェーン署名を実現</p>
</li>
<li><p>必要に応じてブロックデータを取得する「超軽量ノード」を活用し、ソースチェーンの最終性を検証</p>
</li>
</ul>
</li>
<li><p><strong>実行レイヤー</strong></p>
<ul>
<li><p>ICPのスマートコントラクトとネイティブ統合</p>
</li>
<li><p>Bitcoinネイティブアセット、メタプロトコル、サイドチェーン、L2、他のL1との相互運用性を実現</p>
</li>
</ul>
</li>
</ol>
<p>    これにより、開発者は単一のアプリケーションを構築し、それをBitcoinおよび他のブロックチェーンでシームレスに動作させることが可能になります。</p>
<hr />
<h3 id="heading-icpbitcoin-layer-0"><strong>ICPを活用したBitcoin Layer 0の利点</strong></h3>
<p>    ICPには、Bitcoin Layer 0の実現に適した機能が多数あります。</p>
<ol>
<li><p><strong>Bitcoinライトノードのフルオンチェーン実装</strong></p>
<ul>
<li><p>ICP上でBitcoinのライトノードを実行可能</p>
</li>
<li><p>Bitcoinのトランザクションやブロックの検証を分散型かつ安全に実行</p>
</li>
</ul>
</li>
<li><p><strong>しきい値署名サブネットの活用</strong></p>
<ul>
<li>ECDSA、Schnorr、EdDSA（近日対応）を用いたクロスチェーン署名をサポート</li>
</ul>
</li>
<li><p><strong>スマートコントラクトによるHTTPコール</strong></p>
<ul>
<li><p>外部データソースやオラクルとの統合が容易</p>
</li>
<li><p>他のチェーンとのクロスチェーン通信が可能</p>
</li>
</ul>
</li>
<li><p><strong>ガスレストランザクション</strong></p>
<ul>
<li><p>ユーザーはトランザクション手数料を支払う必要がない</p>
</li>
<li><p>UXを大幅に改善し、導入のハードルを低減</p>
</li>
</ul>
</li>
</ol>
<p>    これらのICPの特性を活かせば、<strong>Bitcoinを中心としたLayer 0相互運用プロトコル</strong>を構築でき、さまざまなブロックチェーンエコシステムと連携したアプリケーションの実現が可能になります。</p>
<h3 id="heading-bioniq-revolutionizing-bitcoin-ordinals-with-chain-fusion"><strong>Bioniq: Revolutionizing Bitcoin Ordinals with Chain Fusion</strong></h3>
<p>    Bioniq は <strong>Chain Fusion</strong> を活用することで、<strong>Bitcoin Ordinals の作成・収集・取引をガス代なしで高速に実行</strong>できるようにします。</p>
<p>    <strong>Bitcoin Ordinalsとは？</strong><br />    Bitcoin Ordinals は、<strong>Bitcoin版のNFT</strong>のようなもので、個々のトランザクションに固有のデータを埋め込むことができます。これにより、Bitcoinを単なる価値の保存手段としてではなく、コレクティブルやNFTライクなプロジェクトの基盤として活用できます。</p>
<p>    <strong>Ordinalsの課題とBioniqの解決策</strong><br />    Bitcoin上で Ordinals を作成するには、<br />    ✅ <strong>高額な手数料</strong><br />    ✅ <strong>ネットワーク混雑</strong><br />    といった課題が存在します。</p>
<p>    Bioniq は、<strong>Chain Fusion を利用し、ICP がバックエンド処理を担う</strong>ことで、<strong>Bitcoinの堅牢な台帳の恩恵を受けつつ、手数料ゼロのNFTを高速に決済</strong>する仕組みを実現しました。</p>
<hr />
<h3 id="heading-bitcoinmeta-protocols"><strong>Bitcoin上のメタプロトコル（Meta-Protocols）</strong></h3>
<h3 id="heading-1"><strong>1. 概要</strong></h3>
<p>    Bitcoin上のトークン規格は、Colored Coins から Ordinals、Runes、Atomicals へと進化し続けています。<strong>SegWit、Schnorr署名、Taproot</strong> などの技術革新により、Bitcoinはより多機能で強力なプラットフォームへと変貌しつつあります。</p>
<p>    この発展により、Bitcoinは「価値の保存手段」から「<strong>多様なデジタル資産やDeFiアプリケーションの基盤</strong>」へと進化しています。</p>
<hr />
<h3 id="heading-2-10"><strong>2. メタプロトコル 1.0：初期の試み</strong></h3>
<h4 id="heading-colored-coinsbitcoin"><strong>Colored Coins：Bitcoin上のトークンの始まり</strong></h4>
<ul>
<li><p>特定のサトシに追加情報を付与し、<strong>株式や不動産などの資産を表現</strong></p>
</li>
<li><p>しかし、<strong>Bitcoinのスクリプト制限</strong> により、複雑な取引が難しく、普及せず</p>
</li>
</ul>
<h4 id="heading-ethereum"><strong>Ethereumの誕生</strong></h4>
<ul>
<li><p>Bitcoinのスクリプト制限を解決するため、より柔軟なプラットフォームとしてEthereumが登場</p>
</li>
<li><p><strong>ERC-20標準</strong> により、多数のトークンとdAppエコシステムが形成</p>
</li>
</ul>
<hr />
<h3 id="heading-3-ordinalsrunesatomicals"><strong>3. 新しいパラダイム：Ordinals、Runes、Atomicals</strong></h3>
<h4 id="heading-ordinals"><strong>Ordinals</strong></h4>
<p>    ✅ 各サトシにデータを直接埋め込むことで<strong>Bitcoin上にNFTを実現</strong><br />    ❌ しかし、<strong>非UTXOモデル</strong> のため<strong>手数料が高騰し、ネットワークが混雑</strong></p>
<h4 id="heading-runes"><strong>Runes</strong></h4>
<p>    ✅ <strong>UTXOモデル</strong> を活用し、よりスケーラブルで取引しやすいトークンを実現<br />    ✅ <strong>安価で、既存のBitcoinインフラとの統合が容易</strong><br />    🚀 <strong>ステーブルコインやポイントシステムに最適</strong></p>
<h4 id="heading-atomicals"><strong>Atomicals</strong></h4>
<p>    ✅ <strong>UTXOモデル</strong> を採用し、「ARC-20」標準を導入<br />    ✅ 各トークンが<strong>サトシと1対1で裏付け</strong>され、価値の安定性を確保<br />    ✅ <strong>BRC-20のようなオフチェーン・インデックスの問題を回避</strong></p>
<hr />
<h3 id="heading-4-segwitschnorrtaproot"><strong>4. 技術革新：SegWit、Schnorr、Taproot</strong></h3>
<h4 id="heading-segregated-witnesssegwit2017"><strong>Segregated Witness（SegWit）</strong>（2017年導入）</h4>
<p>    ✅ <strong>署名データをトランザクションから分離</strong>し、ブロックサイズを圧縮<br />    ✅ <strong>取引の改ざん防止（トランザクション・マリアビリティ問題の解決）</strong><br />    ✅ <strong>Lightning Networkの基盤技術</strong></p>
<h4 id="heading-schnorr-signatures"><strong>Schnorr Signatures</strong></h4>
<p>    ✅ <strong>複数の署名を1つにまとめる</strong>ことで、トランザクションサイズを削減<br />    ✅ <strong>マルチシグ取引の匿名性を向上</strong></p>
<h4 id="heading-taproot2021"><strong>Taproot（2021年導入）</strong></h4>
<p>    ✅ <strong>MAST（Merkelized Abstract Syntax Trees）を活用</strong>し、複雑なスマートコントラクトをシンプルに<br />    ✅ <strong>マルチシグ取引を通常取引と同様に見せることで、プライバシーを強化</strong></p>
<hr />
<h3 id="heading-5-202024"><strong>5. メタプロトコル 2.0：2024年以降の動向</strong></h3>
<p>    ✅ <strong>2024年4月：Bitcoinの半減期</strong>に伴い、<strong>Runesがローンチ</strong>し、取引量が急増<br />    ❌ <strong>2024年5月以降：市場の調整、流動性の低下によりメタプロトコルへの関心が一時減退</strong><br />    🚀 <strong>しかし、開発者たちは継続的に新たな技術を開発・改良中</strong></p>
<p>    Bitcoinのスクリプト機能が向上することで、<br />    ✅ <strong>取引コスト削減</strong><br />    ✅ <strong>より高度なアプリケーションの開発</strong><br />    が可能になり、メタプロトコルの進化はさらに加速していくと考えられます。</p>
<hr />
<h3 id="heading-kirjgb7jgajjgoeqkg"><strong>まとめ</strong></h3>
<p>    ✔ <strong>Bioniq は、ICPを活用して手数料ゼロの Ordinals 取引を実現</strong><br />    ✔ <strong>Bitcoinのメタプロトコルは、Ordinals、Runes、Atomicalsへと進化中</strong><br />    ✔ <strong>SegWit、Schnorr、Taproot により Bitcoin の機能性は大幅に向上</strong><br />    ✔ <strong>メタプロトコル 2.0 は、今後の相互運用性とスマートコントラクト機能を強化</strong></p>
<p>    Bitcoinは、もはや「価値の保存手段」だけではなく、<br />    <strong>DeFi、NFT、トークン発行のための強力なプラットフォーム</strong>へと進化を遂げています。</p>
<h3 id="heading-vs"><strong>ビットコイン上のミームトークン vs. ユーティリティトークン</strong></h3>
<h4 id="heading-kirnj77lnkjjga7nirbms4e6ioodnodvoodooodioodvoocrodsobjos4ua1gsoq"><strong>現在の状況: ミームトークンが主流</strong></h4>
<p>    ビットコインベースのトークン、特に <strong>Ordinals</strong> や <strong>BRC-20</strong> 標準の下にあるトークンは、大部分がミーム主導型です。これらのトークンは <strong>機能的なユーティリティ</strong> を持たず、投機的資産としての役割が強く、具体的な価値を提供するものではありません。</p>
<h4 id="heading-kirjg5jg7zjg6djgyvjgonjg6bjg7zjg4bjgqpjg6rjg4bjgqpjgbjjga7np7vooywqkg"><strong>ミームからユーティリティへの移行</strong></h4>
<p>    ミームトークンから <strong>ユーティリティトークン</strong> へ進化するためには、次の機能を統合する必要があります：<br />    ✅ <strong>ガバナンス</strong> – トークン保有者がプロジェクトの意思決定に参加できる。<br />    ✅ <strong>ステーキング</strong> – トークンを保持・ロックすることで報酬を得る。<br />    ✅ <strong>アクセス権</strong> – トークンを利用して特定のサービスや dApps へアクセス可能。</p>
<p>    ユーティリティトークンは <strong>採用率を高め、長期的な価値を追加</strong> するため、短期的な投機を超えて魅力的な資産となります。</p>
<hr />
<h3 id="heading-opcat"><strong>ビットコインのプログラム機能: OP_CAT とその先へ</strong></h3>
<h4 id="heading-opcat-1"><strong>OP_CAT: ビットコインのスクリプト機能の拡張</strong></h4>
<p>    開発者たちは <strong>OP_CAT</strong> に注目しています。これは、ビットコインスクリプト内で文字列を連結できるオペコードです。OP_CAT が有効化されれば、次のことが可能になります：<br />    🔹 <strong>ビットコイン上でより複雑なスマートコントラクトロジックを実装</strong> できる。<br />    🔹 <strong>トークンのプログラム可能性を向上</strong> させ、ビットコイン上の DeFi を拡張できる。</p>
<p>    しかし、OP_CAT の <strong>統合時期は未定</strong> であり、ビットコイン開発者やマイナーの合意が必要です。</p>
<h4 id="heading-evm-amp"><strong>EVM とのブリッジ &amp; その他のスマートコントラクトソリューション</strong></h4>
<p>    ビットコインのプログラム機能は <strong>限定的</strong> であり、高度なトークンプロトコルを構築するには技術的なスキルが求められます。しかし、エコシステムは <strong>開発者向けのツールの普及</strong> により次の方向に進んでいます：<br />    ✅ <strong>EVM ブリッジング</strong> – ビットコインを <strong>イーサリアムのスマートコントラクト</strong> と接続し、DeFi 機能を解放。<br />    ✅ <strong>ビットコインネイティブの拡張</strong> – 外部ブロックチェーンに頼らず、<strong>オンチェーン dApps</strong> を開発可能に。</p>
<p>    この進化により、<strong>開発者の障壁を低減</strong> し、ビットコインベースのアプリケーションに高度な機能をもたらします。</p>
<hr />
<h3 id="heading-amp"><strong>市場の要求: ユーティリティ &amp; 分散化へ</strong></h3>
<h4 id="heading-kirmqzog73nmotjgarjg4jjg7zjgqjg7pjga7pnidopohmi6hlpkcqkg"><strong>機能的なトークンの需要拡大</strong></h4>
<p>    ユーザーは <strong>純粋な投機資産ではなく、実用性のあるトークン</strong> を求めています。求められている機能は以下の通りです：<br />    ✅ <strong>ステーキング &amp; 利回り生成</strong><br />    ✅ <strong>ガバナンス参加</strong><br />    ✅ <strong>プラットフォーム &amp; サービスへのアクセス権</strong></p>
<h4 id="heading-vc"><strong>VC 支援トークンの衰退</strong></h4>
<p>    VC（ベンチャーキャピタル）支援のプロジェクトは次の理由で人気を失っています：<br />    ❌ <strong>中央集権的な懸念</strong> – トークンの不平等な配分が内部関係者に利益をもたらす。<br />    ❌ <strong>利益優先の姿勢</strong> – 多くのプロジェクトが <strong>短期的な利益を優先し、持続可能性を軽視</strong>。<br />    ❌ <strong>約束の未達成</strong> – 失敗したプロジェクトが相次ぎ、VC 主導の取り組みへの信頼が低下。</p>
<p>    代わりに、市場は <strong>コミュニティ主導の分散型プロジェクト</strong> を支持し、透明性のあるトークノミクスを求めています。</p>
<hr />
<h3 id="heading-icp"><strong>ICP の役割: ビットコインの進化を加速</strong></h3>
<h4 id="heading-icp-1"><strong>ICP × ビットコイン: シームレスな統合</strong></h4>
<p>    <strong>インターネットコンピューター（ICP）</strong> はビットコインの機能を強化し、<strong>直接的なブロックチェーン相互運用性</strong> を提供します：<br />    🔹 <strong>ビットコイン API</strong> – ICP のスマートコントラクト（<strong>カニスター</strong>）がビットコインと直接やり取り可能。<br />    🔹 <strong>Header API</strong>（近日公開） – <strong>SPV ノード</strong> を介した <strong>ビットコイン取引のオンチェーン検証</strong> をサポート。<br />    🔹 <strong>しきい値シュノア署名</strong> – <strong>タップルート取引の安全な実行</strong> を可能に。</p>
<h4 id="heading-icp-2"><strong>ICP がビットコインのメタプロトコルに与える影響</strong></h4>
<p>    ICP は <strong>仲介者を排除</strong> し、以下を実現：<br />    ✅ <strong>迅速 &amp; 安全なビットコイン取引</strong> – カストディアンやラップドアセット不要。<br />    ✅ <strong>ネイティブ BTC トランザクションインデックス</strong> – ビットコインベースの資産を効率的に追跡。<br />    ✅ <strong>メタプロトコル開発</strong> – <strong>新しいトークン標準</strong> をビットコイン上で構築可能。</p>
<p>    ICP の <strong>チェーンキー暗号技術</strong> とスマートコントラクトにより、<strong>ビットコインベースの DeFi ソリューション</strong> を構築できます：<br />    ✅ <strong>トラストレス流動性市場</strong><br />    ✅ <strong>クロスチェーンのトークンスワップ</strong><br />    ✅ <strong>分散型ビットコイン金融（BTC-Fi）</strong></p>
<hr />
<h3 id="heading-rainbow-protocol"><strong>Rainbow Protocol: スマートコントラクトの導入</strong></h3>
<h4 id="heading-icp-3"><strong>ビットコインの強みと ICP のスマートコントラクトの融合</strong></h4>
<p>    Rainbow Protocol は、<strong>ビットコインの機能拡張</strong> を目指し、以下を統合します：<br />    🔹 <strong>ビットコインのセキュリティ &amp; ネットワーク効果</strong><br />    🔹 <strong>ICP のスマートコントラクトの効率性</strong></p>
<p>    この <strong>ハイブリッドアプローチ</strong> により、ビットコインは：<br />    ✅ <strong>DeFi &amp; dApps をネイティブサポート</strong>。<br />    ✅ <strong>中央集権的な仲介なしに、シームレスなクロスチェーンソリューション</strong> を実現。</p>
<h4 id="heading-rainbow"><strong>Rainbow がビットコイン開発を強化する方法</strong></h4>
<p>    Rainbow は <strong>ICP の Chain Fusion</strong> を活用し、以下を可能にします：<br />    ✅ <strong>複数のレイヤー1ネットワーク上にスマートコントラクトを展開</strong>。<br />    ✅ <strong>ビットコインの基盤レイヤーとスケーラブルなプラットフォームの相互接続</strong>。<br />    ✅ <strong>既存のビットコイン金融ソリューションの制限を克服</strong>。</p>
<p>    Rainbow は <strong>ビットコインを静的資産からプログラム可能なブロックチェーンへと変革</strong> します。</p>
<hr />
<h3 id="heading-tap-protocol"><strong>TAP Protocol: 先進的なビットコインメタプロトコル</strong></h3>
<h4 id="heading-tap-defi"><strong>TAP: ビットコイン DeFi の可能性を解放</strong></h4>
<p>    TAP は <strong>ビットコイン Ordinals 用のマルチアセットメタプロトコル</strong> で、以下を提供：<br />    ✅ <strong>トークンステーキング</strong> – 保有者は報酬を得る。<br />    ✅ <strong>スワップ &amp; 流動性プール</strong> – オンチェーンの分散型取引所。<br />    ✅ <strong>ICP の Chain Fusion との相互運用性</strong> – 安全なクロスチェーントランザクション。</p>
<hr />
<h3 id="heading-kirntzdoq5y6ioodkodgodioocsocpoodsodmeodvoocueobruodioodvoocrodsobruacquadpsoq"><strong>結論: ビットコインベースのトークンの未来</strong></h3>
<p>    ✔ <strong>ビットコイントークンはミームからユーティリティ資産へ進化中。</strong><br />    ✔ <strong>OP_CAT と ICP の統合により、ビットコインのプログラム機能が拡張。</strong><br />    ✔ <strong>市場は分散型コミュニティ主導のトークンを支持。</strong><br />    ✔ <strong>ICP はスマートコントラクトを強化し、次世代のビットコイン金融を実現。</strong></p>
<p>    🚀 <strong>ビットコインはもはやデジタルゴールドではなく、完全な金融ネットワークへと進化している。</strong></p>
<p>    ビットフィニティ</p>
<p>    ブロックチェーン開発者はキャリアの初期にしばしば厳しい選択を迫られます。それは、Bitcoin と Ethereum のどちらを Layer 1 として選ぶかという選択です。この選択は、コカ・コーラとペプシのどちらを選ぶかに似ており、明確なトレードオフがあります。しかし、もし開発者が選ばなくてもよく、複数の Layer 1 スタックに跨って最適なチェーンを選べるとしたらどうでしょうか？</p>
<p>    Bitfinity はこの課題への解決策を提供します。これは、ICP の Chain Fusion を重要な橋として機能させ、ビットコイン上で Ethereum Virtual Machine (EVM) を実行できるように設計されたものです。Bitfinity によって、開発者はビットコイン上で Ethereum と同様のスマートコントラクト機能を実行でき、ビットコインのインフラを活用しながら契約を記述・デプロイできます。</p>
<p>    ルーンズ・プロトコル</p>
<p>    ルーンズ・プロトコルは、ビットコイン上に構築された非可変トークン・プロトコルで、公開されたより公平なミンティング発行方式を特徴としています。このプロトコルは、ビットコインの UTXO モデルを拡張し、UTXO がサトシと一緒に任意の fungible トークン（ルーンズ）を保持できるモデルを提供します。その主要な利点は、ビットコインの UTXO に基づいて構築されているため、トランザクションの手順が簡素化され、インデックスの効率が向上し、スケーラビリティが改善される点です。ルーンズは、オーディナルズ、インスクリプション、BRC-20 トークンとは完全に無関係であり、BRC-20 トークンと競合しています。ルーンズは、BRC-20 よりもブロックスペースの使用効率が高く（状態膨張に寄与しない）、ビットコインのプロトコル（ウォレット、ブリッジ、スケーラビリティ解決策）との互換性が高いです。対照的に、BRC-20 は通常、インターネットオーダイナルズ対応インフラを介して相互運用を行います。</p>
<p>    ルーンズ・プロトコルは、2024年のビットコイン半減期に発表され、多くの期待が寄せられました。事前にルーンズ・エアドロップがさまざまなオーディナルズ・プロジェクトから行われ、暗号Twitterで多くの議論を呼びました。このローンチは、OKX、ME、Unisats、Xverse など、20以上の主流 Web3 ウォレット、オンチェーン取引プラットフォーム、ビットコインエコシステムツールの支持を受け、ルーンズ資産のミンティング、取引、転送が初日から可能となりました。</p>
<p>    ルーンズ・プロトコルは急速に人気を集め、市場時価総額は20億ドルを超え、2024年の最も活発なエコシステムの一つとなりました。2024年4月20日のローンチ以来、ルーンズはビットコインの非可変トークン市場で支配的な地位を占め、ビットコイン取引の平均60%以上を占めています。ルーンズの取引は、ビットコインネットワーク全体の手数料の約30%に相当する、2,500 BTC以上の手数料を生成しています。</p>
<p>    ルーンズ・プロトコルは、ビットコインのパフォーマンスが低く、コストが高く、スマートコントラクトが不足しているという制限を克服するため、BTC Layer 2 や高速なスマートコントラクト実行チェーンと相互統合に向けて進化しています。</p>
<p>    一方で、ルーンズ・プロトコルの下で発行された多くのミームコインが BTC Layer 2 や他の高速スマートコントラクトチェーンに進出し、ミーム文化を拡大し、さらに多くのユースケースやコラボレーションを探っています。</p>
<p>    もう一方で、ビットコインエコシステムのプロジェクトや現実世界の資産（RWA）プロジェクトは、ルーンズ・プロトコルを利用してユーティリティトークンを発行することを選んでいます。これにより、ビットコイン上で資産を発行し、その後、BTC Layer 2 や他のスマートコントラクトチェーンにクロスチェーンして分配、取引、アプリケーション化が可能となります。</p>
<p>    ルーン $SATOSHI•RUNE•TITAN は、Bitlayer 上で構築され、LayerX GameFi プラットフォームのプラットフォームトークンとして機能します。ルーンズの7.1%がコミュニティインセンティブやガバナンスのために Bitlayer にクロスチェーンされており、市場時価総額で常にトップ15にランクインしています。</p>
<p>    ルーンズのクロスチェーン分野でのリーダーは Omnity Interoperability Protocol で、クロスチェーン資産ボリュームは1百万ドルを超えました。Omnity は、ビットコイン、ICP、Bitlayer、Merlin、BEVM、Bob、X Layer、B^2 Network を接続し、すべてのルーンズ資産をサポートしています。これにより、ICP の Chain Fusion テクノロジーを使用してオフチェーンコンポーネント（リレイヤーやインデクサー）に依存せず、オンチェーンで自己サービスのブリッジとルーンズ機能を提供します。Omnity プロトコルは、迅速で簡単、低コストなユーザー体験を提供し、ビットコインネットワーク資産に最適です。また、Layer 2 からのルーン彫刻、ミンティング、転送、焼却をサポートし、ビットコイン L1 と L2 の統合を提供します。</p>
<p>    結論として、ルーンズはビットコインの決済層における標準化された非可変トークンとして合法性を得ており、暗号世界のモジュラーアーキテクチャ内で広く認識されています。</p>
<p>    すべてのエコシステムはルーンズ資産を採用しており、クロスチェーンインフラと Layer 2 アプリケーションの開発が進む中、ルーンズ資産のクロスチェーンフローとアプリケーションの暗号エコシステム全体への浸透は避けられません。ルーンズエコシステムの活動と影響は引き続き成長し、暗号世界で最も重要で広く採用されている非可変トークン標準として位置づけられる可能性があります。</p>
<p>    Omnity</p>
<p>    Omnity は、ICP 上に構築されたクロスチェーンプロトコルで、モジュラーなブロックチェーンのランドスケープに統合するように設計されています。これは、クロスチェーンドメインにおける初の完全に分散型プロトコルで、最適なユーザー体験を優先します。Omnity は、ICP の Chain Key と HTTPS Outcalls などのユニークな機能を活用することで、セキュリティの脆弱性、高コスト、レイテンシ、流動性の断片化などの課題に対処します。このプロトコルは、既存のソリューションと比べて、よりコスト効率が良く、安全で普遍的なクロスチェーンサービスを提供します。</p>
<p>    ビットコインマイニングの未来</p>
<p>    「情報の非対称性は安定を生むが、透明性はボラティリティを生む。」この言葉は、伝統的な株式市場や金のような商品とビットコインとの対比を強調しています。伝統的な市場では、多くの活動が裏で行われ、インサイダー取引や秘密の取引が一般的です。規制により透明性が求められているものの、通常の投資家はインサイダーの後に重要な情報を受け取り、市場の反応が遅れることがあります。これにより、株価や商品には相対的な安定がもたらされ、市場はすべてのニュースに即座に反応しません。</p>
<p>    ビットコインは、すべてがオンチェーンで検証可能であるため、異なる原則の下で運営されます。この透明性は、いくつかの領域で顕著です：</p>
<p>    ウォレットアクティビティ：すべてのウォレットの残高が公開されており、特に大きな BTC の転送が監視されます。特にクジラが大きな金額を取引所に移動させると、市場の反応を引き起こすことがあります。</p>
<p>    ネットワークメトリック：総テラハッシュ率、ネットワークの難易度、マイナーの報酬など、主要なネットワークメトリックが公開されており、コインベース報酬アルゴリズムもすべてに知られています。</p>
<p>    トランザクションコスト：保留中の取引が確認を待つメモプールも公開され、現在のトランザクションコストが誰でも確認できます。</p>
<p>    ビットコインの透明性は、その大きな市場規模にもかかわらず、ボラティリティを高めています。株式や商品とは異なり、情報をコントロールできないため、ビットコインは市場に即座に影響を与えます。</p>
<p>    ビットコインマイニング</p>
<p>    透明性のあるビットコインエコシステムにおいて、マイナーはほとんど情報の非対称性がなく、すべてのデータが公開されています。マイニングは困難な作業で、マイナーは安価なエネルギーを必要とし、コストはドルで計算されますが、報酬はビットコインであり、価格の動きやマイニング難易度の影響を受けます。</p>
<p>    コスト要因：</p>
<p>    エネルギー価格：場所やエネルギー源に基づいて異なります。</p>
<p>    ハードウェア価格：製造業者へのアクセスやスケールメリット、技術の進歩によって影響されます。コンピューターパワーは2年ごとに倍増するため、マイナーは競争力を保つためにハードウェアのアップグレードを継続的に行う必要があります。</p>
<p>    収益要因：</p>
<p>    価格動向：ビットコインの市場時価総額は、法定通貨との取引活動に影響されます。</p>
<p>    マイニング報酬：コインベース報酬（ビットコインアルゴリズムによって設定された）と、取引手数料（ネットワークのトラフィックに依存）を含みます。</p>
<p>    マイナーは財務に関して非常に賢明であり、リスク管理のために先物取引などのデリバティブを利用することが多いです。</p>
<p>    Loka Mining によって提供されるエキゾチックなツールの一つが、先物ハッシュレート契約です。これは、トウモロコシ農家が未来の収穫を売るのと似ています。ビットコインマイナーは、将来のハッシュレートを売ることで現金前払金を受け取り、より多くの</p>
<p>    Loka、ChainFusion、およびBitcoinとICP空間の広範なDeFiエコシステムは急速に進化しており、マイナーと投資家の両方に強力なツールとソリューションのスイートを提供しています。以下は、議論された主要な特徴と概念の概要です。</p>
<h3 id="heading-loka"><strong>Lokaプラットフォーム</strong></h3>
<ul>
<li><p><strong>小売投資家</strong>: 未来のハッシュレート契約を通じて、Bitcoinを市場より低価格で取得でき、マイナーを支援しながら集中型リスクへの曝露なしで安価なエネルギー機会にアクセスできます。</p>
</li>
<li><p><strong>Bitcoinマイナー</strong>: 未来のハッシュレートを販売して投資の早期リターンを得、Bitcoinを即座に売却することなく運用を拡大でき、価格変動リスクをヘッジするのに役立ちます。</p>
</li>
<li><p><strong>信頼しない、非保管型</strong>: LokaのP2Pプロトコルは、投資家とマイナーの両方に対して分散型とセキュリティを保証します。</p>
</li>
</ul>
<h3 id="heading-chainfusion-amp-defi"><strong>ChainFusion &amp; DeFiイノベーション</strong></h3>
<ul>
<li><p><strong>Chain Fusion</strong>: ICPによって駆動され、ChainFusionは、BitcoinをEthereumなどのチェーンで通常見られるDeFi機能に接続し、ステーキング、レンディング、借入、イールド生成などの機能を可能にします。</p>
</li>
<li><p><strong>Bitomni</strong>: BitoBridgeやBitoRestakingなどの製品を通じて、Bitcoinを広範なDeFiエコシステムに統合し、ICPを介してセキュリティと構成可能性を確保しながらBitcoinベースのDeFiソリューションを提供します。</p>
</li>
<li><p><strong>ChainkeyX</strong>: Bitcoinを使用して、Stablecoinを必要とせずに貸借機能を提供するオンチェーン型ネオバンクで、すべてICPのChainFusionによって駆動されます。</p>
</li>
<li><p><strong>NFID Vaults</strong>: 許可のない、マルチチェーン、マルチ署名スマートウォレットアプローチを通じてウォレット回復とセキュリティを改善します。</p>
</li>
</ul>
<h3 id="heading-amp-1"><strong>分散型ウォレット &amp; アイデンティティソリューション</strong></h3>
<ul>
<li><p><strong>B3Wallet</strong>: 複数のチェーンにわたる資産管理のためにICPのChainFusionを活用する分散型ウォレットで、セキュリティのための複数の署名などの高度な機能を提供します。</p>
</li>
<li><p><strong>OISY Wallet</strong>: Bitcoin、Ethereum、およびICPにわたる資産をサポートする暗号ウォレットで、直接の鍵管理を不要にし、セキュアで統一された体験を提供します。</p>
</li>
<li><p><strong>Orbit</strong>: 開発者がさまざまなブロックチェーンネットワークでシームレスに動作するプログラム可能なウォレットを提供することで、ブロックチェーン統合を簡素化します。</p>
</li>
</ul>
<h3 id="heading-amp-defi"><strong>クロスチェーン &amp; DeFiアプリケーション</strong></h3>
<ul>
<li><p><strong>Helix Markets</strong>: ICPのChainFusionによって駆動される分散型取引所（DEX）で、脆弱なブリッジや流動性プールに依存せず、スケーラブルなクロスチェーントレーディングを実現します。</p>
</li>
<li><p><strong>ICP Swap</strong>: トークン発行、流動性プール、資産スワップを含むDeFiプラットフォームで、ChainFusionを使用してクロスチェーン操作を最適化します。</p>
</li>
<li><p><strong>KongSwap</strong>: ICPのChainFusionを使用して、取引、流動性調整、ステーキングプール、取引履歴の追跡などのDeFi操作を簡素化するために設計されたSuperDEXです。</p>
</li>
<li><p><strong>Sonic</strong>: ICPのスケーラビリティと低トランザクションコストを活用したDeFiハブで、ユーザーがトークンを作成し、スワップし、流動性提供によって報酬を得ることを可能にします。</p>
</li>
</ul>
<h3 id="heading-bitcoinethereum"><strong>BitcoinおよびEthereumとの統合</strong></h3>
<ul>
<li><strong>MSQ</strong>: ユーザーがMetamaskウォレットをICPに接続できるようにするMetamask拡張機能で、ICPベースの資産（ICP、ckBTC、ckETHなど）でのDeFi活動をサポートします。</li>
</ul>
<p>    本質的に、これらのプロジェクトは、Bitcoinがもはや単なる価値の保管庫ではなく、DeFiエコシステムにおいて動的な参加者であり続けるための道を開いています。これらの進展により、Bitcoinのマイナーと投資家は、より簡単で安全に進化する暗号エコシステムをナビゲートできます。</p>
<p>    DFinance</p>
<p>    DFinanceは、セキュアでユーザー中心の貸借エコシステムを提供することを目指す先進的なプラットフォームです。Internet Computer（ICP）ブロックチェーン上に構築され、比類のないデータセキュリティと分散化を実現します。このプラットフォームの使命は、ユーザーが将来に影響を与える力を持つ透明で民主的な金融環境を提供することです。</p>
<p>    DFinanceの主な目標は以下の通りです：</p>
<ul>
<li><p>貸借、ガバナンスのためのトークンのステーキング、提案および投票を通じてプラットフォームの開発への参加を提供する分散型金融ハブの確立</p>
</li>
<li><p>ダイナミックな金利戦略、信頼性のある価格フィード、ckBTCやckETHなどのさまざまなトークンオプションを提供し、DeFi体験の向上</p>
</li>
<li><p>イノベーションと包摂性を促進し、ユーザーガバナンスと透明性に焦点を当てたDeFi分野の基盤となる要素として自らを位置付ける</p>
</li>
</ul>
<p>    オフチェーンとオンチェーンの橋渡し</p>
<p>    従来、オラクルプロバイダーはオフチェーンとオンチェーンのデータ間のギャップを埋め、どのデータをどの条件で更新するかを決定していました。しかし、Internet Computer（ICP）は、これらの制限から開放することによって革新を起こしています。</p>
<p>    EthereumやSolanaのようなブロックチェーンは隔離された環境で動作しますが、ICPはオンチェーンアプリケーションと外部の世界との直接的な通信を可能にします。これにより、従来のブロックチェーンが処理するデータの範囲が限定されている問題を解決します。</p>
<p>    ICPのHTTPSアウトコールは、事実上あらゆる情報をオンチェーンデータとしてインデックスすることを可能にし、分散型アプリケーションの可能性を大幅に広げます。セキュリティは強力な検証メカニズムによって維持され、データの整合性が確保されます。</p>
<p>    このアプローチにより、ICPは潜在的な普遍的なオンチェーンデータハブとして位置付けられ、データ駆動型の次世代DeFiアプリケーションの道を切り開きます。</p>
<p>    例えば、ArbitrumベースのプロトコルはICP同期データを使用して担保率を調整したり、高度なリスクモデルを実装したりできます。Chainkeyによって駆動されるこのクロスチェーンデータフローは、単にエコシステムを橋渡しするだけでなく、より賢く、効率的なDeFiアプリケーションを促進します。</p>
<p>    この技術が成熟することで、隔離されたブロックチェーンの制限を超越し、真に相互接続されたデータ駆動型の分散型金融が実現される金融革新の波を引き起こすでしょう。</p>
<p>    オープンレーティング：ブロックチェーン時代の資産評価の革命</p>
<p>    ブロックチェーン技術が進化する中、評価システムは暗号エコシステムにおいて重要な役割を果たしています。これらのシステムは、オンチェーンデータが増加するにつれて、複雑なデータを単一の指標に簡素化します。ブロックチェーンの公開性により、評価は自動的にリアルタイムで更新されます。</p>
<p>    従来の金融とは異なり、暗号では個々のビルダーがプライベートに評価を作成して公開することができ、より多様で精度の高い評価エコシステムが促進されます。ブロックチェーンは膨大なデータ、評価、ビルダーの評判を統合し、透明性を高め、イノベーションを促進し、信頼を築きます。</p>
<p>    DeFiにとって重要であるだけでなく、評価の影響はガバナンス、デジタル資産、持続可能性、セキュリティにも広がります。ブロックチェーン分野が成熟するにつれて、これらの分散型評価システムは重要になり、暗号業界の信頼性を強化するでしょう。</p>
<p>    データLEGO：未来の構築ブロック</p>
<p>    ICPは、DeFiの「Money LEGO」原則に似た革命的なモジュラー型データ管理の概念を導入する可能性があります。このシステムは、特定の役割を持つ専門化されたキャニスターのネットワークを含みます：</p>
<ul>
<li><p>データ収集：特定のデータ（例：歴史的トークン価格）を収集し保存するキャニスター</p>
</li>
<li><p>データ処理：他のキャニスターからのデータに基づいて複雑な指標（例：ボラティリティ指数）を計算するキャニスター</p>
</li>
<li><p>柔軟性：データ収集キャニスターに影響を与えることなく、データ処理を変更できる新しいキャニスターの展開</p>
</li>
</ul>
<p>    このモジュラーアプローチは、HTTPSアウトコールを利用して多様なデータソースをインデックスし、Rustのような堅牢な言語を使用してキャニスター論理を構築することで、ICP上での共有知識の強力なネットワーク効果を生み出す可能性を秘めています。「Money LEGO」概念は、データにも同様に適用できます。</p>
<p>    クロスチェーンデータ中継：DeFi進化の触媒</p>
<p>    ICPのChainkey技術は、特にDeFiにおけるクロスチェーンデータの使用を変革する準備が整っています。この革新は、ICPから任意のチェーンへのデータの直接送信を可能にし、外部ネットワークのスマートコントラクトがICPの高度なデータや計算を利用できるようにし、さまざまなブロックチェーンエコシステム間でモジュラー「LEGOブロック」データのシームレスな同期を実現します。</p>
<p>    チェーンサイト：オンチェーンデータハブ</p>
<p>    Chainsightは、さまざまな市場からデータを集約し、それをオンチェーンで利用可能にする先進的なオンチェーンデータハブです。スマートコントラクトからのデータ取得を可能にし、HTTPSエンドポイントからの情報や他のチェーンから計算されたデータも含まれます。Chainsightは、多数のインデクサーのネットワークとして機能し、それぞれが独自のデータを管理します。これらのインデクサーは効率的にデータを統合し、新しい情報を生成してそれをEthereumのようなブロックチェーンに直接書き込みます。この設定により、オンチェーンアプリケーションは必要なデータを活用することができます。</p>
<p>    クロークレイヤー：すべてのブロックチェーン向けゼロ知識検証</p>
<p>    クロークレイヤーは、すべてのブロックチェーンでゼロ知識（ZK）検証を統合する方法を開発しています。ZK証明は、計算を高速化し、コストを削減することで主要なブロックチェーンアプリケーションのスケーラビリティに大きな影響を与え、オンチェーン機能に対するデータの可用性を増加させます。ZKは、ユーザーのプライバシーやレイヤー2やその他のブロックチェーンアプリケーションとサービスのセキュリティも強化します。これにより、オンチェーン取引の計算コストが削減され、計算負荷が軽減されます。クロークレイヤーは、ICのChain FusionおよびECDSA/EdDSA署名を活用して、ブロックチェーン間でZK-as-a-Serviceを提供し、完全に信頼のない方法で動作します。</p>
<p>    ブロックチェーン上のブロックチェーン：イントロダクション</p>
<p>    「ブロックチェーン上のブロックチェーン」とICPのネットワーク手数料の爆発</p>
<p>    「ブロックチェーン上のブロックチェーン」という概念は、特に9月のBOBのローンチ後に革新的なユースケースとして登場しました。BOBは、ICPの強力な計算能力を利用して、ビットコインに似たプルーフ・オブ・ワークメカニズムを使用してメモコインをオンチェーンでホストします。このモデルは、トークンの配布における検証可能な公平性や、ハードウェア優位性を通じたマイナーの優位性を防ぐなど、いくつかの利点を提供します。</p>
<p>    BOBの成功は「ブロックチェーン上のブロックチェーン」カテゴリーのさらなる発展を促し、Internet Computer上での計算の大幅な増加を引き起こしました。この増加により、ネットワーク手数料、いわゆる「サイクルバーン」が急増し、2024年1月から8月の間にサイクルバーン率が90％増加しました。しかし、BOBのローンチだけで、8月から9月の間にサイクルバーンが驚異的な3000％増加し、35日間で過去3年間に消費されたICPを上回りました。この成長は衰える気配がなく、より多くの企業家が新しい「ブロックチェーン上のブロックチェーン」アプリケーションを探求しています。</p>
<p>    #BOB：レイヤー2スケーリングのためのプルーフ・オブ・ワーク</p>
<p>    BOB（Blockchain on Blockchain）は、レイヤー2ソリューションにプルーフ・オブ・ワークスタイルのコンセンサスを導入する目的で作られたシステムです。公式ウェブサイトによれば、BOBは「ビットコインのコンセンサスとドージのユーティリティ」を融合させ、ブロックチェーンの相互運用性とスケーリングに対する新たなアプローチを作り出しています。</p>
<p>    そのアプリケーションがすぐに明確でないかもしれませんが、BOBがレイヤー2ネットワークに新しいコンセンサスメカニズムをもたらす能力は重要な革新を意味しています。これはICPを主要なマイニングメカニズムとして活用することで実現されており、マイナーはICPを使ってマイニングサイクルを購入するか、マイニング速度を調整して、消費されるICPの量に直接影響を与えます。</p>
<p>    MSQ.Burn：公正で効率的なメモコインマイナー</p>
<p>    MSQ.Burnは、MSQ Metamaskウォレット拡張機能の作成者によって開発されたメモコインマイナーで、メモコイン運用の公正性を確保します。BURNプールのすべてのメンバーは、ブロックが発行されるたびに比例して報酬を受け取ります。</p>
<p>    BURNはシンプルなトークンモデルに従っており、ブロック報酬は5,040ブロックごとに半減（おおよそ1週間に1回）し、1 BURNに達した時点でブロック時間が徐々に12時間に達するまで増加します。この時点で、制御されたインフレ圧力が導入されます。</p>
<p>    このプロジェクトは効率性にも重点を置き、マイニングの無駄を最小限に抑え、不要な計算サイクルのバーンを削減することを目指しています。</p>
<p>    詳細については:<a target="_blank">file:///C:/Users/user/Downloads/ICP-ChainFusion-Ecosystem-Report-2024%20(1).pdf</a></p>
]]></content:encoded></item><item><title><![CDATA[Development On Icp Ecosystem]]></title><description><![CDATA[ICP (Internet Computer Protocol) is a public blockchain network developed by DFINITY to replace the traditional IT stack and remove reliance on commercial…]]></description><link>https://nwa-eddy84.hashnode.dev/development-on-icp-ecosystem</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/development-on-icp-ecosystem</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Mon, 10 Feb 2025 00:29:51 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-the-icp-ecosystem">THE ICP ECOSYSTEM</h1>
<p>ICP (<strong>Internet Computer Protocol</strong>) is a <strong>public blockchain network</strong> developed by <strong>DFINITY</strong> to replace the traditional IT stack and remove reliance on commercial cloud services. It is designed to be a <strong>scalable, cloud-like blockchain platform</strong> capable of hosting <strong>internet services, websites, and financial systems</strong> using only smart contracts, without any external private systems.</p>
<p>The Internet Computer stores data, supports application development, and enables network interoperability.</p>
<p>For a basic understanding of ICP’s structure and use cases, check out an <strong>introductory article</strong> on the subject. This summary focuses on key events leading to ICP’s <strong>mainnet launch, Mercury, in 2021</strong>.</p>
<h1 id="heading-internet-computer-protocols-release-history"><strong>Internet Computer Protocol’s Release History</strong></h1>
<p>DFINITY released several <strong>ICP components</strong> between <strong>2019 and 2020</strong>, leading up to the <strong>Mercury mainnet launch in 2021</strong>. The key milestones were:</p>
<ul>
<li><p><strong>Copper (Q4 2019)</strong> – Introduced the first public <strong>DFINITY Canister SDK</strong>, specialized smart contracts (<strong>canisters</strong>), and the <strong>Motoko programming language</strong>, inspired by WebAssembly (WASM), designed for tamper-resistant software.</p>
</li>
<li><p><strong>Bronze (Q1 2020)</strong> – Enabled ICP's transition from terminal-based execution to <strong>desktop web application development</strong>, allowing <strong>canisters to store their own state, frontend, and backend logic</strong>.</p>
</li>
<li><p><strong>Tungsten (Q2 2020)</strong> – Opened <strong>ICP to third-party developers</strong>, allowing them to build applications and enterprise systems. Also introduced <strong>mobile development</strong> on top of desktop capabilities.</p>
</li>
<li><p><strong>Sodium (Q4 2020)</strong> – Introduced the <strong>Network Nervous System (NNS)</strong> for protocol economics, subnet governance, and hosting. Also launched <strong>cycles</strong> for canister interactions and <strong>neurons</strong> for governance and staking via the <strong>ICP coin</strong>.</p>
</li>
</ul>
<p>This development culminated in the <strong>Mercury mainnet launch in 2021</strong>, bringing ICP into full-scale deployment. 🚀</p>
<h1 id="heading-icps-mercury-mainnet"><strong>ICP’s Mercury Mainnet</strong></h1>
<p>DFINITY launched the <strong>Mercury mainnet</strong> on <strong>May 7, 2021</strong>, making the <strong>Internet Computer</strong> fully publicly available. The project aims to achieve several key goals:</p>
<p>[if !supportLists]·         [endif]<strong>Public Network Growth</strong> – ICP enables network effects by offering <strong>interoperability between diverse code bases and blockchain systems</strong> at a low cost through <strong>specialized smart contracts (canisters)</strong>, similar to how traditional software integrates software libraries.</p>
<p>[if !supportLists]·         [endif]<strong>Security and Privacy-Focused Systems</strong> – Traditional IT relies on <strong>proprietary cloud computing</strong> and centralized infrastructure, which have security vulnerabilities. ICP <strong>leverages cryptography and Chain Key technology</strong> to enhance security and allow the <strong>Network Nervous System (NNS)</strong> to manage <strong>in-network subnets</strong> securely.</p>
<p>[if !supportLists]·         [endif]<strong>Reimagined Smart Contracts</strong> – <strong>ICP’s smart contracts (software canisters)</strong> are designed to <strong>reduce scalability and complexity issues</strong>, lowering costs and effort required for <strong>building and maintaining network systems</strong>.</p>
<p>[if !supportLists]·         [endif]<strong>Eliminating Centralized Intermediaries</strong> – Unlike traditional blockchain applications hosted on centralized cloud services like <strong>AWS</strong>, <strong>ICP hosts smart contracts that directly serve content to web browsers</strong>. This improves <strong>security, censorship resistance, and uptime</strong>, reducing reliance on third-party services.</p>
<p>[if !supportLists]·         [endif]<strong>Improving Usability</strong> – <strong>ICP eliminates the need for transaction fees</strong> and token-based interactions for users. Instead of <strong>signing up for accounts and KYC</strong>, users authenticate via <strong>WebAuthn</strong>, using <strong>cryptographic keys</strong>, such as <strong>fingerprint scanning on their laptop or smartphone</strong>.</p>
<h1 id="heading-orally"><strong>Orally</strong></h1>
<p>The fully on-chain oracles for secure and reliable decentralized data feeding and automation across multiple chains. Experience seamless real-world data integration across various blockchains, powering dynamic, secure, and efficient dApps.</p>
<p><strong>Sibyl</strong><br />Decentralized data fetcher.<br />Efficient on-demand delivery with verifiable data.<br />Enables custom data feeds.</p>
<p><strong>Pythia</strong></p>
<ul>
<li><p>On-chain automation tool</p>
</li>
<li><p>Random Number Generator (RNG)</p>
</li>
<li><p>Provides data from Sibyl</p>
</li>
</ul>
<p><strong>Apollo</strong></p>
<ul>
<li><p>EVM request-based data delivery</p>
</li>
<li><p>Random Number Generator (RNG)</p>
</li>
<li><p>Provides data from Sibyl</p>
</li>
</ul>
<p><strong>Cassandra</strong><br />Decentralized authentication to Gmail, Twitter, etc., for dApps.</p>
<p><strong>Delphos</strong><br />Decentralized data preprocessing with custom preprocessing algorithms for data streams.</p>
<h1 id="heading-code-integration"><strong>Code Integration</strong></h1>
<h4 id="heading-start"><strong>Start</strong></h4>
<p>Fetch price feed data:</p>
<pre><code class="lang-plaintext">javascript
</code></pre>
<pre><code class="lang-plaintext">CopyEdit
</code></pre>
<pre><code class="lang-plaintext">const fetchData = async () =&gt; {
</code></pre>
<pre><code class="lang-plaintext">  const response = await fetch("https://wth3l-tiaaa-aaaap-aa5uq-cai.icp0.io/get_asset_data_with_proof?pair_id=ICP/USD");
</code></pre>
<pre><code class="lang-plaintext">  const data = await response.json();
</code></pre>
<pre><code class="lang-plaintext">  console.log(data);
</code></pre>
<pre><code class="lang-plaintext">};
</code></pre>
<pre><code class="lang-plaintext">fetchData();
</code></pre>
<h4 id="heading-response-example"><strong>Response Example</strong></h4>
<pre><code class="lang-plaintext">json
</code></pre>
<pre><code class="lang-plaintext">CopyEdit
</code></pre>
<pre><code class="lang-plaintext">{
</code></pre>
<pre><code class="lang-plaintext">    "symbol": "ICP/USD",
</code></pre>
<pre><code class="lang-plaintext">    "rate": 4902941764,
</code></pre>
<pre><code class="lang-plaintext">    "timestamp": 1685442778,
</code></pre>
<pre><code class="lang-plaintext">    "decimals": 9,
</code></pre>
<pre><code class="lang-plaintext">    "signature": "5d4368547f194ff784d904cc9052108894044bba7588d2447bd13f070128ef6d690e12094b5e3c6c304187587cd6ff8b4d35dfc3ea4b7165f79d2e881b446dd31c"
</code></pre>
<pre><code class="lang-plaintext">}
</code></pre>
<h3 id="heading-benefits"><strong>Benefits</strong></h3>
<p><strong>Unbeatable Cost Efficiency</strong><br />Harness the power of ICP to access real-world data with minimal overhead, using a groundbreaking approach that delivers data feeds at incredibly low costs.</p>
<h3 id="heading-fully-decentralized-amp-trustless"><strong>Fully Decentralized &amp; Trustless</strong></h3>
<p>Orally leverages advanced ICP features, including HTTP Outcalls, ECDSA threshold signatures, and random tape, to provide secure and reliable data feeds.</p>
<h3 id="heading-cross-chain-compatibility"><strong>Cross-Chain Compatibility</strong></h3>
<p>Seamlessly integrate Orally into various blockchains, expanding possibilities for decentralized applications.</p>
<h3 id="heading-custom-data-feed"><strong>Custom Data Feed</strong></h3>
<p>Access tailored data feeds for diverse dApp needs, from market trends to real-world events, enhancing reliability and relevance.</p>
<h3 id="heading-modular-amp-compositional-approach"><strong>Modular &amp; Compositional Approach</strong></h3>
<p>Benefit from a flexible, scalable architecture that allows easy adaptation and evolution to meet the changing demands of blockchain applications.</p>
<h3 id="heading-how-it-works"><strong>How It Works</strong></h3>
<p><strong>Step 1</strong><br />Choose your desired Orally product (Sibyl or Pythia) and integrate it into your DApp.</p>
<p><strong>Step 2</strong><br />Subscribe to the oracle service and configure settings such as data sources, frequency, and custom assets (if applicable).</p>
<p><strong>Step 3</strong><br />Orally fetches and processes real-world data, leveraging the power of ICP and special data flow for maximum efficiency and security.</p>
<p><strong>Step 4</strong><br />Data is securely transferred directly to the DApp by end user or automated transactions, allowing developers to access and utilize it in their decentralized applications.</p>
<h1 id="heading-use-cases"><strong>Use Cases</strong></h1>
<p><strong>Decentralized Finance</strong><br />Access real-time price feeds for various assets, enabling accurate pricing and market analysis.</p>
<p><strong>Gaming &amp; NFTs</strong><br />Implement randomness and automation to create dynamic, unpredictable, and fair gaming experiences.</p>
<p><strong>Supply Chain Management</strong><br />Track and verify the movement of goods with secure and reliable data from multiple sources.</p>
<h1 id="heading-chain-fusions-2024-milestones-and-future-vision"><strong>Chain Fusion's 2024 Milestones and Future Vision</strong></h1>
<p>In 2024, Chain Fusion truly became multi-chain, starting with the addition of <strong>ckETH</strong> alongside <strong>ckBTC</strong>, marking the launch of synthetic twin assets on ICP. These assets are held in custody by smart contract logic, governed by the ICP governance system. This milestone was followed by <strong>full Ethereum integration</strong>, highlighted by the <strong>Tritium milestone</strong>, which enabled full read/write support for the Ethereum ecosystem, including EVMs and L2s.</p>
<p>The technology behind this integration—RPC endpoints through HTTPS outcalls—also unlocked other chain integrations, bringing the total number of supported chains to <strong>two dozen</strong>. Ethereum integration came with improvements in <strong>signing latency and throughput</strong> and enabled the launch of "ck" versions of ERC-20 tokens. While the year began with only one <strong>ck token</strong> (ckBTC), the count now stands at <strong>23</strong>, with <strong>ckBTC</strong>, <strong>ckETH</strong>, <strong>ckUSDC</strong>, and <strong>ckUSDT</strong> being the most used.</p>
<p>Additionally, <strong>2024</strong> saw the release of <strong>threshold Schnorr signatures</strong> and <strong>bitcoin block head data</strong> during the <strong>Deuterium milestone</strong>. These features open up new possibilities for Bitcoin-related fungible tokens like <strong>BRC-20s</strong> and <strong>runes</strong>, as well as the creation of decentralized Bitcoin services and infrastructure.</p>
<h1 id="heading-chain-fusion-hubs-uniting-ecosystems"><strong>Chain Fusion HUBS: Uniting Ecosystems</strong></h1>
<p>Chain Fusion HUBS aim to unify diverse blockchain ecosystems, providing seamless interoperability and supporting cross-chain transactions. By leveraging innovations like the integration of multiple blockchains (Bitcoin, Ethereum, Solana) and advanced signature algorithms (ECDSA, Schnorr, EdDSA), Chain Fusion HUBS facilitate the exchange of assets and data between ecosystems in a secure and efficient manner. This approach enhances the potential for decentralized applications and services, paving the way for a more connected and integrated blockchain world.</p>
<p>In <strong>2024</strong>, <strong>Chain Fusion HUBS</strong> emerged as a pivotal series of events for the <strong>Internet Computer (ICP)</strong> ecosystem, embodying core values of <strong>interoperability</strong> and <strong>collaboration</strong>. These gatherings successfully brought together a diverse mix of crypto enthusiasts, developers, and institutional players, fostering a unified vision for a decentralized future.</p>
<p>Each edition of <strong>Chain Fusion HUBS</strong> has showcased the potential for real-world connections within the <strong>Web3</strong> space, emphasizing the unique contributions of <strong>ICP</strong> and its <strong>Chain Fusion</strong> technology. These events highlighted how ICP’s advancements in blockchain integration and interoperability could shape the future of decentralized applications and services.</p>
<h1 id="heading-ethcc-brussels-chain-fusion-hub"><strong>EthCC – Brussels: Chain Fusion HUB</strong></h1>
<p>The <strong>Chain Fusion HUB</strong> at <strong>EthCC – Brussels</strong> marked the inaugural showcase of the <strong>Chain Fusion</strong> narrative, successfully engaging both the <strong>Ethereum community</strong> and the broader <strong>crypto landscape</strong>. This event emphasized <strong>ICP’s</strong> commitment to contributing to the <strong>ETH ecosystem</strong> through its innovative third-generation blockchain technology.</p>
<p>The team's interaction with various stakeholders during the event led to promising leads for future collaborations, establishing a strong foundation for ongoing developments and further strengthening the relationship between <strong>ICP</strong> and the <strong>Ethereum</strong> community.</p>
<p>Bitcoin Integration Challenges</p>
<h1 id="heading-introduction"><strong>Introduction</strong></h1>
<p><strong>User fragmentation</strong> and <strong>liquidity fragmentation</strong> continue to grow across the crypto ecosystem. This issue is evident across <strong>Layer 1s</strong> (e.g., <strong>BTC</strong>, <strong>ETH</strong>, <strong>SOL</strong>), within L1 ecosystems (e.g., <strong>ETH</strong>, <strong>Polygon</strong>, <strong>Arbitrum</strong>, <strong>Optimism</strong>), and even within a single chain, such as the <strong>fungible token standards</strong> on Bitcoin (e.g., <strong>BRC-20</strong>, <strong>Runes</strong>, <strong>Atomicals</strong>, <strong>TAP</strong>). This fragmentation problem will continue to expand as developers introduce new <strong>L1s</strong>, <strong>L2s</strong>, <strong>sidechains</strong>, <strong>rollups</strong>, and token standards.</p>
<p>The issue is worsened by the sheer volume of infrastructure in the crypto space, where every infrastructure product requires users, developers, and liquidity to thrive. This creates a massive capitalistic force, leading to the crypto ecosystem being divided into <strong>walled-off gardens</strong> that generally lack composability. We see this fragmentation in various forms, such as <strong>incentivization models</strong>, <strong>points programs</strong>, <strong>airdrops</strong>, <strong>tokens</strong>, and even <strong>developer grants</strong>.</p>
<p>With so many forces fragmenting the ecosystem, there is a greater need than ever for <strong>seamless</strong>, <strong>permissionless interoperability solutions</strong>.</p>
<h1 id="heading-the-interoperability-problem-for-bitcoin"><strong>The Interoperability Problem for Bitcoin</strong></h1>
<p>Existing interoperability solutions like <strong>Layer Zero</strong>, <strong>Wormhole</strong>, <strong>Axelar</strong>, <strong>Particle Network</strong>, and <strong>Across</strong> are attempting to fill the <strong>omni-chain gap</strong>. These solutions work by deploying <strong>omni-chain smart contracts</strong> on source and destination chains, allowing for the burning and minting of tokens across chains. Typically, they consist of:</p>
<ul>
<li><p>A <strong>relayer network</strong> for message transport</p>
</li>
<li><p><strong>Signing services</strong> to create cross-chain transactions</p>
</li>
<li><p>An <strong>oracle solution</strong> to validate finality on source chain transactions</p>
</li>
<li><p><strong>Developer tooling</strong> to enable omni-chain applications</p>
</li>
</ul>
<p>However, the issue with these models is that you can't deploy omni-chain smart contracts on <strong>Bitcoin</strong>, meaning <strong>Bitcoin assets</strong> cannot currently plug into these systems. This includes <strong>BTC</strong>, the <strong>Lightning Network</strong>, <strong>Ordinals</strong>, <strong>BRC-20</strong>, <strong>Runes</strong>, <strong>Tap</strong>, <strong>Pipe</strong>, <strong>Atomicals</strong>, <strong>BRC-100</strong>, <strong>RSM</strong>, <strong>OP_NET</strong>, and others. Additionally, <strong>Bitcoin sidechains</strong> or <strong>Bitcoin L2s</strong> that don't align with the <strong>EVM</strong> focus of most existing interoperability solutions (like <strong>Move</strong>, <strong>SVM</strong>, <strong>WASM</strong>, etc.) also face limitations.</p>
<p>Solutions such as <strong>L3s</strong>, <strong>shared sequencing</strong> (e.g., <strong>Espresso</strong>), <strong>shared bridging</strong> (e.g., <strong>Polygon Agg Layer</strong>), and <strong>real-time proving</strong> between rollups are potential interoperability models within their specific tech stacks. However, it's overly optimistic to expect that everyone will build on a single stack.</p>
<h1 id="heading-potential-solution-bitcoin-native-layer-0-with-icp"><strong>Potential Solution: Bitcoin-native Layer 0 with ICP</strong></h1>
<p>A potential solution could be a <strong>Bitcoin-native Layer 0 interoperability protocol</strong>. This would be a <strong>Layer 0 protocol</strong> that focuses primarily on <strong>Bitcoin</strong>, while also integrating other ecosystems like <strong>ETH</strong>, <strong>ETH L2s</strong>, <strong>Solana</strong>, and <strong>Cosmos</strong>. The protocol would have two main components:</p>
<ol>
<li><p><strong>Node Network</strong>: The <strong>node network</strong> on ICP would be <strong>threshold signing subnets</strong>. These subnets can handle <strong>threshold signing</strong> (ECDSA, Schnorr, EdDSA) to enable cross-chain signatures. Additionally, ICP supports an <strong>ultra-light node setup</strong>, where blocks are pulled in as needed to verify finality on source chains.</p>
</li>
<li><p><strong>Execution Layer</strong>: These <strong>threshold signing subnets</strong> are natively integrated into the <strong>Internet Computer Protocol (ICP)</strong>, making it easy to incorporate them directly with <strong>ICP smart contracts</strong>. This <strong>execution layer (ICP)</strong> serves as the home for <strong>omni-chain applications</strong>. Developers could potentially build a single application that operates seamlessly across <strong>Bitcoin native assets</strong>, <strong>metaprotocols</strong>, <strong>sidechains</strong>, <strong>L2s</strong>, and other <strong>L1s</strong>, unlocking broader interoperability and use cases across different blockchain ecosystems.</p>
</li>
</ol>
<h1 id="heading-leveraging-icp-for-bitcoin-layer-0"><strong>Leveraging ICP for Bitcoin Layer 0</strong></h1>
<p>The <strong>Internet Computer Protocol (ICP)</strong> offers several key features that make it particularly well-suited for implementing a <strong>Bitcoin Layer 0</strong> solution:</p>
<p>[if !supportLists]1.      [endif]<strong>Bitcoin Light Node</strong>: ICP can run a <strong>Bitcoin light node</strong> fully on-chain, enabling direct verification of Bitcoin transactions and blocks on ICP. This provides a secure and decentralized way to interact with the Bitcoin network.</p>
<p>[if !supportLists]2.      [endif]<strong>Threshold Signing Subnets</strong>: ICP supports <strong>threshold signing subnets</strong> for <strong>ECDSA</strong>, <strong>Schnorr</strong>, and <strong>EdDSA</strong> (coming soon). This is crucial for enabling secure cross-chain signatures.</p>
<p>[if !supportLists]3.      [endif]<strong>HTTP Calls in Smart Contracts</strong>: ICP smart contracts can make <strong>HTTP calls</strong> directly, allowing for easy integration of external data sources and oracles. This is essential for verifying finality on source chains and enabling cross-chain communication.</p>
<p>[if !supportLists]4.      [endif]<strong>Gasless Transactions</strong>: Users on ICP do not have to pay <strong>gas fees</strong> for transactions, significantly improving the user experience and lowering the barrier to entry for interacting with the protocol.</p>
<p>These features of <strong>ICP</strong> could potentially address many of the technical challenges involved in creating a <strong>Bitcoin Layer 0</strong> solution, providing a robust foundation for building interoperable, cross-chain applications.</p>
<h1 id="heading-bioniq">Bioniq</h1>
<p><strong>Bioniq</strong> leverages <strong>Chain Fusion</strong> to enable the creation, collection, and trading of <strong>bitcoin-based Ordinals</strong> without the need to pay gas fees and with quick transaction times. <strong>Bitcoin Ordinals</strong> are like <strong>Bitcoin-based non-fungible tokens (NFTs)</strong>. They allow for writing and recording individual information to the transaction data of Bitcoin transactions, making each transaction unique.</p>
<p>This enables Bitcoin to be used for <strong>collectibles</strong> or other <strong>NFT-like projects</strong>. However, creating Ordinals on Bitcoin is often expensive due to transaction costs and can lead to network congestion. This is where <strong>Bioniq</strong> solves the issue.</p>
<p>By using <strong>Chain Fusion</strong> and having <strong>ICP</strong> handle most of the backend work while still leveraging Bitcoin’s bomb-proof ledger, <strong>Bioniq</strong> provides the best of both worlds: <strong>no-cost NFTs</strong> that settle quickly, all while residing on Bitcoin’s global and immutable ledger.</p>
<p>Meta-Protocols on Bitcoin</p>
<h1 id="heading-overview"><strong>Overview</strong></h1>
<p>The evolution of <strong>token protocols on Bitcoin</strong>, from <strong>Colored Coins</strong> to <strong>Ordinals</strong>, <strong>Runes</strong>, and <strong>Atomicals</strong>, showcases the ongoing innovation in the ecosystem. Technological advancements like <strong>SegWit</strong>, <strong>Schnorr signatures</strong>, and <strong>Taproot</strong> have unlocked new possibilities, transforming Bitcoin into a more versatile and robust platform for <strong>decentralized finance</strong>. These developments signal a new era for Bitcoin, expanding its role beyond being just a <strong>store of value</strong> to becoming the foundation for diverse <strong>digital assets</strong> and complex financial applications.</p>
<h1 id="heading-metaprotocols-10"><strong>Metaprotocols 1.0</strong></h1>
<p><strong>Early Efforts: Colored Coins and Ethereum</strong></p>
<p>The initial efforts to create tokens on <strong>Bitcoin</strong> began with <strong>Colored Coins</strong>. This method involved “coloring” specific <strong>Satoshis</strong> with additional information to represent assets like <strong>stocks</strong> or <strong>real estate</strong>. Despite its innovative approach, <strong>Colored Coins</strong> faced significant limitations due to Bitcoin's scripting constraints and the lack of native support for complex transactions.</p>
<p>These challenges prompted the need for more advanced solutions, which led to the creation of <strong>Ethereum</strong>. Ethereum was designed to address Bitcoin’s limitations by offering a more flexible platform for <strong>decentralized applications (dApps)</strong> and <strong>smart contracts</strong>. The introduction of the <strong>ERC-20 standard</strong> by Ethereum laid the foundation for a vast ecosystem of <strong>tokens</strong> and <strong>dApps</strong>, marking a significant advancement in blockchain technology.</p>
<h1 id="heading-new-paradigms-ordinals-runes-and-atomicals"><strong>New Paradigms: Ordinals, Runes, and Atomicals</strong></h1>
<p><strong>Ordinals</strong>: Ordinals allow data inscriptions on individual <strong>Satoshis</strong>, enabling unique digital assets directly on the <strong>Bitcoin</strong> blockchain. This method, although innovative, led to issues like network congestion and high fees due to its <strong>non-UTXO</strong> model.</p>
<p><strong>Runes</strong>: <strong>Runes</strong> address some of the inefficiencies of <strong>Ordinals</strong> by utilizing Bitcoin’s <strong>UTXO model</strong>, making it more scalable and easier to integrate with existing infrastructure. <strong>Runes</strong> are ideal for fungible tokens like <strong>stablecoins</strong> and <strong>loyalty points</strong>.</p>
<p><strong>Atomicals</strong>: <strong>Atomicals</strong> leverage the <strong>UTXO model</strong> to introduce the <strong>ARC-20 standard</strong>, backing each token with a <strong>Satoshi</strong>. This ensures intrinsic value and simplifies token management while avoiding the off-chain indexing issues of <strong>BRC-20 tokens</strong>.</p>
<h1 id="heading-technological-enhancements-taproot-schnorr-signatures-and-segregated-witness"><strong>Technological Enhancements: Taproot, Schnorr Signatures, and Segregated Witness</strong></h1>
<p><strong>Segregated Witness (SegWit)</strong>: Implemented in <strong>2017</strong>, <strong>SegWit</strong> separates transaction <strong>signatures</strong> from transaction data, reducing transaction sizes and increasing Bitcoin’s <strong>block capacity</strong>. It also mitigates <strong>transaction malleability</strong>, paving the way for more advanced second-layer solutions like the <strong>Lightning Network</strong>.</p>
<p><strong>Schnorr Signatures</strong>: <strong>Schnorr signatures</strong> offer a more efficient and secure way to aggregate multiple signatures into one, reducing the size of multi-signature transactions. This improves scalability and enhances privacy by making multi-signature transactions indistinguishable from regular transactions.</p>
<p><strong>Taproot</strong>: Activated in <strong>2021</strong>, <strong>Taproot</strong> introduces <strong>MAST</strong> (Merkelized Abstract Syntax Trees) and integrates <strong>Schnorr signatures</strong>, allowing for more complex and private <strong>smart contracts</strong>.</p>
<h1 id="heading-metaprotocols-20"><strong>Metaprotocols 2.0</strong></h1>
<p>Since the beginning of <strong>2024</strong>, <strong>metaprotocols</strong> have seen rapid development. In <strong>April</strong>, during the halving cycle, the successful launch of <strong>Runes</strong> pushed metaprotocols to new transaction volume peaks. However, by <strong>May</strong>, with the overall adjustment of the crypto market, user fatigue towards new asset issuance stories and a lack of market liquidity led to a downturn in metaprotocols. Despite this, developers continue to iterate and innovate on <strong>metaprotocols</strong>.</p>
<p>This advancement enhances Bitcoin’s scripting capabilities, making it more suitable for advanced applications and reducing transaction costs.</p>
<h1 id="heading-meme-vs-utility-tokens"><strong>MEME vs. Utility Tokens</strong></h1>
<p>The current landscape of tokens on <strong>Bitcoin</strong>, particularly those under the <strong>Ordinals</strong> and <strong>BRC-20 standards</strong>, is predominantly <strong>meme-based</strong>. These tokens often lack functional utility, serving more as <strong>speculative assets</strong> rather than offering tangible benefits. Transitioning from meme to utility involves integrating functionalities such as <strong>governance</strong>, <strong>staking</strong>, or access to specific services. <strong>Utility tokens</strong> have the potential to enhance value and foster broader adoption within the crypto ecosystem.</p>
<p>Developers and the market have high expectations for <strong>OP_CAT</strong>, a Bitcoin script operation code capable of concatenating strings, which could enhance Bitcoin’s scripting capabilities. This enhancement could enable more complex operations and functionalities, paving the way for utility-based tokens with advanced contract logic. However, as an early-stage proposal, the timeline for <strong>OP_CAT</strong>’s integration into Bitcoin’s <strong>mainnet</strong> remains uncertain.</p>
<h1 id="heading-programmability-and-evolution"><strong>Programmability and Evolution</strong></h1>
<p>The development and deployment of advanced token protocols and smart contracts on <strong>Bitcoin</strong> currently require significant programming skills. However, the ecosystem is evolving to provide more <strong>user-friendly</strong> tools and frameworks, reducing this barrier. One possible future direction is bridging Bitcoin with <strong>Ethereum’s Virtual Machine (EVM)</strong>, allowing Bitcoin to leverage Ethereum’s extensive smart contract capabilities. This approach would foster <strong>interoperability</strong> and expand the potential use cases for Bitcoin-based assets. Alternatively, enhancing Bitcoin’s native programmability could involve developing new <strong>scripting languages</strong> or extending existing ones, enabling more sophisticated smart contracts and decentralized applications (<strong>dApps</strong>) directly on Bitcoin without relying on external chains.</p>
<h1 id="heading-user-and-market-demands"><strong>User and Market Demands</strong></h1>
<p>Users and markets are increasingly demanding tokens with <strong>tangible utility</strong>, reflecting a desire for assets that offer more than just speculative value. This includes tokens that can be used in <strong>real-world applications</strong>, provide <strong>governance rights</strong>, or offer <strong>staking rewards</strong>. <strong>Venture Capital (VC)-backed</strong> tokens have fallen out of favor due to concerns about centralization and unequal distribution, which contradict the decentralized ethos of the crypto community. Additionally, the perception that VC tokens prioritize <strong>profit extraction</strong> over community and long-term project sustainability has caused wariness among users and investors. The market has also seen an influx of VC-backed tokens, many of which have failed to deliver on their promises, leading to skepticism and a preference for community-driven, <strong>transparent projects</strong>.</p>
<h1 id="heading-opportunities-with-internet-computer-icp"><strong>Opportunities with Internet Computer (ICP)</strong></h1>
<p>The <strong>Internet Computer (ICP)</strong> is continuously enhancing and exploring integrations with Bitcoin, presenting significant opportunities for <strong>metaprotocols</strong>. ICP’s <strong>subnets</strong> provide a <strong>Bitcoin API</strong>, and soon, the <strong>Header API</strong> will be introduced, enabling on-chain verification of Bitcoin transactions and acting as Simplified Payment Verification (<strong>SPV</strong>) nodes. This integration allows ICP canister smart contracts to directly interact with the <strong>Bitcoin network</strong> without intermediaries, facilitating seamless transactions and improving security.</p>
<p>ICP now supports <strong>Threshold Schnorr signatures</strong> following the implementation of <strong>t-ECDSA</strong>.</p>
<p>The development of ICP's capabilities means that ICP subnets are able to support and broadcast <strong>Taproot signatures</strong>, enhancing compatibility with advanced <strong>Bitcoin protocols</strong> and expanding the capabilities of <strong>Bitcoin-based applications</strong>. These enhancements position ICP as a robust platform for developing next-generation Bitcoin protocols, leveraging its unique features like <strong>chain-key cryptography</strong> and high-performance <strong>smart contracts</strong>.</p>
<p>Building on its capabilities, ICP can provide the <strong>technical foundation</strong> needed for enhanced programmability and the creation of <strong>utility tokens</strong>. By natively implementing <strong>BTC transaction indexing</strong> and <strong>metaprotocol declarations</strong> using its token standards, ICP offers a new combined paradigm that integrates current metaprotocol advancements with <strong>chain-key technology</strong>. This fusion can lead to the development of <strong>trustless liquidity markets</strong>, allowing seamless and secure interactions between different digital assets, thereby attracting more users to issue and engage with <strong>metaprotocols</strong> on ICP.</p>
<h1 id="heading-rainbow-protocol">Rainbow Protocol</h1>
<p>Rainbow Protocol is enhancing Bitcoin with new functionality. Its main goal is to make it easier to build financial features on Bitcoin while leveraging its security and network effects. It is developing a new system of Bitcoin-based smart contracts that utilize Bitcoin's security and infrastructure along with ICP’s ease of smart contract development, combining the strengths of both platforms. Rainbow addresses some limitations of current inter-chain solutions and opens up possibilities for new types of on-chain innovations. This movement aims to use Bitcoin as an infrastructure layer for more decentralized applications and services. Despite Bitcoin’s lack of smart contract capabilities, which limits its ability to extend functionality, Rainbow seeks to overcome these limitations by enabling Bitcoin to support decentralized applications.</p>
<p>A few new developments, including Ordinals, Runes, and other Bitcoin extender projects, have started to challenge the Bitcoin community’s monolithic stance and inspired a new generation of builders interested in Bitcoin-based DeFi and other decentralized services. One way to scale Bitcoin-based development is by leveraging other decentralized computing systems and enabling systems to interconnect. The basic system design would be to connect Bitcoin’s underlying utility and security with a platform optimized for smart contract development. This is where ICP’s Chain Fusion comes in. Chain Fusion allows for writing smart contracts on ICP and deploying them across other Layer 1 networks, like Bitcoin, through a system of bridges.</p>
<h1 id="heading-tap-protocol">Tap Protocol</h1>
<p>TAP is an advanced multi-asset metaprotocol for Bitcoin Ordinals, enabling more complex financial operations directly on the Bitcoin blockchain, while being powered by and benefiting from the Ordinals ecosystem. It’s designed to be more flexible and user-friendly than other token metaprotocols, offering features like token staking, swapping, and liquidity pools, all without the need for secondary layers or complex mechanisms. TAP Protocol aims to create decentralized bridge security while ensuring that building on Bitcoin via ICP’s Chain Fusion is both safe and easy.</p>
<h1 id="heading-bitfinity">Bitfinity</h1>
<p>Blockchain developers often face a tough decision early in their careers: choosing between Bitcoin and Ethereum as their Layer 1 of choice. This choice, like picking between Coke and Pepsi, comes with clear trade-offs. However, what if developers didn’t have to choose? What if they could build across multiple Layer 1 stacks and select the best chain for each task?</p>
<p>Bitfinity offers a solution to this challenge. It is an Ethereum Virtual Machine (EVM) designed to run on top of Bitcoin, with ICP’s Chain Fusion serving as the critical bridge between the two chains. Bitfinity enables Ethereum-like smart contract functionality on Bitcoin, allowing developers to write and deploy contracts on Bitcoin while leveraging its infrastructure.</p>
<h1 id="heading-the-runes-protocol">The Runes Protocol</h1>
<p>The Runes Protocol is a fungible token protocol built on top of Bitcoin, featuring a fair minting issuance method that is more accessible to the public. The protocol extends Bitcoin’s UTXO model into a model where UTXOs can hold balances of arbitrary fungible tokens (called Runes) alongside their satoshis. Its core advantage lies in its construction based on Bitcoin’s UTXO, which makes transaction steps simpler, indexing more efficient, and scalability better. Runes are completely unrelated to Ordinals, Inscriptions, and BRC-20 tokens, and are directly competitive with BRC-20s. Runes are much more efficient at using blockspace compared to BRC-20s (and contribute less to state bloat). They are also likely to be more compatible with Bitcoin protocols (wallets, bridges, and scalability solutions), as they simply exist on UTXOs (like Bitcoin). In contrast, BRC-20s usually required Ordinal-supported infrastructure in order to interoperate.</p>
<p>The Runes Protocol launched during the 2024 Bitcoin Halving and was highly anticipated, with extensive marketing that included Pre-Rune airdrops from various Ordinals projects, generating significant discussions on crypto Twitter. The launch saw strong support from over 20 mainstream Web3 wallets, on-chain trading platforms, and Bitcoin ecosystem tools, such as OKX, ME, Unisats, and Xverse. These platforms enabled the minting, trading, and transferring of Runes assets from day one.</p>
<p>The Runes Protocol quickly gained traction, with market cap exceeding US$2B, making it one of the most active ecosystems of 2024. Since its launch on April 20, Runes have dominated the Bitcoin fungible token market, accounting for over 95% of the market share and representing over 60% of all Bitcoin transactions on average. Runes transactions have generated over 2,500 BTC in fees, approximately US$165M, representing about 30% of all fees on the Bitcoin network since the launch.</p>
<p>The Runes Protocol is advancing towards mutual integration with the "Runes Ecosystem" and BTC Layer 2 and other high-speed smart contract execution chains, addressing Bitcoin's limitations such as low performance, high costs, and the lack of smart contracts.</p>
<p>On one side, numerous memecoins issued under the Runes protocol are aiming to enter BTC Layer 2 and other fast smart contract chains to expand meme culture and explore more use cases and collaborations.</p>
<p>On the other side, more Bitcoin ecosystem projects and real-world asset (RWA) projects are opting to issue their utility tokens using the Runes protocol. This allows assets to be issued on Bitcoin and then cross-chained to BTC Layer 2 or other smart contract chains for distribution, trading, and application.</p>
<p>The Rune $SATOSHI•RUNE•TITAN, built on Bitlayer, functions as the platform token for the LayerX GameFi platform. With 7.1% of its Runes cross-chained to Bitlayer for community incentives and governance, it consistently ranks among the Top 15 by market cap.</p>
<p>Leading the cross-chain field for Runes is the Omnity Interoperability Protocol, which has seen cross-chain asset volumes exceed $1M. Omnity connects Bitcoin, ICP, Bitlayer, Merlin, BEVM, Bob, X Layer, and B^2 Network, supporting all Rune assets. It enables self-service Bridge and Runes functionality and operates entirely on-chain using ICP’s Chain Fusion technology, without relying on off-chain components like relayers or indexers. The Omnity protocol offers a fast, simple, and low-cost user experience, making it ideal for Bitcoin network assets. It also provides composable protocol interfaces for Rune etching, minting, transferring, and burning from Layer 2, supporting the integration of Bitcoin L1 and L2.</p>
<p>In conclusion, Runes have gained legitimacy as the standardized fungible token on Bitcoin’s settlement layer and are widely recognized within the modular architecture of the crypto world.</p>
<p>All ecosystems embrace Runes assets, and with the ongoing development of cross-chain infrastructure and Layer 2 applications, the cross-chain flow and application of Runes assets across the crypto ecosystem is inevitable. The activity and influence of the Runes ecosystem will continue to grow, potentially positioning it as the most important and widely adopted fungible token standard in the crypto world.</p>
<h1 id="heading-omnity">Omnity</h1>
<p>Omnity is a cross-chain protocol built on ICP, designed to integrate into the modular blockchain landscape. It is the first fully decentralized protocol in the cross-chain domain, prioritizing optimal user experience. Omnity addresses challenges like security vulnerabilities, high costs, latency, and liquidity fragmentation by leveraging ICP’s unique features, such as Chain Key and HTTPS Outcalls. The protocol offers a more cost-efficient, secure, and ubiquitous cross-chain service compared to existing solutions.</p>
<p>The future of Bitcoin Mining</p>
<p>“Information asymmetry begets stability, while transparency begets volatility.” This adage highlights the contrast between traditional stock markets or commodities like gold and Bitcoin. In traditional markets, much of the activity happens behind closed doors, with insider trading and secret deals being common. Even though regulations mandate transparency, regular investors often receive crucial information after insiders, which delays market reactions. This creates relative stability in stock prices and commodities, as the market doesn't react instantly to every bit of news.</p>
<p>Bitcoin operates under different principles due to its transparency, where everything is on-chain and verifiable by anyone. This transparency is evident in several areas:</p>
<ul>
<li><p><strong>Wallet Activity</strong>: All wallet balances are visible, allowing people to monitor large BTC transfers, especially when whales move significant amounts to exchanges, often signaling potential sell-offs. This can lead to immediate market reactions, as seen in a recent German Bitcoin sell-off, which impacted the market price before bouncing back.</p>
</li>
<li><p><strong>Network Metrics</strong>: Key network metrics like the total terahash rate, network difficulty, and miners' payouts are public knowledge. The coinbase reward algorithm, which halves rewards every four years, is also known to all.</p>
</li>
<li><p><strong>Transaction Costs</strong>: The mempool, where pending transactions wait for confirmation, is public, giving everyone visibility into the current transaction costs.</p>
</li>
</ul>
<p>Bitcoin's transparency makes it more volatile, despite its large market cap. Unlike stocks and commodities, where information can be controlled, Bitcoin’s openness causes significant activity to quickly impact the market.</p>
<h1 id="heading-bitcoin-mining">Bitcoin Mining</h1>
<p>In the transparent Bitcoin ecosystem, miners have minimal information asymmetry since all data is public. Mining is a challenging task as miners require cheap energy, and while their costs are in dollars, their rewards are in Bitcoin, influenced by price action and mining difficulty.</p>
<h4 id="heading-cost-factors">Cost Factors:</h4>
<ul>
<li><p><strong>Energy Price</strong>: Varies based on location and energy sources.</p>
</li>
<li><p><strong>Hardware Price</strong>: Influenced by access to manufacturers, economies of scale, and technological advancements. As computing power doubles every two years (Moore’s Law), miners must continually upgrade their hardware to stay competitive.</p>
</li>
</ul>
<h4 id="heading-revenue-factors">Revenue Factors:</h4>
<ul>
<li><p><strong>Price Action</strong>: Driven by Bitcoin's market cap, which is influenced by trading activity against fiat currencies.</p>
</li>
<li><p><strong>Mining Reward</strong>: Includes the Coinbase reward (set by the Bitcoin algorithm) and transaction fees (dependent on network traffic).</p>
</li>
</ul>
<p>Miners must be financially savvy, often utilizing derivative instruments like futures to manage these challenges.</p>
<p>One exotic instrument used by miners is the <strong>forward hashrate contract</strong> offered by Loka Mining. It’s similar to how corn farmers sell their future harvests. Bitcoin miners can sell their future hashrate in exchange for a cash advance, allowing them to purchase more mining machines. At the same time, this strategy helps them hedge against price volatility risks by locking in the price of their hashrates upfront.</p>
<p>Here’s how the forward hashrate contract works:</p>
<ol>
<li><p><strong>Bob's Situation</strong>: Bob is a Bitcoin miner looking to expand his operation by buying more mining machines. Instead of selling his Bitcoin to fund the expansion, Bob lists a percentage of his future hashrate for sale on the Loka protocol.</p>
</li>
<li><p><strong>Hashrate Listing</strong>: Bob’s hashrate is projected to generate 1 BTC over the next year based on the hashprice trajectory. To get funds immediately, he lists his future hashrate for 0.9 BTC (offering a 10% discount on the projected 1 BTC).</p>
</li>
<li><p><strong>Collateral</strong>: Since Loka is a permissionless protocol, Bob must also put up 0.9 BTC as collateral to guarantee that he will deliver the promised hashrate.</p>
</li>
<li><p><strong>Alice's Investment</strong>: Alice, an investor who buys Bitcoin every month and prefers not to worry about short-term price fluctuations, purchases Bob’s forward hashrate contract. At the time of the contract, Bitcoin’s price is $60K, so Alice pays Bob 0.9 BTC (equivalent to $54K).</p>
</li>
<li><p><strong>Upfront Payment</strong>: In this transaction, Bob receives money upfront and can immediately use it for his expansion. Alice, however, will eventually receive 1 BTC when the contract matures, paying only 0.9 BTC.</p>
</li>
<li><p><strong>Contract Execution</strong>: The protocol releases a fraction of Bob’s collateral to Alice every 24 hours as Bob delivers the agreed-upon hashrate. If Bob’s mining machine goes offline, the protocol slashes his collateral for the period of downtime, and the slashed amount is given to Alice.</p>
</li>
</ol>
<p>This system ensures fairness and security for both parties, offering Bob immediate funds for expansion while Alice gets a discount on Bitcoin in the future.</p>
<h1 id="heading-loka">Loka</h1>
<p>Loka is a platform connecting Bitcoin miners and individual investors through a trustless, non-custodial approach. It allows:</p>
<ol>
<li><p><strong>Retail Investors</strong>: To acquire Bitcoin at a lower price than the market by purchasing future hashrate contracts, providing liquidity to Bitcoin miners. Investors gain access to cheap energy opportunities without exposure to centralized party risk.</p>
</li>
<li><p><strong>Bitcoin Miners</strong>: To gain early returns on investment by selling future hashrates, allowing them to scale their operations by purchasing more hardware. This also helps them hedge against price volatility exposure.</p>
</li>
</ol>
<p>Loka’s two-sided marketplace, powered by a P2P trustless protocol, ensures a safe and decentralized environment for both parties.</p>
<p>The Future of ChainFusion powered DeFi</p>
<p>Over recent years, Bitcoin's utility has significantly evolved beyond being just a store of value. With innovations such as ordinals and the expansion of decentralized finance (DeFi) capabilities, the Bitcoin economy is continuously growing. Bitcoin-native DeFi offers a sustainable ecosystem for Bitcoin's expanding use cases, and <strong>Chain Fusion</strong> technology, powered by <strong>ICP</strong>, is instrumental in driving this evolution by providing the necessary tech stack and tools for <strong>BTCfi</strong> applications.</p>
<h3 id="heading-key-developments">Key Developments:</h3>
<p><strong>Chain Fusion's Role</strong>: By offering a unified Web3 experience with protocol-level Bitcoin integration, Chain Fusion allows <strong>Bitcoin (BTC)</strong> to activate traditional DeFi functionalities like staking, restaking, lending, borrowing, and yield generation—activities typically associated with programmable blockchains like <strong>Ethereum</strong> and <strong>Solana</strong>.</p>
<p><strong>Bitomni</strong>: A leading BTCFi innovation, Bitomni integrates Bitcoin with omnichain capabilities. Through products like <strong>BitoBridge</strong>, <strong>BitoRestaking</strong>, and <strong>BitoIndexer</strong>, it enables Bitcoin to participate in DeFi activities across multiple blockchain ecosystems. The integration of <strong>ICP’s Chain Fusion</strong> and <strong>Bitcoin Integration</strong> ensures seamless interoperability and interaction with the Bitcoin blockchain, positioning Bitomni as a competitive force in the BTCFi market.</p>
<p><strong>ChainkeyX</strong>: This project aims to create a <strong>Bitcoin Neobank</strong>, replicating modern banking on-chain using Bitcoin. It offers a fully on-chain Bitcoin borrowing and lending platform without requiring stablecoins. The platform uses <strong>Chain Fusion</strong> technology, integrating <strong>ckBTC</strong> and <strong>ckETH</strong> to facilitate borrowing and lending on-chain. Additionally, <strong>ICP’s reverse gas model</strong> allows users to interact with the platform without needing ICP tokens or wallets.</p>
<h1 id="heading-chainkeyx">ChainkeyX</h1>
<p><strong>ChainkeyX</strong> aims to merge the best aspects of traditional banking with decentralized finance (DeFi) through its <strong>on-chain neobank</strong> suite. Traditional banks provide essential financial services such as fixed deposits, collateralized loans, and asset swapping, but <strong>ChainkeyX</strong> allows these functions to operate on-chain, bringing speed and efficiency to financial activities.</p>
<p>By utilizing <strong>ICP’s Chain Fusion</strong>, <strong>ChainkeyX</strong> enables users to create <strong>noncustodial wallets</strong>, providing access to liquidity pools on both <strong>Bitcoin</strong> and <strong>Ethereum</strong>. This integration offers a bank-like experience while maintaining the decentralized nature of DeFi.</p>
<p>A key challenge in the digital asset world, much like in the days of physical coinage, is managing and securing wallets. As more individuals take control of their finances through noncustodial wallets, issues around wallet security and management become increasingly important. In this context, <strong>ChainkeyX</strong> aims to enhance digital asset storage and management, bridging the gap between traditional and decentralized finance.</p>
<h1 id="heading-nfid-vaults">NFID Vaults</h1>
<p><strong>Where did I put my wallet?</strong><br />This timeless question reflects a persistent issue, even as we move from physical coins to digital assets. As people take control of their finances through <strong>noncustodial wallets</strong>, managing and securing these wallets becomes increasingly complex, especially with digital assets where there is no support line to call. The challenge is to create better systems for digital asset storage and management.</p>
<p><strong>NFID Vaults</strong> addresses this problem by providing a <strong>crypto smart wallet</strong> that is interoperable across multiple chains and assets. It enables <strong>permissionless wallet recovery</strong> through <strong>multifactor signatures</strong> for added security. This solution is made possible by <strong>ICP’s Chain Fusion</strong>, which allows users to securely access multiple chains from various devices. The <strong>NFID Vault</strong> ensures top-tier wallet security while integrating with <strong>Bitcoin</strong> and <strong>Ethereum</strong> liquidity pools, offering the benefits of both traditional finance and decentralized finance in one platform.</p>
<h1 id="heading-bitomni">Bitomni</h1>
<p><strong>Bitomni</strong> is pioneering <strong>Bitcoin-based DeFi</strong> across multiple chains. It provides various decentralized financial services, including <strong>staking</strong>, <strong>lending &amp; borrowing</strong>, <strong>indexing</strong>, and <strong>token management</strong>, thanks to its <strong>multi-chain approach</strong>.</p>
<p>Key products of Bitomni include:</p>
<ul>
<li><p><strong>BitoBridge</strong></p>
</li>
<li><p><strong>BitoRestaking</strong></p>
</li>
<li><p><strong>BitoIndexer</strong></p>
</li>
<li><p><strong>BitoBank</strong></p>
</li>
<li><p><strong>BitoFund</strong></p>
</li>
</ul>
<p>Bitomni enables the addition of smart contract-based financial functionality on top of <strong>Bitcoin</strong>, while also ensuring <strong>programmability</strong>, <strong>composability</strong>, and <strong>security</strong>. The project leverages <strong>ICP’s Chain Fusion</strong> to make this possible, enabling <strong>Bitcoin</strong> and compatibility with <strong>EVM-compatible blockchains</strong> like <strong>Aptos</strong>, <strong>Solana</strong>, and <strong>Polkadot</strong>.</p>
<p>Bitomni is governed by its <strong>DAO</strong> and operates using the <strong>BITO utility token</strong>.</p>
<h1 id="heading-b3wallet">B3Wallet</h1>
<p>To enable true decentralization, we need to rethink how we manage identity in the digital world. What if our <strong>digital asset wallet identity</strong> was tied to our <strong>Internet Identity</strong> rather than our traditional physical or social identity? This shift could have significant implications for <strong>privacy</strong> and <strong>personal security</strong>, but it also raises potential risks like <strong>fraud</strong> and <strong>scams</strong> if not properly managed.</p>
<p>This is where <strong>B3Wallet</strong> comes in. B3Wallet provides a <strong>fully decentralized platform</strong> for storing assets across multiple chains and sources. The wallet can be configured in various ways, allowing for <strong>multiple owners</strong>, <strong>single owners</strong>, and <strong>multiple signatures</strong>. Users can set up their wallets without the need for registration and can recover them without dealing with traditionally complex backup processes.</p>
<p>Thanks to <strong>ICP’s Chain Fusion</strong>, the process is made seamless—users only need an <strong>ICP Internet Identity</strong> to get started, enabling an efficient and secure way to manage assets across multiple blockchain networks.</p>
<h1 id="heading-oisy">OISY</h1>
<p><strong>OISY Wallet</strong> offers a comprehensive solution for managing digital assets like <strong>BTC</strong>, <strong>ETH</strong>, and <strong>ICP</strong> within a single interface, eliminating the need to switch between multiple wallets for different cryptocurrencies. This streamlines the user experience, enabling users to manage diverse assets across blockchain networks with ease and efficiency.</p>
<p>Built on <strong>ICP</strong>, OISY utilizes <strong>network custody</strong> through advanced cryptographic methods, removing the need for users to directly manage private keys. This enhances security by distributing control across the network and mitigating risks associated with traditional key management.</p>
<p>The wallet itself is fully <strong>on-chain</strong> and operates without relying on external servers, offering <strong>tamper-proof security</strong> to protect user data and assets from unauthorized access. Additionally, by leveraging <strong>Internet Identity</strong>, users can link multiple devices and enjoy a seamless experience across mobile, tablet, and desktop, all without compromising security.</p>
<h1 id="heading-orbit">Orbit</h1>
<p><strong>Orbit</strong> aims to simplify blockchain technology, making it as easy to use as traditional <strong>web2</strong> alternatives. The project’s goal is to lower the barrier to entry for developers to integrate programmable functionality into on-chain apps and services, even if they only have <strong>web2</strong> development skills and tools.</p>
<p>Orbit’s first project is the <strong>Orbit Wallet</strong>, which uses <strong>ICP’s Chain Fusion</strong> to enable easy communication across various <strong>Layer 1</strong> chains and control of multiple assets. The wallet is programmable and can be customized for a wide range of use cases, from hobbyists collecting multiple assets to enterprise-level power users, with tailored setups and permissions.</p>
<p>The <strong>Orbit Wallet</strong> serves as the first proof-of-concept, showcasing how Orbit operates modularly. It relies on several ICP components like <strong>canisters</strong>, <strong>stations</strong>, and <strong>control panels</strong> to ensure extensibility and flexibility.</p>
<h1 id="heading-plug-wallet">Plug Wallet</h1>
<p><strong>Plug</strong> is a <strong>browser</strong> and <strong>mobile crypto wallet</strong> designed for the <strong>Internet Computer</strong>, also serving as an <strong>identity</strong> and <strong>authentication provider</strong>. It features native <strong>ETH</strong> and <strong>ERC-20</strong> token storage, aiming to provide users with the smoothest possible experience when interacting with <strong>Chain Fusion</strong>.</p>
<h1 id="heading-defi-vectors">DeFi Vectors</h1>
<p><strong>DeFi Vectors</strong> is a project leveraging the <strong>Internet Computer Protocol (ICP)</strong> to simplify the development of decentralized finance (DeFi) applications. It aims to be the <strong>Zapier of DeFi</strong>, allowing developers to mix and match pre-made components to quickly and securely create new financial products. By setting standards and building modular components, DeFi Vectors reduces development overhead, enabling anyone to build interoperable DeFi services. The project takes advantage of ICP’s <strong>Chain Fusion technology</strong> to enhance access and ease of use for DeFi services.</p>
<h1 id="heading-helix-markets">Helix Markets</h1>
<p><strong>Helix Markets</strong> is a decentralized exchange (DEX) focused on seamless and affordable cross-chain trading. Unlike other DEXs, Helix is user-centric and built on decentralization principles, allowing users to retain control of their assets throughout transactions. It does not rely on vulnerable bridges, liquidity pools, or aggregators, commonly seen in other DEX environments. The functionality of Helix Markets is powered by <strong>ICP’s Chain Fusion</strong>, enabling integration with Bitcoin, Ethereum, and other Ethereum Virtual Machine-compliant chains. One of its major achievements is developing an API capable of processing up to <strong>100,000 transactions per second</strong>, making scalable trading operations across exchanges and chains feasible at unprecedented speeds.</p>
<h1 id="heading-icp-swap">ICP Swap</h1>
<p><strong>ICP Swap</strong> is a decentralized finance (DeFi) platform offering a full suite of services, including token issuing, market-making, and plug-and-play decentralized autonomous organizations (DAOs). It simplifies the development of DeFi services by consolidating key functions like minting tokens, creating liquidity pools, and performing asset swaps. This reduces the technical barriers and costs for DeFi teams with innovative ideas, allowing easier market entry. Built using <strong>ICP’s Chain Fusion</strong>, ICP Swap enables cross-chain operations, optimizing transaction and development costs. The <strong>ICPSwap Token (ICS)</strong> serves as a governance and ecosystem token with a deflationary model, where the 1 billion tokens will be repurchased and burned over time.</p>
<h1 id="heading-icdex">ICDex</h1>
<p><strong>ICDex</strong> is a decentralized exchange (DEX) that features an order book-style trading system built on ICP, utilizing <strong>Chain Fusion</strong> for cross-chain functionality across multiple Layer 1 blockchains. It operates entirely on-chain and is governed by smart contracts. Unlike traditional decentralized order books, ICDex offers full trading functionality, including limit and market orders, along with more advanced formats like grid orders and iceberg orders. Additionally, it supports Orderbook Automated Market Making (AMM), allowing anyone to participate in market-making by adding liquidity.</p>
<p>ICDex is part of a broader suite of decentralized services provided by <strong>ICLighthouse</strong>, a Singapore-based company. Other offerings from ICLighthouse include <strong>IC Router</strong> (a cross-chain network), <strong>ICHouse</strong> (an Internet Computer blockchain explorer), and <strong>CyclesFinance</strong> (a decentralized marketplace for ICP and Cycles).</p>
<h1 id="heading-kongswap">KongSwap</h1>
<p><strong>KongSwap</strong> is building a <strong>SuperDEX</strong>, a decentralized exchange designed to allow users to trade native Bitcoin, Ethereum, and Solana with minimal transaction or gas fees. Unlike other DEXs that rely on multiple layers and workarounds, KongSwap leverages <strong>ICP’s Chain Fusion</strong> for built-in efficiency, scalability, and cross-chain interoperability. The platform runs on a single canister, governed by a smart contract, which simplifies the DeFi operations like initiating trades, adjusting liquidity, staking pools, and tracking transaction history.</p>
<p>This streamlined approach reduces the need for multiple smart contracts, making transactions more efficient and synchronized. Security is ensured through the use of <strong>Threshold ECDSA</strong> and <strong>Schnorr signatures</strong> for managing access and interoperability.</p>
<h1 id="heading-sonic">Sonic</h1>
<p><strong>Sonic</strong> is a <strong>DeFi hub</strong> that leverages the scalability and low transaction costs enabled by <strong>Internet Computer's Chain Fusion</strong> model. It allows users to create and issue their own tokens, trade tokens across chains, and earn rewards by providing liquidity. One of the key features of Sonic is its ability to enable token swaps in a <strong>completely decentralized and permissionless environment</strong>, meaning users can easily convert one asset to another on-chain.</p>
<p>To ensure sufficient liquidity for these swaps, Sonic encourages users to deposit tokens into liquidity pools by offering rewards in the form of shares of the fees generated from the pools. This system essentially turns Sonic into a <strong>DeFi-enabled revenue generator</strong> for liquidity providers.</p>
<h1 id="heading-msq">MSQ</h1>
<p><strong>MSQ</strong> is a <strong>Metamask extension</strong> that enables users to connect their <strong>Metamask wallet</strong> to the <strong>Internet Computer</strong> (ICP). <strong>Metamask</strong> is a widely used web3 wallet supporting a range of on-chain activities, from <strong>DeFi</strong> to decentralized social media. With <strong>MSQ</strong>, users can securely access decentralized applications (dApps) and transact in ICP-based assets like <strong>ICP</strong>, <strong>ckBTC</strong>, <strong>ckETH</strong>, and more.</p>
<p>The two core components driving <strong>MSQ’s</strong> mission are:</p>
<ol>
<li><p>A <strong>simple wallet interface</strong> that streamlines interaction with dApps.</p>
</li>
<li><p><strong>Built-in privacy features</strong> that protect sensitive data, including transaction and wallet connection history.</p>
</li>
</ol>
<h1 id="heading-dfinance">DFinance</h1>
<p><strong>DFinance</strong> is an advanced platform aimed at transforming the <strong>DeFi</strong> sector with a <strong>secure</strong> and <strong>user-centric lending and borrowing ecosystem</strong>. Built on the <strong>Internet Computer (ICP)</strong> blockchain, it ensures <strong>unmatched data security</strong> and <strong>decentralization</strong>. The platform’s mission is to offer a <strong>transparent and democratic</strong> financial environment, where users have the power to influence its future.</p>
<p>The primary goals of <strong>DFinance</strong> are:</p>
<ul>
<li><p>To establish a <strong>decentralized financial hub</strong> for lending, borrowing, staking tokens for governance, and participating in the platform’s development through proposals and voting.</p>
</li>
<li><p>To enhance the DeFi experience with <strong>dynamic interest rate strategies</strong>, a reliable price feed, and a variety of token options, including <strong>ckBTC</strong> and <strong>ckETH</strong>.</p>
</li>
<li><p>To drive innovation and inclusivity, positioning itself as a foundational element in the <strong>DeFi</strong> space, focused on <strong>user governance</strong> and <strong>transparency</strong>.</p>
</li>
</ul>
<h1 id="heading-bridging-off-chain-and-on-chain">Bridging Off-chain and On-chain</h1>
<p>Traditionally, <strong>oracle providers</strong> bridge the gap between <strong>off-chain</strong> and <strong>on-chain</strong> data, deciding which data is updated and under what conditions. However, <strong>Internet Computer (ICP)</strong> is revolutionizing this by enabling users and developers to break free from these limitations.</p>
<p>Unlike blockchains like <strong>Ethereum</strong> and <strong>Solana</strong>, which operate in isolated environments, <strong>ICP</strong> allows direct communication between on-chain applications and the external world. This solves the issue of the limited scope of data handled by traditional blockchains, even with oracle services.</p>
<p>ICP's <strong>HTTPS outcalls</strong> enable the indexing of virtually any information as on-chain data, significantly expanding the potential for decentralized applications. Security is maintained through a robust verification mechanism, which ensures data integrity by calling the same endpoint multiple times to reach consensus.</p>
<p>This approach positions <strong>ICP</strong> as a potential universal on-chain data hub, enabling more comprehensive and data-rich decentralized applications.</p>
<p>This advancement ushers in a new era for DeFi, enabling protocols to integrate complex, data-driven logic such as predictive analytics and automated asset filtering. Unlike traditional blockchains, which are limited to current state references, ICP’s synchronization capabilities create a dynamic, data-rich environment, setting the stage for next-generation DeFi applications.</p>
<p>For example, an Arbitrum-based protocol could use ICP-synchronized data to adjust collateral rates or implement advanced risk models. Powered by Chainkey, this cross-chain data flow isn’t just bridging ecosystems but fostering smarter, more efficient DeFi applications.</p>
<p>As this technology matures, it will spark a wave of financial innovation that transcends the limitations of isolated blockchains, leading to truly interconnected, data-empowered decentralized finance.</p>
<h1 id="heading-open-ratings-revolutionizing-asset-evaluation-in-the-blockchain-era"><strong>Open Ratings: Revolutionizing Asset Evaluation in the Blockchain Era</strong></h1>
<p>As blockchain technology grows, ratings systems are becoming essential in the crypto ecosystem. These systems simplify complex data into single metric comparisons, a necessity as on-chain data increases in volume and complexity. Blockchain’s public nature allows for automatic, real-time updates to ratings.</p>
<p>Unlike traditional finance, crypto enables individual builders to privately create and publish ratings, which fosters a more diverse and potentially more accurate evaluation ecosystem. The blockchain synergizes vast data, ratings, and the reputation of the builders, increasing transparency, promoting innovation, and building trust.</p>
<p>While crucial for DeFi, the impact of ratings extends to governance, digital assets, sustainability, and security. As the blockchain space matures, these decentralized rating systems will become vital, strengthening the credibility of the crypto industry.</p>
<h1 id="heading-data-lego-building-blocks-of-the-future"><strong>Data LEGO: Building Blocks of the Future</strong></h1>
<p>ICP could introduce a revolutionary concept of modular data management, similar to the "Money LEGO" principle in DeFi. This system would involve a network of specialized canisters, each with specific roles:</p>
<ol>
<li><p><strong>Data Collection:</strong> Canisters that collect and store specific data, like historical token prices.</p>
</li>
<li><p><strong>Data Processing:</strong> Canisters that compute complex metrics, such as volatility indices, based on data from other canisters.</p>
</li>
<li><p><strong>Flexibility:</strong> New canisters can be deployed to alter data processing without impacting data collection canisters.</p>
</li>
</ol>
<p>This modular approach, combined with HTTPS outcalls to index diverse data sources and the use of robust languages like Rust for canister logic, has the potential to create a powerful network effect of shared knowledge on the ICP. The "Money LEGO" concept from DeFi can similarly be applied to data.</p>
<h1 id="heading-cross-chain-data-relay-catalyzing-defi-evolution"><strong>Cross-Chain Data Relay: Catalyzing DeFi Evolution</strong></h1>
<p>ICP’s Chainkey technology is set to transform cross-chain data usage, especially in DeFi. This innovation enables bridge-free integration, allowing direct data transmission from ICP to any desired chain. It empowers smart contracts on external networks to utilize ICP’s advanced data and computations while facilitating seamless synchronization of modular “Lego block” data across various blockchain ecosystems.</p>
<h1 id="heading-chainsight-on-chain-data-hub"><strong>Chainsight: On-Chain Data Hub</strong></h1>
<p>Chainsight is an advanced on-chain data hub that aggregates data from various markets and makes it accessible on-chain. It allows data retrieval from smart contracts, including information from HTTPS endpoints on the web and data computed from other chains. Chainsight operates as a network of numerous indexers, each maintaining its own data. These indexers can combine their data efficiently to generate new information, which is then written directly to blockchains like Ethereum, removing the need for off-chain bridges. This setup enables on-chain applications to leverage the required data.</p>
<h1 id="heading-cloaking-layer-zero-knowledge-verification-for-all-blockchains"><strong>Cloaking Layer: Zero-Knowledge Verification for All Blockchains</strong></h1>
<p>Cloaking Layer is developing a way to integrate zero-knowledge (ZK) verification across all blockchains. ZK proofs will significantly impact the scalability of major blockchain applications by making computation faster and cheaper, thus increasing data availability for on-chain functions. ZK also enhances privacy for users and overall security for layer-2s and other blockchain apps and services. It helps reduce computation costs for on-chain transactions by alleviating the computing burden. Cloaking Layer leverages IC’s Chain Fusion and ECDSA/EdDSA signatures to offer ZK-as-a-Service across blockchains, operating in a fully trustless manner.</p>
<h1 id="heading-blockchains-on-blockchain-an-introduction">Blockchains on Blockchain: an Introduction</h1>
<p><strong>"Blockchains on Blockchain" and ICP's Explosion in Network Fees</strong></p>
<p>The concept of "blockchains on blockchain" has emerged as a groundbreaking use case, particularly after the launch of BOB in September. BOB utilizes ICP's powerful compute capabilities to host a memecoin on-chain, using a proof-of-work mechanism similar to Bitcoin. This model offers several advantages, such as verifiable fairness in token distribution and the prevention of miner advantages through hardware superiority.</p>
<p>BOB's success spurred further development in the "blockchains on blockchain" category, driving a significant increase in computation on the Internet Computer. This surge led to a dramatic rise in network fees, also known as cycles burned, with a 90% increase in cycle burn rate from January to August 2024. However, the launch of BOB alone resulted in a staggering 3000% increase in cycle burn between August and September, burning more ICP in 35 days than in the previous three years combined. This growth shows no sign of slowing, as more entrepreneurs continue to explore novel "blockchains on blockchain" applications.</p>
<h1 id="heading-bob-proof-of-work-for-layer-2-scaling"><strong>#BOB: Proof-of-Work for Layer 2 Scaling</strong></h1>
<p>BOB (Blockchain on Blockchain) is a purpose-built system that introduces proof-of-work-style consensus to Layer 2 solutions. According to its website, BOB merges "Bitcoin’s consensus with Doge’s utility," creating a novel approach to blockchain interoperability and scaling.</p>
<p>While its applications may not be immediately clear, BOB’s ability to bring new consensus mechanisms to Layer 2 networks represents a significant innovation. This is made possible by leveraging ICP as the primary mining mechanism—miners either use ICP to buy mining cycles or adjust their mining speed, directly impacting the amount of ICP consumed.</p>
<h1 id="heading-msqburn-a-fair-and-efficient-memecoin-miner"><strong>MSQ.Burn: A Fair and Efficient Memecoin Miner</strong></h1>
<p>MSQ.Burn, developed by the creators of the MSQ Metamask wallet extension, is a memecoin miner designed to ensure fairness in memecoin operations. All members of the BURN pool receive proportional rewards whenever a block is minted.</p>
<p>BURN follows a simple tokenomics model—block rewards halve every 5,040 blocks (approximately once per week) until they reach 1 BURN per block. At that point, block times will gradually increase until they reach 12 hours per block, introducing controlled inflationary forces.</p>
<p>The project also emphasizes efficiency, aiming to minimize mining waste and reduce unnecessary compute cycle burns.</p>
]]></content:encoded></item><item><title><![CDATA[Step by step tutorial on zksapp development]]></title><description><![CDATA[Developers building zkApps in the Mina ecosystem can utilize two different frameworks, each designed to optimize different types of solutions. Explore the…]]></description><link>https://nwa-eddy84.hashnode.dev/step-by-step-tutorial-on-zksapp-development</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/step-by-step-tutorial-on-zksapp-development</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Sun, 02 Feb 2025 11:03:35 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-zkapp-development-frameworks">zkApp Development Frameworks</h1>
<p>Developers building zkApps in the Mina ecosystem can utilize two different frameworks, each designed to optimize different types of solutions. Explore the options below to find the best fit for your project.</p>
<h1 id="heading-o1js">o1js</h1>
<p>o1js is the framework for building zkApps on the Mina L1 and new infrastructure like rollups. It is TypeScript-based for ease of use, comes with built-in features, is highly extensible, and takes full advantage of Mina's unique protocol characteristics.</p>
<p>o1js is also the zkDSL used for:</p>
<ul>
<li><p>Writing general-purpose zk circuits.</p>
</li>
<li><p>Constructing new primitives and data structures.</p>
</li>
</ul>
<h4 id="heading-considerations-for-building-zkapps-with-o1js-on-mina-l1">Considerations for Building zkApps with o1js on Mina L1:</h4>
<ul>
<li><p>zkApps are subject to protocol throughput limitations.</p>
</li>
<li><p>zkApps requiring support for multiple concurrent users must be designed to avoid race conditions:</p>
<ul>
<li><p>If more than eight on-chain field elements are needed to manage state without shared access, the <strong>Offchain Storage API</strong> provides a solution.</p>
</li>
<li><p>If concurrent access to shared global state is necessary, <strong>Protokit</strong> allows building zkApp-chains (L2) with built-in support. Currently, there is no equivalent easy-to-use solution for shared state in o1js L1 contracts.</p>
</li>
</ul>
</li>
</ul>
<p><strong>o1js</strong> is a <strong>TypeScript library</strong> designed for:</p>
<ul>
<li><p>Writing <strong>general-purpose zero-knowledge (zk) programs</strong>.</p>
</li>
<li><p>Writing <strong>zk smart contracts</strong> for <strong>Mina</strong>.</p>
</li>
</ul>
<h4 id="heading-example-code">Example Code</h4>
<pre><code class="lang-plaintext">typescript
</code></pre>
<pre><code class="lang-plaintext">CopyEdit
</code></pre>
<pre><code class="lang-plaintext">import { Field, Poseidon } from 'o1js';
</code></pre>
<pre><code class="lang-plaintext">function knowsPreimage(preimage: Field) {
</code></pre>
<pre><code class="lang-plaintext">  let hash = Poseidon.hash([preimage]);
</code></pre>
<pre><code class="lang-plaintext">  hash.assertEquals(expectedHash);
</code></pre>
<pre><code class="lang-plaintext">}
</code></pre>
<pre><code class="lang-plaintext">const expectedHash =
</code></pre>
<pre><code class="lang-plaintext">  0x1d444102d9e8da6d566467defcc446e8c1c3a3616d059facadbfd674afbc37ecn;
</code></pre>
<p>This example demonstrates <strong>zero-knowledge proof</strong> (ZKP) capabilities, proving knowledge of a secret value without revealing it.</p>
<h1 id="heading-key-features-of-o1js">Key Features of o1js</h1>
<ul>
<li><p><strong>Provable Methods</strong>: Includes operations like <code>Poseidon.hash()</code> and <code>Field.assertEquals()</code>, enabling zk proofs.</p>
</li>
<li><p><strong>Zero-Knowledge Proofs</strong>: Verification without revealing input values or execution traces.</p>
</li>
<li><p><strong>Rich Built-in Operations</strong>: Arithmetic, hashing, signatures, boolean operations, comparisons, and more.</p>
</li>
<li><p><strong>Client-Side zkApps</strong>: Smart contracts that run privately on users' devices.</p>
</li>
</ul>
<h4 id="heading-getting-started">Getting Started</h4>
<ul>
<li><p><strong>Use zkApp CLI</strong> for setup.</p>
</li>
<li><p>Install via npm:</p>
</li>
</ul>
<pre><code class="lang-plaintext">sh
</code></pre>
<pre><code class="lang-plaintext">CopyEdit
</code></pre>
<pre><code class="lang-plaintext">npm i o1js
</code></pre>
<ul>
<li>Compatible with <strong>major web browsers</strong> and <strong>Node.js</strong>.</li>
</ul>
<h3 id="heading-audits-of-o1js"><strong>Audits of o1js</strong></h3>
<h4 id="heading-veridise-external-audit-q3-2024"><strong>Veridise External Audit (Q3 2024)</strong></h4>
<ul>
<li><p>Security audit conducted by <strong>Veridise</strong>, a leading auditing company.</p>
</li>
<li><p><strong>Duration</strong>: <strong>39 person-weeks</strong> of in-depth review.</p>
</li>
<li><p><strong>Outcome</strong>: All <strong>medium severity and higher</strong> issues were identified and resolved.</p>
</li>
</ul>
<h4 id="heading-internal-audit-q1-2024"><strong>Internal Audit (Q1 2024)</strong></h4>
<ul>
<li><p>Conducted by the <strong>o1js team</strong> in <strong>March 2024</strong>.</p>
</li>
<li><p><strong>Duration</strong>: <strong>Two person-weeks</strong> focused on core provable code.</p>
</li>
<li><p><strong>Outcome</strong>: Several issues were found and fixed.</p>
</li>
</ul>
<h1 id="heading-o1js-basic-concepts"><strong>o1js Basic Concepts</strong></h1>
<p>o1js is a <strong>TypeScript (TS) library</strong> designed for:</p>
<ul>
<li><p>Writing <strong>general-purpose zero knowledge (zk) programs</strong>.</p>
</li>
<li><p>Writing <strong>zk smart contracts</strong> for <strong>Mina</strong>.</p>
</li>
</ul>
<h3 id="heading-field"><strong>Field</strong></h3>
<p>Field elements are the fundamental data unit in <strong>zero knowledge proof programming</strong>. Each <strong>field element</strong> can store a number <strong>up to almost 256 bits</strong> in size, similar to <strong>uint256 in Solidity</strong>.</p>
<h1 id="heading-protokit">Protokit</h1>
<p>Protokit is a powerful framework for building <strong>ZK appchains</strong> and <strong>smart contracts</strong> that are user-facing, privacy-preserving, and interoperable. It provides a developer experience similar to Solidity dApps, making it easier for developers to integrate zero-knowledge proofs into blockchain solutions.</p>
<h4 id="heading-features-and-use-cases">Features and Use Cases:</h4>
<p>Protokit offers a full set of tools for:</p>
<ul>
<li><p>zkApps requiring <strong>high throughput</strong> or <strong>multiple concurrent users</strong>.</p>
</li>
<li><p>zkApps needing <strong>shared or global state access</strong>.</p>
</li>
<li><p>Developers familiar with execution environments like <strong>EVM</strong>.</p>
</li>
<li><p>Those leveraging Protokit's <strong>modular architecture</strong> for enhanced flexibility.</p>
<h4 id="heading-first-a-note-on-permissions"><strong>First: A Note on Permissions</strong></h4>
<p>  Permissions related to ZkApp upgrades are detailed in the <strong>Permissions</strong> article, which covers the security assumptions in more depth. This article focuses on how to perform the upgrade itself.</p>
<h4 id="heading-second-a-note-on-minas-execution-model"><strong>Second: A Note on Mina's Execution Model</strong></h4>
<p>  On other blockchains, upgrading a smart contract may result in users unknowingly running a different program with the same function signature, leading to unsafe or unpredictable outcomes. Mina’s execution model is different.</p>
<p>  On Mina, users run their own program and upload the proof to the blockchain only for verification. Upgrading a ZkApp means <strong>changing the verification key on-chain</strong>. Proofs generated with an older prover function will become invalid, requiring users to download the new prover function to generate valid proofs.</p>
<h3 id="heading-baseline-zkapp"><strong>Baseline ZkApp</strong></h3>
<p>  Here’s an example of a basic <strong>Add</strong> smart contract in Mina:</p>
<pre><code class="lang-plaintext">  typescript
</code></pre>
<pre><code class="lang-plaintext">  CopyEdit
</code></pre>
<pre><code class="lang-plaintext">  import { Field, SmartContract, state, State, method } from 'o1js';
</code></pre>
<pre><code class="lang-plaintext">  export class Add extends SmartContract {
</code></pre>
<pre><code class="lang-plaintext">    @state(Field) num = State&lt;Field&gt;();
</code></pre>
<pre><code class="lang-plaintext">    init() {
</code></pre>
<pre><code class="lang-plaintext">      super.init();
</code></pre>
<pre><code class="lang-plaintext">      this.num.set(Field(1));
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<pre><code class="lang-plaintext">    @method async update() {
</code></pre>
<pre><code class="lang-plaintext">      const currentState = this.num.getAndRequireEquals();
</code></pre>
<pre><code class="lang-plaintext">      const newState = currentState.add(2);
</code></pre>
<pre><code class="lang-plaintext">      this.num.set(newState);
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<pre><code class="lang-plaintext">  }
</code></pre>
<p>  This contract has the <strong>verification key</strong>:<br />  <code>27729068461170601362912907281403262888852363473424470267835507636847418791713</code></p>
<hr />
<h1 id="heading-upgraded-zkapp"><strong>Upgraded ZkApp</strong></h1>
<p>  Here’s the upgraded version of the contract, which adds <strong>4</strong> instead of <strong>2</strong>:</p>
<pre><code class="lang-plaintext">  typescript
</code></pre>
<pre><code class="lang-plaintext">  CopyEdit
</code></pre>
<pre><code class="lang-plaintext">  import { Field, SmartContract, state, State, method } from 'o1js';
</code></pre>
<pre><code class="lang-plaintext">  export class AddV2 extends SmartContract {
</code></pre>
<pre><code class="lang-plaintext">    @state(Field) num = State&lt;Field&gt;();
</code></pre>
<pre><code class="lang-plaintext">    init() {
</code></pre>
<pre><code class="lang-plaintext">      super.init();
</code></pre>
<pre><code class="lang-plaintext">      this.num.set(Field(1));
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<pre><code class="lang-plaintext">    @method async update() {
</code></pre>
<pre><code class="lang-plaintext">      const currentState = this.num.getAndRequireEquals();
</code></pre>
<pre><code class="lang-plaintext">      const newState = currentState.add(4);
</code></pre>
<pre><code class="lang-plaintext">      this.num.set(newState);
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<pre><code class="lang-plaintext">  }
</code></pre>
<p>  This upgraded contract has a new <strong>verification key</strong>:<br />  <code>18150279532259194644722165513074833862035641840431153413486908511595437348455</code></p>
<h3 id="heading-upgrading-a-zkapp"><strong>Upgrading a ZkApp</strong></h3>
<p>  Upgrading a ZkApp by <strong>signature</strong> can be done if you control the private key of the ZkApp. This involves signing a transaction that upgrades the ZkApp with the corresponding private key.</p>
<p>  Let’s assume we have already deployed the <strong>Add</strong> contract and we possess the private key as <strong>zkAppKey</strong>. To upgrade the contract, you would sign the transaction with <strong>zkAppKey</strong> to authorize the change, such as updating the verification key or any other contract parameters.</p>
<h3 id="heading-upgrading-a-zkapp-code-example"><strong>Upgrading a ZkApp (Code Example)</strong></h3>
<p>  To upgrade a ZkApp, you can follow these steps using the following code:</p>
<pre><code class="lang-plaintext">  typescript
</code></pre>
<pre><code class="lang-plaintext">  CopyEdit
</code></pre>
<pre><code class="lang-plaintext">  const verificationKey = (await AddV2.compile()).verificationKey;
</code></pre>
<pre><code class="lang-plaintext">  const contractAddress = zkAppKey.toPublicKey();
</code></pre>
<pre><code class="lang-plaintext">  const upgradeTx = await Mina.transaction({ sender, fee },
</code></pre>
<pre><code class="lang-plaintext">    async () =&gt; {
</code></pre>
<pre><code class="lang-plaintext">      const update = AccountUpdate.createSigned(contractAddress);
</code></pre>
<pre><code class="lang-plaintext">      update.account.verificationKey.set(verificationKey);
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<pre><code class="lang-plaintext">  );
</code></pre>
<pre><code class="lang-plaintext">  await upgradeTx.sign([senderKey, zkAppKey]).prove();
</code></pre>
<pre><code class="lang-plaintext">  await upgradeTx.send();
</code></pre>
<p>  In this example:</p>
<ul>
<li><p>The <strong>verification key</strong> for the upgraded contract (<code>AddV2</code>) is compiled.</p>
</li>
<li><p>The contract address is derived from the public key of the <strong>zkAppKey</strong>.</p>
</li>
<li><p>A transaction is created, which signs the update for the contract's verification key.</p>
</li>
<li><p>After signing with both the <strong>senderKey</strong> and <strong>zkAppKey</strong>, the transaction is proved and sent to the blockchain.</p>
</li>
</ul>
</li>
</ul>
<p>    Once the transaction is applied, the verification key for the ZkApp address will be updated from:<br />    <code>27729068461170601362912907281403262888852363473424470267835507636847418791713</code><br />    to:<br />    <code>18150279532259194644722165513074833862035641840431153413486908511595437348455</code></p>
<h3 id="heading-angular-integration-guide"><strong>Angular Integration Guide</strong></h3>
<h4 id="heading-1-install-a-wallet"><strong>1. Install a Wallet</strong></h4>
<p>    To interact with zkApp transactions, you'll need a wallet that supports them. In this tutorial, we’ll use <strong>Auro Wallet</strong>.</p>
<ol>
<li><p><strong>Download Auro Wallet</strong>: <a target="_blank" href="https://www.aurowallet.com">Download Auro Wallet</a></p>
</li>
<li><p><strong>Add the Auro Wallet Browser Extension</strong>: Install it in your browser.</p>
</li>
<li><p><strong>Create a New Wallet</strong>: Open the extension and follow the prompts to create a new wallet.</p>
</li>
<li><p><strong>Switch to Devnet</strong>:</p>
<ul>
<li><p>Click "Mainnet" at the top of the extension view.</p>
</li>
<li><p>Select "Show Testnet" from the menu, then choose <strong>Devnet</strong>.</p>
</li>
<li><p><strong>Devnet</strong> allows you to interact with a test version of the Mina network, so you won’t need real Mina for transaction fees.</p>
</li>
</ul>
</li>
</ol>
<h4 id="heading-2-fund-your-wallet"><strong>2. Fund Your Wallet</strong></h4>
<ul>
<li><p>Use the <strong>Mina Faucet</strong> to fund your wallet with test Mina.</p>
</li>
<li><p>Wait for one block (~3 minutes) for the balance to reflect on-chain.</p>
</li>
<li><p>Track your transaction status using <strong>Minascan</strong>.</p>
</li>
</ul>
<h3 id="heading-initialize-the-project"><strong>Initialize the Project</strong></h3>
<p>    [if !supportLists]1.      [endif]<strong>Install the Angular CLI globally</strong>:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    npm install -g @angular/cli
</code></pre>
<p>    [if !supportLists]2.      [endif]<strong>Create a new Angular project</strong>:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    ng new &lt;project-name&gt;
</code></pre>
<ol start="2">
<li><ul>
<li><p>Select your preferred stylesheet format (CSS, SCSS, etc.).</p>
<ul>
<li>For <strong>Server-Side Rendering (SSR)</strong> and <strong>Static Site Generation (SSG/Prerendering)</strong>, choose <strong>Yes</strong> if you plan to use these features.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>Install the</strong> <code>o1js</code> <strong>library</strong>:</p>
<ol start="3">
<li><ul>
<li>Navigate to your project directory:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    cd &lt;project-name&gt;
</code></pre>
<ol start="3">
<li><ul>
<li>Install the <code>o1js</code> library:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    npm install o1js
</code></pre>
<p>    [if !supportLists]4.      [endif]<strong>Start the local development server</strong>:</p>
<ol start="4">
<li><ul>
<li>Run the following command to start the server:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    npm run start
</code></pre>
<ol start="4">
<li><ul>
<li>This runs <code>ng serve</code>, and you can further configure it by modifying options in the <code>angular.json</code> file under the <strong>serve</strong> build target.</li>
</ul>
</li>
</ol>
<h1 id="heading-create-the-zkapp-contract"><strong>Create the ZkApp Contract</strong></h1>
<p>    [if !supportLists]1.      [endif]<strong>Navigate out of the demo project directory</strong> and install the <strong>zkapp-cli</strong> globally:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    cd ../
</code></pre>
<pre><code class="lang-plaintext">    npm install -g zkapp-cli
</code></pre>
<p>    [if !supportLists]2.      [endif]<strong>Initialize a new zkApp project</strong> with the CLI:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    zk project add
</code></pre>
<ol start="2">
<li><ul>
<li>When prompted to create a UI project, select <strong>none</strong>.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>Change into the newly created add directory</strong> and build the contract:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    cd add
</code></pre>
<pre><code class="lang-plaintext">    npm run build
</code></pre>
<p>    [if !supportLists]4.      [endif]<strong>Deploying the Add contract</strong>:</p>
<ol start="4">
<li><ul>
<li><p>An instance of the default <strong>Add</strong> contract has already been deployed to <strong>Devnet</strong> at:<br />   <code>B62qnTDEeYtBHBePA4yhCt4TCgDtA4L2CGvK7PirbJyX4pKH8bmtWe5</code></p>
<ul>
<li>You won’t need to deploy this contract again, but you will still need to include the contract code in your project to compile it into a <strong>verification key</strong> and <strong>proving key</strong>.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]5.      [endif]<strong>Proving Key and Verification Key</strong>:</p>
<ol start="5">
<li><ul>
<li><p>The <strong>proving key</strong> enables users to generate proofs of valid contract execution locally in their browsers.</p>
<ul>
<li><p>A user can execute the contract, create a proof using the proving key, and publish the proof on-chain to update the zkApp's state.</p>
</li>
<li><p>The <strong>verification key</strong> is stored on-chain, and the network will accept a transaction sent to the contract's address if it includes a proof generated by the proving key that matches the verification key on-chain.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    Your provided code is a solid setup for interacting with a deployed <strong>Add</strong> contract on Mina's Devnet using <strong>Angular</strong> and <strong>o1js</strong>. Here's a brief breakdown of the key parts of the code and how they work:</p>
<h3 id="heading-breakdown-of-the-code">Breakdown of the Code:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Imports</strong>:</p>
<ol>
<li><ul>
<li>You import <code>afterNextRender</code> from Angular's core and also import the necessary components to handle Mina operations (<code>Mina</code>, <code>PublicKey</code>, <code>fetchAccount</code>).</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]2.      [endif]<strong>Mina Network Setup</strong>:</p>
<ol start="2">
<li><ul>
<li>The <code>Mina.setActiveInstance()</code> function connects the Mina instance to the <strong>Devnet</strong> using the specified API URL (<code>https://api.minascan.io/node/devnet/v1/graphql</code>).</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>ZkApp Address</strong>:</p>
<ol start="3">
<li><ul>
<li>The <code>zkAppAddress</code> points to the already deployed <strong>Add contract</strong> on Mina's <strong>Devnet</strong>. This contract is accessible at the provided address (<code>B62qnTDEeYtBHBePA4yhCt4TCgDtA4L2CGvK7PirbJyX4pKH8bmtWe5</code>).</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]4.      [endif]<strong>Contract Interaction</strong>:</p>
<ol start="4">
<li><ul>
<li><p>The code fetches the account for the contract using the <code>fetchAccount()</code> method.</p>
<ul>
<li>It then creates a new instance of the <code>Add</code> contract using the public key of the <strong>zkApp</strong>.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]5.      [endif]<strong>State Reading</strong>:</p>
<ol start="5">
<li><ul>
<li>The <code>console.log()</code> reads and logs the current state of the contract, specifically the <code>num</code> field from the <code>Add</code> contract.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]6.      [endif]<strong>Wallet Interaction</strong>:</p>
<ol start="6">
<li><ul>
<li><p>It retrieves the injected Mina provider (<code>window.mina</code>), assuming the user has Auro Wallet installed.</p>
<ul>
<li><p>It then retrieves the public key of the wallet via <code>mina.requestAccounts()</code> and logs it.</p>
</li>
<li><p>The <code>Add.compile()</code> function compiles the contract to generate the necessary verification keys and proving keys.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]7.      [endif]<strong>Transaction Creation</strong>:</p>
<ol start="7">
<li><ul>
<li><p>A Mina transaction is created, and the <code>update()</code> method from the <code>Add</code> contract is called.</p>
<ul>
<li>The transaction is then proved and sent via the Mina provider to the network. Afterward, a link to the transaction is logged on the console.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]8.      [endif]<strong>Error Handling</strong>:</p>
<ol start="8">
<li><ul>
<li><p>Multiple error cases are handled, including:</p>
<ul>
<li><p>Missing Auro Wallet installation</p>
</li>
<li><p>Missing wallet creation</p>
</li>
<li><p>User rejecting wallet permissions</p>
</li>
<li><p>General unknown errors</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h3 id="heading-key-functional-flow">Key Functional Flow:</h3>
<ol>
<li><p><strong>Setup</strong>: Initializes the contract address and connects to the Devnet Mina network.</p>
</li>
<li><p><strong>State Reading</strong>: Fetches the state of the deployed <strong>Add contract</strong>.</p>
</li>
<li><p><strong>Wallet Interaction</strong>: Fetches the wallet’s public key from the Mina provider (Auro Wallet), compiles the contract, and sends the transaction.</p>
</li>
<li><p><strong>Transaction Creation</strong>: The transaction is sent and a link to the Mina scan page for the transaction is displayed.</p>
</li>
</ol>
<h3 id="heading-improvements-amp-suggestions">Improvements &amp; Suggestions:</h3>
<ul>
<li><p><strong>Error Handling</strong>: The error handling is well-structured. You might want to add more specific handling for other types of errors that could occur during the transaction (e.g., network issues).</p>
</li>
<li><p><strong>Async Execution</strong>: Consider adding loading indicators or UI changes while the asynchronous operations (contract interaction, wallet connection, etc.) are happening to improve user experience.</p>
</li>
</ul>
<h3 id="heading-things-to-test">Things to Test:</h3>
<ul>
<li><p>Make sure Auro Wallet is installed and active in the browser.</p>
</li>
<li><p>Ensure the wallet is properly configured and connected to <strong>Devnet</strong>.</p>
</li>
<li><p>Check that the contract interaction successfully updates the state on the <strong>Add contract</strong> and sends the transaction to the Mina network.</p>
</li>
</ul>
<p>    This is a great setup for an Angular-based Mina app with zkApps! Let me know if you need more assistance with this integration.</p>
<h3 id="heading-overview-of-what-the-code-does">Overview of What the Code Does:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Connects to the Devnet</strong>:</p>
<ol>
<li><ul>
<li>The code connects the Mina instance to the <strong>Devnet node</strong> using the Mina API URL. This ensures that any transactions made are broadcasted to the <strong>Devnet</strong> network rather than the main network, allowing you to interact with the test environment.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]2.      [endif]<strong>Requests User Address from the Wallet</strong>:</p>
<ol start="2">
<li><ul>
<li>The code fetches the user's address by requesting it from the wallet's injected <strong>mina provider</strong> (<code>window.mina</code>). This provider is automatically injected into the browser context by the wallet (like Auro Wallet), making it accessible to the app.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>Compiles the zkApp</strong>:</p>
<ol start="3">
<li><ul>
<li>The <code>Add</code> zkApp contract is compiled using <code>Add.compile()</code>. This step generates and caches the <strong>proving key</strong>, which is necessary for generating proofs. These proofs will allow users to submit a valid transaction to the Mina network.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]4.      [endif]<strong>Creates the zkApp Transaction</strong>:</p>
<ol start="4">
<li><ul>
<li>The code creates a <strong>transaction</strong> that calls the <code>update()</code> method of the <code>Add</code> contract. The transaction will update the state of the contract (in this case, incrementing the number).</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]5.      [endif]<strong>Proves the Transaction</strong>:</p>
<ol start="5">
<li><ul>
<li>The transaction is <strong>proved</strong> using the cached proving key that o1js holds internally. The proof ensures that the transaction is valid according to the contract's logic.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]6.      [endif]<strong>Prompts User to Broadcast</strong>:</p>
<ol start="6">
<li><ul>
<li>After proving the transaction, the wallet prompts the user to approve and broadcast the transaction to the network. This step requires user interaction with the wallet (Auro Wallet in this case) to confirm and send the transaction.</li>
</ul>
</li>
</ol>
<h3 id="heading-how-to-run-the-application">How to Run the Application:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Start the Local Development Server</strong>:</p>
<ol>
<li><ul>
<li>Run the following command in the terminal to start the local development server:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    npm run start
</code></pre>
<p>    This command will execute <code>ng serve</code>, which compiles and serves the Angular application.</p>
<p>    [if !supportLists]2.      [endif]<strong>Open the Browser Console</strong>:</p>
<ol start="2">
<li><ul>
<li><p>After the server starts, open your browser and navigate to the application (usually accessible at <code>http://localhost:4200</code>).</p>
<ul>
<li>Open the <strong>browser console</strong> (right-click -&gt; Inspect -&gt; Console) to see the log outputs.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>Approve Connection in Auro Wallet</strong>:</p>
<ol start="3">
<li><ul>
<li><p>Once the app requests the wallet connection, Auro Wallet will display a prompt in the browser asking the user for permission to connect.</p>
<ul>
<li><strong>Approve the connection request</strong> in Auro Wallet. This grants the app access to your Mina address and allows the app to interact with the Mina network.</li>
</ul>
</li>
</ul>
</li>
</ol>
<h3 id="heading-after-approving">After Approving:</h3>
<ul>
<li><p>Once the connection is approved, the app will proceed with compiling the zkApp, creating a transaction, proving it, and then prompting you to broadcast it to the network.</p>
</li>
<li><p>You will see a transaction hash in the console with a link to view the transaction on <strong>MinaScan</strong> for Devnet.</p>
</li>
</ul>
<p>    To resolve the <strong>DataCloneError</strong> and enable the use of <code>SharedArrayBuffer</code> in your Angular application while running <code>ng serve</code>, you'll need to set the necessary HTTP headers for <strong>Cross-Origin-Opener-Policy (COOP)</strong> and <strong>Cross-Origin-Embedder-Policy (COEP)</strong>.</p>
<h3 id="heading-steps-to-configure-sharedarraybuffer-headers-in-angular">Steps to Configure SharedArrayBuffer Headers in Angular:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Open your</strong> <code>angular.json</code> <strong>file</strong>:</p>
<ol>
<li><ul>
<li>Navigate to your project’s root directory and open the <code>angular.json</code> file.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]2.      [endif]<strong>Locate the</strong> <code>serve</code> <strong>configuration</strong>:</p>
<ol start="2">
<li><ul>
<li>In the <code>angular.json</code> file, look for the <code>serve</code> configuration under the project settings. It will look like this:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    json
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    "projects": {
</code></pre>
<pre><code class="lang-plaintext">      "&lt;your-project-name&gt;": {
</code></pre>
<pre><code class="lang-plaintext">        "architect": {
</code></pre>
<pre><code class="lang-plaintext">          "serve": {
</code></pre>
<pre><code class="lang-plaintext">            "builder": "@angular-devkit/build-angular:dev-server",
</code></pre>
<pre><code class="lang-plaintext">            "options": {
</code></pre>
<pre><code class="lang-plaintext">              "proxyConfig": "proxy.conf.json"
</code></pre>
<pre><code class="lang-plaintext">            },
</code></pre>
<pre><code class="lang-plaintext">            "configurations": {
</code></pre>
<pre><code class="lang-plaintext">              "development": {
</code></pre>
<pre><code class="lang-plaintext">                // custom configurations here
</code></pre>
<pre><code class="lang-plaintext">              }
</code></pre>
<pre><code class="lang-plaintext">            }
</code></pre>
<pre><code class="lang-plaintext">          }
</code></pre>
<pre><code class="lang-plaintext">        }
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>    [if !supportLists]3.      [endif]<strong>Add the headers configuration</strong>:</p>
<ol start="3">
<li><ul>
<li>Under the <code>options</code> section, add custom headers that enable <strong>SharedArrayBuffer</strong>. These headers are required for the WASM workers used in <code>o1js</code> for zkApp proof compilation.</li>
</ul>
</li>
</ol>
<p>    You need to configure <code>Cross-Origin-Opener-Policy</code> (COOP) and <code>Cross-Origin-Embedder-Policy</code> (COEP) to the following:</p>
<pre><code class="lang-plaintext">    json
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    "options": {
</code></pre>
<pre><code class="lang-plaintext">      "headers": {
</code></pre>
<pre><code class="lang-plaintext">        "Cross-Origin-Opener-Policy": "same-origin",
</code></pre>
<pre><code class="lang-plaintext">        "Cross-Origin-Embedder-Policy": "require-corp"
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>    This should look like:</p>
<pre><code class="lang-plaintext">    json
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    "projects": {
</code></pre>
<pre><code class="lang-plaintext">      "angular-o1js-demo": {
</code></pre>
<pre><code class="lang-plaintext">        "architect": {
</code></pre>
<pre><code class="lang-plaintext">          "serve": {
</code></pre>
<pre><code class="lang-plaintext">            "builder": "@angular-devkit/build-angular:dev-server",
</code></pre>
<pre><code class="lang-plaintext">            "options": {
</code></pre>
<pre><code class="lang-plaintext">              "headers": {
</code></pre>
<pre><code class="lang-plaintext">                "Cross-Origin-Opener-Policy": "same-origin",
</code></pre>
<pre><code class="lang-plaintext">                "Cross-Origin-Embedder-Policy": "require-corp"
</code></pre>
<pre><code class="lang-plaintext">              }
</code></pre>
<pre><code class="lang-plaintext">            },
</code></pre>
<pre><code class="lang-plaintext">            "configurations": {
</code></pre>
<pre><code class="lang-plaintext">              "development": {
</code></pre>
<pre><code class="lang-plaintext">                // custom configurations here
</code></pre>
<pre><code class="lang-plaintext">              }
</code></pre>
<pre><code class="lang-plaintext">            }
</code></pre>
<pre><code class="lang-plaintext">          }
</code></pre>
<pre><code class="lang-plaintext">        }
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>    [if !supportLists]4.      [endif]<strong>Restart the development server</strong>:</p>
<ol start="4">
<li><ul>
<li>After saving the changes to the <code>angular.json</code> file, stop the running <code>ng serve</code> process and start it again using:</li>
</ul>
</li>
</ol>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    npm run start
</code></pre>
<h3 id="heading-explanation-of-the-headers">Explanation of the Headers:</h3>
<p>    [if !supportLists]·         [endif]<strong>Cross-Origin-Opener-Policy (COOP)</strong>: This header ensures that only same-origin resources can interact with your application’s JavaScript context. This prevents malicious cross-origin resources from accessing shared memory in the browser.</p>
<p>    [if !supportLists]·         [endif]<strong>Cross-Origin-Embedder-Policy (COEP)</strong>: This header ensures that resources embedded in your page (like scripts or iframes) must either come from the same origin or include the appropriate permissions (<code>Cross-Origin-Resource-Policy: cross-origin</code>). This is required to allow the <code>SharedArrayBuffer</code> object to work correctly.</p>
<h3 id="heading-result">Result:</h3>
<ul>
<li><p>With these headers configured, the error related to <code>SharedArrayBuffer</code> should no longer occur, and you should be able to compile and execute zkApp contracts using WASM workers for proof generation.</p>
</li>
<li><p>Restart the server with npm run start and view the application in the browser again - the SharedArrayBuffer error should be gone!</p>
</li>
</ul>
<h2 id="heading-loading-o1jshttpsdocsminaprotocolcomzkappsfront-end-integration-guidesangularloading-o1js"><strong>Loading o1js</strong><a target="_blank" href="https://docs.minaprotocol.com/zkapps/front-end-integration-guides/angular#loading-o1js"><strong>​</strong></a></h2>
<ul>
<li><p>We still have another error: <code>Uncaught ReferenceError: __async is not defined</code>.</p>
</li>
<li><p>This one comes from the way Angular bundles dependencies internally. We'll address it by supplying our own custom webpack config which will exclude o1js from the bundle generated by Angular. Then we'll copy o1js into our static assets directory so it's served with the app and use import maps to import o1js directly.</p>
</li>
</ul>
<h1 id="heading-zkapp-developer-tutorials">zkApp Developer Tutorials</h1>
<p>    The <strong>zkApp Developer Tutorials</strong> provide hands-on guides to walk you through use cases that help you achieve specific goals with zkApps. These tutorials are aimed at helping developers build decentralized applications on the Mina blockchain using zkApps.</p>
<p>    <strong>o1js</strong> (formerly known as SnarkyJS) is a TypeScript library designed for writing general-purpose zk (zero-knowledge) programs and zk smart contracts for the Mina Protocol. It simplifies the process of creating and deploying zkApps on the Mina blockchain.</p>
<p>    To connect with other developers who are building zkApps using o1js, you can join the <strong>#zkapps-developers</strong> channel on the <strong>Mina Protocol Discord</strong>. This is a great way to share knowledge, ask questions, and collaborate with other developers in the community.</p>
<p>    <strong>Prerequisites</strong> for the zkApp developer tutorials:</p>
<ul>
<li><p><strong>zkApp CLI</strong>: This command-line tool is essential for creating, managing, and deploying zkApps. It's important to have the latest version installed to ensure compatibility with the tutorials.</p>
</li>
<li><p><strong>o1js</strong>: This TypeScript library is used to write zk smart contracts for the Mina blockchain. o1js is automatically included when you create a project using the zkApp CLI, so you don’t need to manually install it for basic usage.</p>
</li>
<li><p><strong>Other dependencies</strong>: Depending on the specific tutorial you're following, there may be additional dependencies that are required. These will be noted in the individual tutorial instructions.</p>
</li>
</ul>
<p>    To install the zkApp CLI, run the following command:</p>
<pre><code class="lang-plaintext">    ·         bash
</code></pre>
<pre><code class="lang-plaintext">    ·         CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    ·         $ npm install -g zkapp-cli
</code></pre>
<p>    [if !supportLists]·         [endif]To confirm the installation was successful, check the version with:</p>
<pre><code class="lang-plaintext">    ·         bash
</code></pre>
<pre><code class="lang-plaintext">    ·         CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    ·         $ zk –version
</code></pre>
<p>    To use the zkApp CLI and o1js, ensure your environment meets the following dependencies:</p>
<ul>
<li><p><strong>NodeJS v18 and later</strong></p>
</li>
<li><p><strong>NPM v10 and later</strong></p>
</li>
<li><p><strong>Git v2 and later</strong></p>
</li>
</ul>
<p>    To install or upgrade these dependencies, use a package manager appropriate for your operating system:</p>
<ul>
<li><p><strong>MacOS</strong>: Homebrew</p>
</li>
<li><p><strong>Windows</strong>: Chocolatey</p>
</li>
<li><p><strong>Linux</strong>: apt, yum, and others (you may need to use NodeSource for the latest Node.js version)</p>
</li>
</ul>
<p>    You can verify your installed versions using the following commands:</p>
<p>    bash</p>
<p>    CopyEdit</p>
<p>    npm -v</p>
<p>    node -v</p>
<p>    git -v</p>
<p>    <strong>Tips for following zkApp developer tutorials:</strong></p>
<ul>
<li><p><strong>Source Code</strong>: You can find the full source code for the tutorials in the examples/zkapps/ directory on GitHub. This can be helpful if you need to refer to the code directly or download it for your project.</p>
</li>
<li><p><strong>Support the Community</strong>: While you're on GitHub, don’t forget to give the /docs2 repository a star. This will help other zk developers discover resources to build their own zkApps.</p>
</li>
<li><p><strong>Avoid Copying Errors</strong>: To avoid copying line numbers or command prompts when copying code, use the "copy code to clipboard" button. This button appears at the top right of the snippet box when you hover over it. It ensures that you're only copying the actual code, without any extra annotations.</p>
</li>
</ul>
<p>    <strong>Useful Resources for zkApp Development:</strong></p>
<ol>
<li><p><strong>API Reference Docs</strong>: Once you're comfortable with the basics, the o1js Reference docs provide detailed information about all the available methods, properties, and interfaces. It's a comprehensive guide to the o1js library.</p>
</li>
<li><p><strong>o1Labs Blog</strong>: For updates and further reading about o1js and zkApps, visit the <a target="_blank" href="https://www.o1labs.org/blog/">o1Labs Blog</a>. You can also explore specific topics, including o1js updates, via the <a target="_blank" href="https://www.o1labs.org/blog?topics=o1js">o1js-specific blog feed</a>.</p>
</li>
<li><p><strong>Step-by-Step zkApp Explainer Videos</strong>: If you're new to zkApp development, the Mina Foundation YouTube channel offers helpful <a target="_blank" href="https://www.youtube.com/c/MinaProtocol">explainer videos</a>. Each video is linked to corresponding tutorials, providing a guided path to learning. Don't forget to <strong>Subscribe</strong> to get notified about new videos!</p>
</li>
</ol>
<h1 id="heading-tutorial-1-hello-world-introduction-to-zkapps-with-o1js"><strong>Tutorial 1: Hello World - Introduction to zkApps with o1js</strong></h1>
<p>    This tutorial is designed to introduce you to o1js, zkApps, and the basics of programming with zero-knowledge proofs (zkPs). By the end of this hands-on tutorial, you will have learned to build and interact with a simple zkApp smart contract.</p>
<h3 id="heading-what-you-will-learn">What You Will Learn:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Write a Basic Smart Contract</strong>:</p>
<ol>
<li><ul>
<li><p>Create a smart contract that stores a number as an on-chain state.</p>
<ul>
<li><p>Implement logic that allows you to replace the number with its square. For example:</p>
<ul>
<li>3 → 9 → 81 → 6561, and so on.</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]2.      [endif]<strong>Create a Project with zkApp CLI</strong>:</p>
<ol start="2">
<li><ul>
<li>Use the zkApp CLI to set up your project structure.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>Write the Smart Contract Code</strong>:</p>
<ol start="3">
<li><ul>
<li>Implement the contract logic in TypeScript using o1js.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]4.      [endif]<strong>Interact with the Contract Locally</strong>:</p>
<ol start="4">
<li><ul>
<li>Use a simulated local Mina blockchain to deploy and interact with your smart contract.</li>
</ul>
</li>
</ol>
<p>    This tutorial covers everything from setting up your development environment to running a zkApp contract. It’s a great starting point for anyone new to zkApps and zero-knowledge programming!</p>
<p>    Later tutorials introduce more concepts and patterns.</p>
<p>    The full source code for this tutorial is provided in the <a target="_blank" href="https://github.com/o1-labs/docs2/tree/main/examples/zkapps/01-hello-world">examples/zkapps/01-hello-world</a> directory on GitHub. While you're there, give the <code>/docs2</code> repository a star so that other zk developers can learn to build a zkApp!</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>    Before starting with the Hello World tutorial, make sure your development environment is ready. This includes having the necessary tools installed, especially the zkApp CLI.</p>
<h4 id="heading-steps-to-prepare">Steps to Prepare:</h4>
<p>    [if !supportLists]1.      [endif]<strong>Install the zkApp CLI</strong>: Make sure the <code>zkapp-cli</code> is installed globally on your system by running the following command:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    $ npm install -g zkapp-cli
</code></pre>
<p>    [if !supportLists]2.      [endif]<strong>Create or Change to a Directory</strong>: Create a new directory or navigate to an existing directory where you have write access.</p>
<p>    [if !supportLists]3.      [endif]<strong>Create a New Project</strong>: Once you’re in the desired directory, you can create a new project using the <code>zk project</code> command:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    $ zk project 01-hello-world
</code></pre>
<p>    [if !supportLists]4.      [endif]<strong>Scaffold the Project</strong>: The <code>zk project</code> command allows you to scaffold both the project structure and a UI for your project. For this tutorial, when prompted to create a UI, select <strong>none</strong>.</p>
<p>    With the tools installed and the project created, you're ready to begin building your zkApp!</p>
<h3 id="heading-project-setup-completion">Project Setup Completion</h3>
<p>    After running the <code>zk project</code> command and selecting <strong>none</strong> for the UI, the project setup process completes with the following steps:</p>
<ul>
<li><p><strong>Accompanying UI</strong>: No UI is created as you selected <strong>none</strong>.</p>
</li>
<li><p><strong>Git Initialization</strong>: The project initializes a Git repository with the first commit.</p>
</li>
<li><p><strong>Dependency Setup</strong>: The project installs dependencies (e.g., Prettier, ESLint, Jest).</p>
</li>
<li><p><strong>Contract Build</strong>: The contract is compiled as part of the setup process.</p>
</li>
<li><p><strong>Project Naming</strong>: The project name is set.</p>
</li>
</ul>
<h4 id="heading-next-steps">Next Steps:</h4>
<p>    [if !supportLists]1.      [endif]<strong>Navigate to the Project Directory</strong>: Change into the <code>01-hello-world</code> project directory:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    cd 01-hello-world
</code></pre>
<p>    [if !supportLists]2.      [endif]<strong>Add Remote Git Repository</strong>: Add your remote repository URL to the project:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    git remote add origin &lt;your-repo-url&gt;
</code></pre>
<p>    [if !supportLists]3.      [endif]<strong>Push to Remote Repository</strong>: Push the changes to your Git remote repository:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    git push -u origin main
</code></pre>
<p>    The project is now ready with the initial setup. You can begin writing your zkApp smart contract code.</p>
<p>    To navigate into the <code>01-hello-world</code> directory and list its contents, run the following commands:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    $ cd 01-hello-world
</code></pre>
<pre><code class="lang-plaintext">    $ ls
</code></pre>
<p>    This will change your current directory to <code>01-hello-world</code> and display the files and directories contained within it.</p>
<h3 id="heading-file-setup-for-the-hello-world-tutorial">File Setup for the "Hello World" Tutorial</h3>
<p>    After setting up the project, you need to prepare the project files by removing the default files and creating the necessary ones for this tutorial. Here are the steps:</p>
<h4 id="heading-1-remove-default-files">1. <strong>Remove Default Files</strong>:</h4>
<p>    The default project includes some sample files that you no longer need for this tutorial. Run these commands to delete them:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    rm src/Add.ts
</code></pre>
<pre><code class="lang-plaintext">    rm src/Add.test.ts
</code></pre>
<pre><code class="lang-plaintext">    rm src/interact.ts
</code></pre>
<h4 id="heading-2-create-new-files">2. <strong>Create New Files</strong>:</h4>
<p>    Use the following commands to create new files for your project:</p>
<p>    [if !supportLists]·         [endif]<strong>Create the contract file</strong> (Square.ts):</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    zk file src/Square
</code></pre>
<p>    [if !supportLists]·         [endif]<strong>Create the main script file</strong> (main.ts) for interacting with the smart contract:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    touch src/main.ts
</code></pre>
<p>    The <code>zk file</code> command creates both the contract file <code>src/Square.ts</code> and a corresponding test file <code>src/Square.test.ts</code>. However, since the tutorial does not include writing tests, you will not need to focus on the test file for now.</p>
<h4 id="heading-3-next-steps">3. <strong>Next Steps</strong>:</h4>
<p>    Now you're ready to proceed with coding your zkApp contract. The next steps will involve writing the logic for the smart contract in <code>src/Square.ts</code> and using the <code>src/main.ts</code> file to interact with it.</p>
<h3 id="heading-project-preparation-and-file-setup">Project Preparation and File Setup</h3>
<p>    After cleaning up the default files, here’s how to proceed with the necessary setup for your project.</p>
<h4 id="heading-1-delete-old-files">1. <strong>Delete Old Files</strong>:</h4>
<p>    The default files provided by the zkApp CLI are not needed for this tutorial, so you’ll remove them:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    rm src/Add.ts
</code></pre>
<pre><code class="lang-plaintext">    rm src/Add.test.ts
</code></pre>
<pre><code class="lang-plaintext">    rm src/interact.ts
</code></pre>
<h4 id="heading-2-create-new-files-1">2. <strong>Create New Files</strong>:</h4>
<p>    Use the following commands to create the necessary files for this tutorial:</p>
<p>    [if !supportLists]·         [endif]<strong>Create the Square contract file</strong>:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    zk file src/Square
</code></pre>
<p>    This will create the <code>src/Square.ts</code> contract file and a corresponding test file (<code>src/Square.test.ts</code>).</p>
<p>    [if !supportLists]·         [endif]<strong>Create the main script file</strong> (main.ts) for interacting with the smart contract:</p>
<pre><code class="lang-plaintext">    bash
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    touch src/main.ts
</code></pre>
<h4 id="heading-3-modify-the-srcindexts-file">3. <strong>Modify the</strong> <code>src/index.ts</code> <strong>File</strong>:</h4>
<p>    Open the <code>src/index.ts</code> file in a text editor and change it to:</p>
<pre><code class="lang-plaintext">    typescript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    import { Square } from './Square.js';
</code></pre>
<pre><code class="lang-plaintext">    export { Square };
</code></pre>
<p>    This change makes the <code>Square</code> contract available for consumption from outside the smart contract project, such as from a UI or other modules.</p>
<p>    Now your project is prepared, and you can begin writing the smart contract code and interacting with it through the <code>src/main.ts</code> file. In the next tutorial steps, you'll start defining the logic of the <code>Square</code> contract.</p>
<h3 id="heading-writing-the-square-zkapp-smart-contract">Writing the <code>Square</code> zkApp Smart Contract</h3>
<p>    In this part of the tutorial, you’ll write the smart contract code in the <code>src/Square.ts</code> file. This contract will store a number as its on-chain state and allow this number to be replaced by its square, for example: 3 → 9 → 81 → 6561, and so on.</p>
<p>    Here’s an example of what the code in <code>src/Square.ts</code> might look like:</p>
<pre><code class="lang-plaintext">    typescript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    import { Field, SmartContract, state, State, method } from 'o1js';
</code></pre>
<pre><code class="lang-plaintext">    export class Square extends SmartContract {
</code></pre>
<pre><code class="lang-plaintext">      // Define a state variable to hold the current number
</code></pre>
<pre><code class="lang-plaintext">      @state(Field) num = State&lt;Field&gt;();
</code></pre>
<pre><code class="lang-plaintext">      // The initialization function sets the initial value of the number to 1
</code></pre>
<pre><code class="lang-plaintext">      init() {
</code></pre>
<pre><code class="lang-plaintext">        super.init();
</code></pre>
<pre><code class="lang-plaintext">        this.num.set(Field(1)); // Start with the number 1
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">      // Method to square the current number and store the new value
</code></pre>
<pre><code class="lang-plaintext">      @method async update() {
</code></pre>
<pre><code class="lang-plaintext">        const currentState = this.num.getAndRequireEquals(); // Get the current number
</code></pre>
<pre><code class="lang-plaintext">        const newState = currentState.square(); // Square the current number
</code></pre>
<pre><code class="lang-plaintext">        this.num.set(newState); // Set the new squared value as the new state
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<h3 id="heading-explanation-of-the-code">Explanation of the Code:</h3>
<p>    [if !supportLists]1.      [endif]<strong>Imports</strong>:</p>
<ol>
<li><ul>
<li><p>The <code>Field</code> module represents the type for numbers on the Mina blockchain.</p>
<ul>
<li>The <code>SmartContract</code>, <code>state</code>, <code>State</code>, and <code>method</code> modules are imported to help define the contract's logic and state.</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]2.      [endif]<strong>Contract Definition</strong>:</p>
<ol start="2">
<li><ul>
<li>The <code>Square</code> class extends <code>SmartContract</code> which enables us to define the contract's state and methods.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]3.      [endif]<strong>State</strong>:</p>
<ol start="3">
<li><ul>
<li>The contract has a state variable called <code>num</code>, which holds a <code>Field</code> type (a number). This is where the on-chain state is stored.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]4.      [endif]<strong>Init Method</strong>:</p>
<ol start="4">
<li><ul>
<li>The <code>init()</code> method sets up the initial state of the contract. In this case, we start by setting <code>num</code> to <code>1</code>.</li>
</ul>
</li>
</ol>
<p>    [if !supportLists]5.      [endif]<strong>Update Method</strong>:</p>
<ol start="5">
<li><ul>
<li><p>The <code>update()</code> method squares the current value of <code>num</code> and sets it as the new value of <code>num</code>.</p>
<ul>
<li><p><code>getAndRequireEquals()</code> is used to get the current state and ensure it matches the expected value.</p>
</li>
<li><p><code>square()</code> is a method provided by the Mina protocol to square the <code>Field</code> type.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h3 id="heading-testing-and-interacting-with-the-contract">Testing and Interacting with the Contract</h3>
<p>    Once you've written this code, you can compile and deploy the smart contract, and interact with it using the <code>src/main.ts</code> file. Each time you call <code>update()</code>, it will square the value of <code>num</code>.</p>
<h3 id="heading-copy-the-examplehttpsdocsminaprotocolcomzkappstutorialshello-worldcopy-the-example"><strong>Copy the example</strong><a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/hello-world#copy-the-example"><strong>​</strong></a></h3>
<p>    This tutorial describes each part of the completed code in the <a target="_blank" href="https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/Square.ts">Square.ts</a> example file.</p>
<p>    [if !supportLists]1.      [endif]First, open the <a target="_blank" href="https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/Square.ts">Square.ts</a> example file.</p>
<p>    [if !supportLists]2.      [endif]Copy the entire contents of the file into your smart contract in the <code>src/Square.ts</code> file.</p>
<p>    Now you are ready to review the imports in the smart contract.</p>
<h3 id="heading-importshttpsdocsminaprotocolcomzkappstutorialshello-worldimports"><strong>Imports</strong><a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/hello-world#imports"><strong>​</strong></a></h3>
<p>    The <code>import</code> statement brings in other packages and dependencies to use in your smart contract.</p>
<p>    All functions used inside a smart contract must operate on o1js compatible data types: <code>Field</code> types and other types built on top of <code>Field</code> types.</p>
<p>    Here are the items mentioned, explained in the context of o1js and zkApp smart contracts:</p>
<ul>
<li><p><strong>Field</strong>: The native number type in o1js. You can think of field elements as unsigned integers. Field elements are the most basic type in o1js, and all other o1js-compatible types are built on top of field elements.</p>
</li>
<li><p><strong>SmartContract</strong>: The class used to create zkApp smart contracts. It forms the basis for building the logic and structure of your zkApp.</p>
</li>
<li><p><strong>state</strong>: A decorator used in zkApp smart contracts to create references to state stored on-chain in a zkApp account. It makes interacting with and modifying on-chain state easier.</p>
</li>
<li><p><strong>State</strong>: A class used in zkApp smart contracts to represent state that is stored on-chain in a zkApp account. It defines the data structure that will be stored and manipulated within the smart contract.</p>
</li>
<li><p><strong>method</strong>: A decorator used in zkApp smart contracts to create smart contract methods (functions). These methods are the end-user's entry points to interact with the smart contract.</p>
</li>
</ul>
<p>    The <code>Square</code> smart contract in the <code>src/Square.ts</code> file has the following structure:</p>
<pre><code class="lang-plaintext">    typescript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    export class Square extends SmartContract {
</code></pre>
<pre><code class="lang-plaintext">      @state(Field) num = State&lt;Field&gt;();
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<h3 id="heading-breakdown">Breakdown:</h3>
<ul>
<li><p><strong>Square Class</strong>: This class extends <code>SmartContract</code>, meaning it is a zkApp smart contract that can run on the Mina blockchain.</p>
</li>
<li><p><strong>num (state)</strong>: The contract has one piece of on-chain state named <code>num</code>, which is of type <code>Field</code>.</p>
<ul>
<li><p><code>@state(Field)</code>: The <code>@state</code> decorator is used to define <code>num</code> as a state variable that is stored on-chain.</p>
</li>
<li><p><code>State&lt;Field&gt;()</code>: This initializes the state variable <code>num</code> with the type <code>Field</code>, which is the basic number type in o1js.</p>
</li>
</ul>
</li>
</ul>
<p>    This contract is simple, storing a field element (<code>num</code>) on-chain that can be interacted with within the contract's methods.</p>
<p>    The updated <code>Square</code> smart contract in the <code>src/Square.ts</code> file includes an <code>init</code> method, which is used to initialize the on-chain state when the contract is deployed:</p>
<pre><code class="lang-plaintext">    typescript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    export class Square extends SmartContract {
</code></pre>
<pre><code class="lang-plaintext">      @state(Field) num = State&lt;Field&gt;();
</code></pre>
<pre><code class="lang-plaintext">      init() {
</code></pre>
<pre><code class="lang-plaintext">        super.init();
</code></pre>
<pre><code class="lang-plaintext">        this.num.set(Field(3));
</code></pre>
<pre><code class="lang-plaintext">      }
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<h3 id="heading-breakdown-1">Breakdown:</h3>
<ul>
<li><p><strong>init Method</strong>:</p>
<ul>
<li><p><code>super.init()</code>: Since the <code>Square</code> class extends the <code>SmartContract</code> class, it calls the <code>init</code> method from the base class using <code>super.init()</code>. This ensures that any initialization logic from the base class is executed.</p>
</li>
<li><p><code>this.num.set(Field(3))</code>: This line sets the initial value of the <code>num</code> state to <code>3</code> when the smart contract is deployed. The value is stored as a <code>Field</code> type, which is a basic number type in o1js.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-key-points">Key Points:</h3>
<ul>
<li><p><strong>Initialization</strong>: The <code>init</code> method is a special method that runs when the zkApp smart contract is deployed. It is where you can set up the initial state of the contract.</p>
</li>
<li><p><strong>State Management</strong>: The <code>this.num.set(Field(3))</code> line ensures that the state variable <code>num</code> starts with the value <code>3</code>.</p>
</li>
<li><p><strong>Permissions</strong>: You can specify permissions for state variables, though this is optional. More details on setting permissions can be found in the o1js Reference documentation.</p>
</li>
<li><h3 id="heading-import-items-in-maints">Import Items in <code>main.ts</code>:</h3>
<ul>
<li><p><code>Field</code>: The fundamental o1js data type, representing unsigned integers.</p>
</li>
<li><p><code>Mina</code>: A local, simulated Mina blockchain instance used for testing and deploying smart contracts.</p>
</li>
<li><p><code>PrivateKey</code>: A class that provides functions to create and manipulate private keys.</p>
</li>
<li><p><code>AccountUpdate</code>: A class responsible for generating data structures used to update zkApp accounts on the Mina blockchain.</p>
</li>
</ul>
</li>
</ul>
<p>        These imports allow developers to interact with the Mina blockchain, deploy smart contracts, and simulate real blockchain operations locally.</p>
<h3 id="heading-simulated-local-blockchain">Simulated Local Blockchain</h3>
<p>        A <strong>simulated local blockchain</strong> provides a fast and efficient way to develop and test zkApps without interacting with a live network. It allows developers to:</p>
<ul>
<li><p><strong>Deploy smart contracts locally</strong> without incurring transaction fees.</p>
</li>
<li><p><strong>Test contract behavior</strong> in a controlled environment.</p>
</li>
<li><p><strong>Debug efficiently</strong> before moving to a public testnet or mainnet.</p>
</li>
</ul>
<p>        Later tutorials will introduce <strong>Lightnet</strong>, a lightweight Mina network that serves as an intermediate testing environment before deploying to live networks.</p>
<p>        The <strong>simulated local blockchain</strong> is the initial testing environment for zkApps, providing a fast and efficient way to test smart contracts locally.</p>
<p>        <strong>Lightnet</strong> is a lightweight version of the Mina network, offering a more accurate representation of the live blockchain. It serves as an intermediate testing step before deploying to public testnets or mainnet.</p>
<p>        For more details, refer to <strong>Testing zkApps with Lightnet</strong>.</p>
<p>        To initialize your simulated local blockchain, add the following code from the <a target="_blank" href="https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/main.ts">main.ts</a> <a target="_blank" href="https://github.com/o1-labs/docs2/blob/main/examples/zkapps/01-hello-world/src/main.ts">example</a> file to <code>src/main.ts</code>:</p>
<p>        4 const useProof = false;<br />        5<br />        6 const Local = await Mina.LocalBlockchain({ proofsEnabled: useProof });<br />        7 Mina.setActiveInstance(Local);<br />        8<br />        9 const deployerAccount = Local.testAccounts[0];<br />        10 const deployerKey = deployerAccount.key;<br />        11 const senderAccount = Local.testAccounts[1];<br />        12 const senderKey = senderAccount.key;</p>
<p>        To ensure line numbers remain consistent in your <strong>main.ts</strong> file, insert blank lines as necessary when copying code snippets.</p>
<p>        The <strong>simulated local blockchain</strong> includes <strong>pre-funded test accounts</strong>. Add the following lines to create <strong>local test accounts</strong> with <strong>test MINA (tMINA)</strong> for this tutorial:</p>
<p>        16 // ----------------------------------------------------<br />        17<br />        18 // Create a public/private key pair. The public key is your address and where you deploy the zkApp to<br />        19 const zkAppPrivateKey = PrivateKey.random();<br />        20 const zkAppAddress = zkAppPrivateKey.toPublicKey();</p>
<p>        To execute the compiled JavaScript code, use the following command:</p>
<pre><code class="lang-plaintext">        shCopyEdit$ node build/main.js
</code></pre>
<p>        This will deploy the <strong>Square</strong> smart contract to the <strong>simulated local blockchain</strong> and execute your interaction script. Let me know if you need help troubleshooting any issues!</p>
<p>        That's correct! Running the command:</p>
<pre><code class="lang-plaintext">        shCopyEditnpm run build &amp;&amp; node build/src/main.js
</code></pre>
<p>        ensures that your <strong>Square</strong> smart contract is compiled and executed in the <strong>simulated local blockchain</strong> in a single step. Let me know if you run into any issues or need further clarification!</p>
<p>        To initialize your smart contract, follow these steps and add the corresponding code to <code>src/main.ts</code>:</p>
<h3 id="heading-1-create-a-publicprivate-key-pair"><strong>1. Create a Public/Private Key Pair</strong></h3>
<p>        This generates an address (<code>zkAppAddress</code>) on the Mina network where the zkApp will be deployed.</p>
<h3 id="heading-2-deploy-the-smart-contract"><strong>2. Deploy the Smart Contract</strong></h3>
<p>        Create an instance of the <code>Square</code> smart contract and deploy it to <code>zkAppAddress</code>.</p>
<h3 id="heading-3-get-the-initial-state"><strong>3. Get the Initial State</strong></h3>
<p>        Retrieve the initial state (<code>num</code>) stored on-chain and log it to confirm deployment.</p>
<h3 id="heading-example-code-1"><strong>Example Code:</strong></h3>
<pre><code class="lang-plaintext">        typescriptCopyEdit// Import required classes
        import { Mina, PrivateKey, AccountUpdate } from 'o1js';
        import { Square } from './Square';

        // Initialize a local Mina blockchain
        const localBlockchain = Mina.LocalBlockchain();
        Mina.setActiveInstance(localBlockchain);

        // Generate deployer and zkApp keys
        const deployerKey = localBlockchain.testAccounts[0].privateKey;
        const zkAppPrivateKey = PrivateKey.random();
        const zkAppAddress = zkAppPrivateKey.toPublicKey();

        // Create an instance of Square and deploy it
        const zkAppInstance = new Square(zkAppAddress);
        const deployTxn = await Mina.transaction(deployerKey.toPublicKey(), async () =&gt; {
          AccountUpdate.fundNewAccount(deployerKey.toPublicKey());
          await zkAppInstance.deploy();
        });
        await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();

        // Retrieve and log the initial state
        const num0 = zkAppInstance.num.get();
        console.log('State after init:', num0.toString());
</code></pre>
<h3 id="heading-expected-output"><strong>Expected Output:</strong></h3>
<pre><code class="lang-plaintext">        shCopyEditState after init: 3
</code></pre>
<h3 id="heading-smart-contract-initialization-summary"><strong>Smart Contract Initialization Summary</strong></h3>
<p>        To initialize your smart contract, add more code from the <code>main.ts</code> example file to <code>src/main.ts</code>.</p>
<h4 id="heading-steps"><strong>Steps:</strong></h4>
<ol>
<li><p><strong>Generate Keys:</strong> Create a public/private key pair; the public key is an address on the Mina network where the zkApp is deployed.</p>
</li>
<li><p><strong>Deploy Smart Contract:</strong> Create an instance of <code>Square</code> and deploy it to <code>zkAppAddress</code>.</p>
</li>
<li><p><strong>Retrieve Initial State:</strong> Get the initial state of <code>Square</code> after deployment.</p>
</li>
</ol>
<h4 id="heading-code-breakdown"><strong>Code Breakdown:</strong></h4>
<pre><code class="lang-plaintext">        typescriptCopyEdit// create an instance of Square - and deploy it to zkAppAddress
        const zkAppInstance = new Square(zkAppAddress);
        const deployTxn = await Mina.transaction(deployerAccount, async () =&gt; {
          AccountUpdate.fundNewAccount(deployerAccount);
          await zkAppInstance.deploy();
        });
        await deployTxn.sign([deployerKey, zkAppPrivateKey]).send();

        // get the initial state of Square after deployment
        const num0 = zkAppInstance.num.get();
        console.log('state after init:', num0.toString());
</code></pre>
<p>        This code initializes and deploys the <code>Square</code> smart contract while retrieving its initial on-chain state.</p>
<h3 id="heading-updating-zkapp-account-with-a-transaction"><strong>Updating zkApp Account with a Transaction</strong></h3>
<p>        To update your local zkApp account with a transaction, add the following code to <code>src/main.ts</code>:</p>
<h4 id="heading-code-implementation"><strong>Code Implementation:</strong></h4>
<pre><code class="lang-plaintext">        typescriptCopyEdit// ----------------------------------------------------

        const txn1 = await Mina.transaction(senderAccount, async () =&gt; {
          await zkAppInstance.update(Field(9));
        });
        await txn1.prove();
        await txn1.sign([senderKey]).send();

        const num1 = zkAppInstance.num.get();
        console.log('state after txn1:', num1.toString());
</code></pre>
<h4 id="heading-execution-amp-expected-output"><strong>Execution &amp; Expected Output:</strong></h4>
<p>        Run the following command:</p>
<pre><code class="lang-plaintext">        shCopyEdit$ npm run build &amp;&amp; node build/src/main.js
</code></pre>
<p>        Expected output:</p>
<pre><code class="lang-plaintext">        perlCopyEdit&gt; 01-hello-world@0.1.0 build
        &gt; tsc

        state after init: 3  
        state after txn1: 9
</code></pre>
<p>        This confirms that the zkApp's state was successfully updated from 3 to 9 based on the <code>update()</code> function’s rules.</p>
<p>        Here’s a reconstructed and summarized version without adding or removing any words:</p>
<hr />
<h3 id="heading-adding-a-transaction-that-fails">Adding a Transaction That Fails</h3>
<p>        To test a failing transaction, add more code from <code>main.ts</code> to <code>src/main.ts</code>. The contract logic allows the stored number to be updated only with its square. Since <code>num</code> is now <code>9</code>, updating is only possible with <code>81</code>.</p>
<p>        To test failure, modify the state to <code>75</code> using:</p>
<pre><code class="lang-plaintext">        typescriptCopyEdittry {
          const txn2 = await Mina.transaction(senderAccount, async () =&gt; {
            await zkAppInstance.update(Field(75));
          });
          await txn2.prove();
          await txn2.sign([senderKey]).send();
        } catch (error: any) {
          console.log(error.message);
        }
        const num2 = zkAppInstance.num.get();
        console.log('state after txn2:', num2.toString());
</code></pre>
<p>        Run:</p>
<pre><code class="lang-plaintext">        shCopyEdit$ npm run build &amp;&amp; node build/src/main.js
</code></pre>
<p>        <strong>Expected Output:</strong></p>
<pre><code class="lang-plaintext">        yamlCopyEditstate after init: 3  
        state after txn1: 9  
        Field.assertEquals(): 75 != 81  
        state after txn2: 9
</code></pre>
<p>        Finally, update <code>main.ts</code> to correctly change the state to <code>81</code> and rerun the command.</p>
<p>        <strong>Expected Output:</strong></p>
<pre><code class="lang-plaintext">        perlCopyEditstate after init: 3  
        state after txn1: 9  
        state after txn2: 81
</code></pre>
<h3 id="heading-tutorial-2-private-inputs-and-hash-functions"><strong>Tutorial 2: Private Inputs and Hash Functions</strong></h3>
<p>        In the <strong>Hello World</strong> tutorial, you created a basic zkApp smart contract using <strong>o1js</strong> with a single state variable that could be updated only if you knew its square.</p>
<p>        This tutorial introduces <strong>private inputs</strong> and <strong>hash functions</strong>.</p>
<p>        In a <strong>zkApp</strong>, a user's device generates zero-knowledge proofs, which the <strong>Mina network</strong> verifies. Each method in an <strong>o1js</strong> smart contract corresponds to constructing a proof.</p>
<p>        By default, <strong>all inputs to a smart contract are private</strong>. Inputs are only visible on the blockchain if they are explicitly stored as on-chain state in the <strong>zkApp account</strong>.</p>
<p>        In this tutorial, you will build a smart contract with <strong>private state</strong> that can be modified only if the user knows its value.</p>
<h3 id="heading-prerequisites-1"><strong>Prerequisites</strong></h3>
<p>        This tutorial has been tested with <strong>zkApp CLI version 0.20.1</strong>. Ensure your environment meets the <strong>Prerequisites for zkApp Developer Tutorials</strong>.</p>
<hr />
<h3 id="heading-create-a-project"><strong>Create a Project</strong></h3>
<ol>
<li><p>Navigate to a directory where you have write privileges.</p>
</li>
<li><p>Run the following command to create a new zkApp project:</p>
<pre><code class="lang-plaintext"> shCopyEdit$ zk project 02-private-inputs-and-hash-functions
</code></pre>
</li>
<li><p>When prompted, select <strong>none</strong> for the accompanying UI project:</p>
<pre><code class="lang-plaintext"> sqlCopyEdit? Create an accompanying UI project too? …
   next
   svelte
   nuxt
   empty
 &gt; none
</code></pre>
</li>
<li><p><strong>Expected Output:</strong></p>
<pre><code class="lang-plaintext"> sqlCopyEdit✔ Create an accompanying UI project too? · none
 ✔ UI: Set up project
 ✔ Initialize Git repo
 ✔ Set up project
 ✔ NPM install
 ✔ NPM build contract
 ✔ Set project name
 ✔ Git init commit

 Success!

 Next steps:
   cd 02-private-inputs-and-hash-functions
   git remote add origin &lt;your-repo-url&gt;
   git push -u origin main
</code></pre>
</li>
</ol>
<hr />
<h3 id="heading-project-structure"><strong>Project Structure</strong></h3>
<p>        The <code>zk project</code> command creates the <code>02-private-inputs-and-hash-functions</code> directory, which includes:</p>
<ul>
<li><p><strong>Prettier</strong> (code formatting)</p>
</li>
<li><p><strong>ESLint</strong> (static code analysis)</p>
</li>
<li><p><strong>Jest</strong> (JavaScript testing framework)</p>
</li>
</ul>
<p>        To explore the project, change into the directory and list its contents:</p>
<pre><code class="lang-plaintext">        shCopyEdit$ cd 02-private-inputs-and-hash-functions
        $ ls
</code></pre>
<p>        <strong>Expected Output:</strong></p>
<pre><code class="lang-plaintext">        luaCopyEditLICENSE
        README.md
        babel.config.cjs
        build
        config.json
        jest-resolver.cjs
        jest.config.js
        keys
        node_modules
        package-lock.json
        package.json
        src
        tsconfig.json
</code></pre>
<p>        You will run commands from the <strong>root</strong> of this directory while working on <strong>TypeScript</strong> code inside the <code>src</code> folder.</p>
<p>        Each time you update, build, or deploy, the <strong>TypeScript code</strong> is compiled into <strong>JavaScript</strong> in the <code>build</code> directory.</p>
<ul>
<li><h3 id="heading-prepare-the-project"><strong>Prepare the Project</strong></h3>
<h4 id="heading-1-remove-default-files-1"><strong>1. Remove Default Files</strong></h4>
<p>  Delete the default generated files:</p>
<pre><code class="lang-plaintext">  shCopyEdit$ rm src/Add.ts
  $ rm src/Add.test.ts
  $ rm src/interact.ts
</code></pre>
<hr />
<h4 id="heading-2-create-new-files-2"><strong>2. Create New Files</strong></h4>
<p>  Run the following commands to set up new files for the project:</p>
<pre><code class="lang-plaintext">  shCopyEdit$ zk file src/IncrementSecret
  $ touch src/main.ts
</code></pre>
<ul>
<li><p>The <code>zk file</code> command creates:</p>
<ul>
<li><p><code>src/IncrementSecret.ts</code> (smart contract file)</p>
</li>
<li><p><code>src/IncrementSecret.test.ts</code> (test file, but not used in this tutorial)</p>
</li>
</ul>
</li>
<li><p><code>main.ts</code> will be used as a script to interact with the smart contract.</p>
</li>
</ul>
</li>
</ul>
<hr />
<h4 id="heading-3-modify-srcindexts"><strong>3. Modify</strong> <code>src/index.ts</code></h4>
<p>        Open <code>src/index.ts</code> in a text editor and modify it to:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditimport { IncrementSecret } from './IncrementSecret.js';

        export { IncrementSecret };
</code></pre>
<p>        This file manages exports for external consumption, such as UI components interacting with the smart contract.</p>
<h3 id="heading-copy-the-example-files"><strong>Copy the Example Files</strong></h3>
<p>        This tutorial requires using the example files from <code>02-private-inputs-and-hash-functions/src/</code>.</p>
<h4 id="heading-1-copy-incrementsecretts"><strong>1. Copy</strong> <code>IncrementSecret.ts</code></h4>
<ul>
<li><p>Open the <strong>example</strong> <code>IncrementSecret.ts</code> file.</p>
</li>
<li><p>Copy its entire contents into <strong>your</strong> <code>src/IncrementSecret.ts</code> file.</p>
</li>
</ul>
<h4 id="heading-2-copy-maints"><strong>2. Copy</strong> <code>main.ts</code></h4>
<ul>
<li><p>Open the <strong>example</strong> <code>main.ts</code> file.</p>
</li>
<li><p>Copy its entire contents into <strong>your</strong> <code>src/main.ts</code> file.</p>
</li>
</ul>
<hr />
<p>        Now, you are ready to <strong>review the imports</strong> in the smart contract.</p>
<h3 id="heading-write-the-smart-contract"><strong>Write the Smart Contract</strong></h3>
<p>        Now, let's build the smart contract for our application.</p>
<hr />
<h3 id="heading-imports"><strong>Imports</strong></h3>
<p>        The import statement in <code>IncrementSecret.ts</code> brings in required packages:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditimport { Field, SmartContract, state, State, method, Poseidon } from 'o1js';
</code></pre>
<p>        ⚡ <strong>Note:</strong><br />        All functions inside a smart contract must operate on <strong>o1js-compatible data types</strong>, such as <code>Field</code> and types built on top of <code>Field</code>.</p>
<hr />
<h3 id="heading-exports"><strong>Exports</strong></h3>
<p>        The smart contract <strong>IncrementSecret</strong> has an <strong>on-chain state</strong> named <code>x</code> of type <code>Field</code>:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditexport class IncrementSecret extends SmartContract {
          @state(Field) x = State&lt;Field&gt;();
        }
</code></pre>
<p>        This defines the basic structure of the smart contract. If you completed <strong>Tutorial 01: Hello World</strong>, you should recognize the import and export structure.</p>
<hr />
<h3 id="heading-initial-state"><strong>Initial State</strong></h3>
<p>        The <code>initState()</code> method runs <strong>once</strong> to set up the initial state in the zkApp account:</p>
<pre><code class="lang-plaintext">        typescriptCopyEdit@method async initState(salt: Field, firstSecret: Field) {
          this.x.set(Poseidon.hash([salt, firstSecret]));
        }
</code></pre>
<ul>
<li><p>The method accepts two inputs:</p>
<ul>
<li><p><code>salt</code> → A random value for added security</p>
</li>
<li><p><code>firstSecret</code> → The initial private state</p>
</li>
</ul>
</li>
</ul>
<p>        These <strong>inputs are private</strong> to whoever initializes the contract. The <strong>zkApp account does not reveal</strong> the actual values of <code>firstSecret</code> or <code>salt</code>.</p>
<h3 id="heading-update-the-state"><strong>Update the State</strong></h3>
<p>        The <code>incrementSecret()</code> method updates the on-chain state:</p>
<pre><code class="lang-plaintext">        typescriptCopyEdit@method async incrementSecret(salt: Field, secret: Field) {
          const x = this.x.get();
          this.x.requireEquals(x);

          Poseidon.hash([salt, secret]).assertEquals(x);
          this.x.set(Poseidon.hash([salt, secret.add(1)]));
        }
</code></pre>
<hr />
<h3 id="heading-how-it-works"><strong>How It Works</strong></h3>
<ol>
<li><p><strong>Retrieves</strong> the current state <code>x</code>.</p>
</li>
<li><p><strong>Ensures</strong> that <code>x</code> matches the expected value.</p>
</li>
<li><p><strong>Verifies</strong> that the provided <code>salt</code> and <code>secret</code> hash to <code>x</code>.</p>
</li>
<li><p><strong>Increments</strong> the secret (<code>secret + 1</code>).</p>
</li>
<li><p><strong>Updates</strong> <code>x</code> with the hash of <code>salt</code> and the new secret.</p>
</li>
</ol>
<hr />
<h3 id="heading-why-poseidon-hash"><strong>Why Poseidon Hash?</strong></h3>
<ul>
<li><p><strong>Optimized</strong> for zero-knowledge proof systems.</p>
</li>
<li><p><strong>Takes an array of</strong> <code>Field</code>s and outputs a single <code>Field</code>.</p>
</li>
</ul>
<p>        This ensures that:</p>
<p>        ✅ The <strong>secret and salt remain private</strong> (not stored on-chain).<br />        ✅ The <strong>only revealed value</strong> is <code>x = hash([salt, secret + 1])</code>.<br />        ✅ The <strong>transaction updates</strong> the zkApp account securely.</p>
<p>        Since <strong>hash functions are one-way</strong>, <strong>salt and secret cannot be deduced</strong> from their hash, ensuring privacy.</p>
<h3 id="heading-about-the-salt-argument"><strong>About the</strong> <code>salt</code> Argument</h3>
<p>        Cryptographic <strong>salt</strong> adds an extra layer of security to a smart contract.</p>
<p>        Without <code>salt</code>, an attacker could:</p>
<ol>
<li><p><strong>Guess likely secrets</strong>, hash them, and compare with the stored hash.</p>
</li>
<li><p><strong>Discover the secret</strong> if it falls within a small range (e.g., 1–10,000).</p>
</li>
</ol>
<p>        <strong>Example Attack Without Salt:</strong></p>
<ul>
<li><p>The attacker hashes numbers from <strong>1 to 10,000</strong>.</p>
</li>
<li><p>If a match is found, the secret is exposed.</p>
</li>
</ul>
<hr />
<h3 id="heading-how-salt-enhances-security"><strong>How</strong> <code>salt</code> Enhances Security</h3>
<p>        By including <code>salt</code> in the hash:<br />        ✅ <strong>The same secret produces a different hash each time.</strong><br />        ✅ <strong>Attackers can’t precompute hashes</strong> without knowing <code>salt</code>.<br />        ✅ <strong>Reverse-engineering the secret becomes impractical.</strong></p>
<p>        For <strong>maximum security</strong>:</p>
<ul>
<li><p><strong>Keep</strong> <code>salt</code> private (only you should know it).</p>
</li>
<li><p><strong>Use a random value</strong> to prevent predictable patterns.</p>
</li>
</ul>
<p>        This makes the <strong>contract more secure</strong> and protects on-chain data from brute-force attacks.</p>
<h3 id="heading-main"><strong>Main</strong></h3>
<p>        The <code>src/main.ts</code> file is similar to the <strong>Hello World</strong> tutorial but with modifications for using the <strong>Poseidon hash</strong> and smart contract initialization.</p>
<hr />
<h3 id="heading-smart-contract-initialization"><strong>Smart Contract Initialization</strong></h3>
<p>        The smart contract is initialized with a <strong>random salt</strong> and a <strong>secret</strong> value. The <code>initState()</code> method takes both:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditconst salt = Field.random();

        const deployTxn = await Mina.transaction(deployerAccount, async () =&gt; {
          AccountUpdate.fundNewAccount(deployerAccount);
          await zkAppInstance.deploy();
          await zkAppInstance.initState(salt, Field(750));  // Initializing with salt and secret 750
        });
        await deployTxn.prove();
</code></pre>
<ul>
<li><p><strong>salt</strong> is randomly generated using <code>Field.random()</code>.</p>
</li>
<li><p><strong>secret</strong> is <code>750</code> in this case.</p>
</li>
<li><p><code>initState()</code> sets the initial state for the smart contract, using the salt and secret to create the <strong>Poseidon hash</strong>.</p>
</li>
</ul>
<hr />
<h3 id="heading-user-transaction"><strong>User Transaction</strong></h3>
<p>        The user transaction is used to update the on-chain state, calling the <code>incrementSecret()</code> method:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditconst txn1 = await Mina.transaction(senderAccount, async () =&gt; {
          await zkAppInstance.incrementSecret(salt, Field(750));  // Sending salt and secret 750
        });
</code></pre>
<p>        This call does not include the salt or secret in the transaction itself. Instead, it includes the <strong>proof</strong> that the update was valid and that the state was updated.</p>
<hr />
<h3 id="heading-what-happens-in-the-transaction"><strong>What Happens in the Transaction?</strong></h3>
<p>        The transaction proves that the update to the on-chain state <strong>passed all assertions</strong>. The state <code>x</code> is updated to:</p>
<pre><code class="lang-plaintext">        plaintextCopyEditPoseidon.hash([salt, Field(750).add(1)])
</code></pre>
<ul>
<li><p>The <strong>salt</strong> and <strong>secret</strong> are not included in the transaction.</p>
</li>
<li><p>Only the <strong>updated state</strong> is stored on-chain.</p>
</li>
</ul>
<p>        Once the transaction is processed by the <strong>Mina network</strong>, the new value of <code>x</code> becomes:</p>
<pre><code class="lang-plaintext">        plaintextCopyEditPoseidon.hash([salt, 751])
</code></pre>
<hr />
<h3 id="heading-run-the-script"><strong>Run the Script</strong></h3>
<p>        To run the script, use:</p>
<pre><code class="lang-plaintext">        shCopyEdit$ npm run build &amp;&amp; node build/src/main.js
</code></pre>
<hr />
<h3 id="heading-expected-output-1"><strong>Expected Output</strong></h3>
<p>        The output will look like this:</p>
<pre><code class="lang-plaintext">        perlCopyEditstate after init: 3116464240601550031577632290308565252747064306168758166756574536757280262269
        state after txn1: 15333363135506653312218020664441564145350761288169575380089681962972642150348
</code></pre>
<p>        The state strings will differ because <code>Field.random()</code> generates a unique salt each time, ensuring different state values.</p>
<h3 id="heading-tutorial-3-deploy-to-a-live-network"><strong>Tutorial 3: Deploy to a Live Network</strong></h3>
<p>        In previous tutorials, you learned how to deploy and execute transactions on a local network. In this tutorial, you will use the <strong>zk config</strong> command to create the deploy alias, request <strong>tMINA</strong> funds to pay for transaction fees, and deploy <strong>zkApp</strong> to a live network.</p>
<p>        This tutorial reuses the <strong>Square contract</strong> that was created in <strong>Tutorial 1: Hello World</strong>.</p>
<h3 id="heading-prerequisites-2"><strong>Prerequisites</strong></h3>
<p>        This tutorial has been tested with:</p>
<ul>
<li><p><strong>zkApp CLI version 0.20.1</strong></p>
</li>
<li><p><strong>o1js version 1.1.0</strong></p>
</li>
</ul>
<p>        Ensure your environment meets the prerequisites for zkApp Developer Tutorials.</p>
<p>        If you have earlier versions of <strong>zkApp CLI</strong> and <strong>o1js</strong>, be sure to update them to the latest version with the command:</p>
<pre><code class="lang-plaintext">        shCopyEditnpm update -g zkapp-cli
</code></pre>
<hr />
<h3 id="heading-create-a-project-1"><strong>Create a Project</strong></h3>
<ol>
<li><p><strong>Create or change to a directory</strong> where you have write privileges.</p>
</li>
<li><p>Use the <strong>zk project</strong> command to create the project:</p>
<pre><code class="lang-plaintext"> shCopyEdit$ zk project 03-deploying-to-a-live-network
</code></pre>
<p> The <strong>zk project</strong> command has the ability to scaffold the UI for your project. For this tutorial, select <strong>none</strong> when prompted:</p>
<pre><code class="lang-plaintext"> sqlCopyEdit? Create an accompanying UI project too? …
 &gt; none
</code></pre>
<p> <strong>Expected Output:</strong></p>
<pre><code class="lang-plaintext"> pgsqlCopyEdit✔ Create an accompanying UI project too? · none
 ✔ UI: Set up project
 ✔ Initialize Git repo
 ✔ Set up project
 ✔ NPM install
 ✔ NPM build contract
 ✔ Set project name
 ✔ Git init commit
</code></pre>
</li>
<li><p>After the setup is complete, proceed with the next steps:</p>
<pre><code class="lang-plaintext"> shCopyEditcd 03-deploying-to-a-live-network
 git remote add origin &lt;your-repo-url&gt;
 git push -u origin main
</code></pre>
</li>
<li><p>The <strong>zk project</strong> command creates the <strong>03-deploying-to-a-live-network</strong> directory containing the scaffolding for your project. It includes tools like:</p>
<ul>
<li><p>Prettier (for code formatting)</p>
</li>
<li><p>ESLint (for static code analysis)</p>
</li>
<li><p>Jest (for JavaScript testing)</p>
</li>
</ul>
</li>
<li><p>Change into the <strong>03-deploying-to-a-live-network</strong> directory:</p>
<pre><code class="lang-plaintext"> shCopyEditcd 03-deploying-to-a-live-network
</code></pre>
</li>
</ol>
<hr />
<h3 id="heading-prepare-the-project-1"><strong>Prepare the Project</strong></h3>
<ol>
<li><p><strong>Delete Default Files</strong><br /> Start by deleting the default files that come with the new project:</p>
<pre><code class="lang-plaintext"> shCopyEdit$ rm src/Add.ts
 $ rm src/Add.test.ts
 $ rm src/interact.ts
</code></pre>
</li>
<li><p><strong>Copy Files from the First Tutorial</strong><br /> Copy the <code>src/Square.ts</code> and <code>src/index.ts</code> files from the <strong>01-hello-world/src</strong> directory of the first tutorial to your local <strong>03-deploying-to-a-live-network/src</strong> directory. If prompted, replace the existing files.</p>
</li>
<li><p><strong>Smart Contract Ready for Deployment</strong><br /> After copying the files, your smart contract is now in place and ready for deployment to <strong>Devnet</strong>.</p>
</li>
</ol>
<h3 id="heading-zkapp-cli"><strong>zkApp CLI</strong></h3>
<p>        You have already installed the <strong>zkApp CLI</strong> as part of the prerequisites, so you're equipped with the necessary tools to manage deployments.</p>
<p>        In certain cases, you might need to:</p>
<ol>
<li><p><strong>Create a custom account</strong> for your zkApp.</p>
</li>
<li><p><strong>Programmatically parameterize a zkApp</strong> before initializing it.</p>
</li>
<li><p><strong>Create a smart contract</strong> programmatically for users as part of an application.</p>
</li>
</ol>
<p>        For more information on these advanced topics, refer to the <strong>Interacting with zkApps server-side</strong> section.</p>
<h3 id="heading-deploy-the-smart-contract"><strong>Deploy the Smart Contract</strong></h3>
<p>        The <strong>config.json</strong> configuration file contains the necessary settings to deploy your <strong>zkApp</strong>. This file was automatically created when you ran the <strong>zk project</strong> command to scaffold your project.</p>
<p>        However, the generated <strong>config.json</strong> file does not yet contain the <strong>deploy alias</strong>.</p>
<p>        To proceed with deploying your <strong>zkApp</strong>, you will need to update the <strong>config.json</strong> file with the appropriate <strong>deploy alias</strong> for your target network (such as <strong>Devnet</strong>, <strong>Testnet</strong>, or <strong>Mainnet</strong>).</p>
<h3 id="heading-deploy-alias-configuration"><strong>Deploy Alias Configuration</strong></h3>
<p>        The <strong>zk config</strong> command helps you set up a deploy alias in your project’s <strong>config.json</strong> file. You can create one or more deploy aliases, which are essential for deploying your zkApp.</p>
<p>        A <strong>deploy alias</strong> consists of:</p>
<ol>
<li><p><strong>A self-describing name</strong> that can be anything. It's helpful to use a pattern if you have multiple deploy aliases.</p>
</li>
<li><p><strong>The target network kind</strong> (Testnet, Mainnet, or custom network ID).</p>
</li>
<li><p><strong>The Mina GraphQL API URL</strong>, which defines the network for your deploy transaction (e.g., Testnet, Devnet, Mainnet).</p>
</li>
<li><p><strong>The transaction fee</strong> (in MINA) used for deployment.</p>
</li>
<li><p><strong>Two key pairs</strong>:</p>
<ul>
<li><p>A key pair for the zkApp account (generated automatically in <strong>keys/&lt;deploy-alias-name&gt;.json</strong>).</p>
</li>
<li><p>A key pair for the fee payer account for updates and deployments (stored locally and reusable across projects).</p>
</li>
</ul>
</li>
<li><p><strong>Fee payer account alias</strong>: You can use an existing account or create a new one to pay for transaction fees.</p>
</li>
</ol>
<h4 id="heading-steps-to-configure-your-deploy-alias">Steps to Configure Your Deploy Alias:</h4>
<p>        Run the <strong>zk config</strong> command and answer the prompts:</p>
<pre><code class="lang-plaintext">        bashCopyEdit$ zk config
</code></pre>
<p>        For this tutorial (using <strong>Devnet</strong>), use the following values:</p>
<ol>
<li><p><strong>Deploy alias name</strong>: <code>devnet</code></p>
</li>
<li><p><strong>Target network kind</strong>: <code>Testnet</code></p>
</li>
<li><p><strong>Mina GraphQL API URL</strong>: <code>https://api.minascan.io/node/devnet/v1/graphql</code></p>
</li>
<li><p><strong>Transaction fee</strong>: <code>0.1 MINA</code></p>
</li>
<li><p>When prompted for an account to pay transaction fees, select <strong>Use a different account</strong>.</p>
</li>
<li><p>Choose to <strong>Create a new fee payer key pair</strong>.</p>
<ul>
<li><strong>Fee payer alias</strong>: <code>03-deploy</code></li>
</ul>
</li>
</ol>
<p>        Once your deploy alias is configured, the <strong>zkApp key pair</strong> and <strong>fee payer key pair</strong> are created and stored in <strong>keys/devnet.json</strong> and <strong>${HOME}/.cache/zkapp-cli/keys/03-deploy.json</strong> respectively.</p>
<h4 id="heading-request-tmina-from-the-faucet">Request tMINA from the Faucet:</h4>
<p>        To fund your fee payer account, request <strong>tMINA</strong> from the faucet:</p>
<ul>
<li><p>Go to the faucet URL: https://faucet.minaprotocol.com</p>
</li>
<li><p>Choose the network (Devnet in this case) and click <strong>Request</strong>.</p>
</li>
</ul>
<p>        Wait for the transaction to be included in the next block, so your fee payer account gets funded.</p>
<h4 id="heading-deploy-the-zkapp">Deploy the zkApp:</h4>
<p>        Once your fee payer account is funded, deploy the zkApp by running:</p>
<pre><code class="lang-plaintext">        bashCopyEdit$ zk deploy
</code></pre>
<ul>
<li><p>When prompted, select the <code>devnet</code> deploy alias.</p>
</li>
<li><p>A <strong>verification key</strong> for your smart contract is generated (it takes 10-30 seconds).</p>
</li>
<li><p>Review and confirm the transaction details:</p>
<ul>
<li><p>Deploy alias: <code>devnet</code></p>
</li>
<li><p>Network: <code>Testnet</code></p>
</li>
<li><p>URL: <code>https://api.minascan.io/node/devnet/v1/graphql</code></p>
</li>
<li><p>Fee payer account: <code>03-deploy</code></p>
</li>
<li><p>zkApp account: <code>Square</code></p>
</li>
<li><p>Transaction fee: <code>0.1 Mina</code></p>
</li>
</ul>
</li>
</ul>
<p>        When prompted, type <strong>yes</strong> to confirm and send the transaction to the network.</p>
<h4 id="heading-after-deployment">After Deployment:</h4>
<p>        Your smart contract will be live (or updated) once the transaction is included in a block. You can view the transaction and zkApp details via the <strong>Minascan</strong> explorer:</p>
<ul>
<li><strong>Transaction Link</strong>: <code>https://minascan.io/devnet/tx/&lt;txn-hash&gt;?type=zk-tx</code></li>
</ul>
<p>        This link shows the deployed zkApp transaction and involved accounts.</p>
<h3 id="heading-success-zkapp-deployed"><strong>Success: zkApp Deployed!</strong></h3>
<p>        Once the transaction is included in a block, your <strong>zkApp</strong> is successfully deployed! Here’s what happens after deployment:</p>
<ul>
<li><p><strong>Verification Key</strong>: The Mina account used to deploy the zkApp now contains the verification key for the smart contract.</p>
</li>
<li><p><strong>Key Pairs</strong>:</p>
<ul>
<li><p>The <strong>fee payer key pair</strong> was created at <code>${HOME}/.cache/zkapp-cli/keys/03-deploy.json</code>.</p>
</li>
<li><p>The <strong>zkApp key pair</strong> was created at <code>keys/devnet.json</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Funding</strong>: You successfully requested <strong>tMINA</strong> to fund your fee payer account and pay for the deploy transaction fees. The remaining tMINA can be used for building and testing.</p>
</li>
<li><p><strong>Deployment Process</strong>:</p>
<ul>
<li><p>You generated a verification key for your smart contract.</p>
</li>
<li><p>The <strong>zk deploy</strong> command sent the deploy transaction to the Mina network.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-next-steps-1"><strong>Next Steps</strong></h3>
<ul>
<li><p>If you want to continue testing, configuring, and deploying your zkApp locally, explore <strong>Testing zkApps with Lightnet</strong>.</p>
<h3 id="heading-smart-contract-transactions-and-proofs"><strong>Smart Contract Transactions and Proofs</strong></h3>
<p>  In this tutorial, the <strong>smart contract</strong> used is from Tutorial 1: Hello World, where permissions are set in a way that <strong>editState</strong> operations require a valid zk proof. Here's how this works:</p>
<ol>
<li><p><strong>Proof Creation</strong>:</p>
<ul>
<li>When a user interacts with the smart contract, they provide a proof that is generated locally on their device using the <strong>private key</strong> associated with the <strong>zkApp account</strong>.</li>
</ul>
</li>
<li><p><strong>Transaction Submission</strong>:</p>
<ul>
<li>The generated proof is included in the transaction when it is submitted to the network. The network checks that the proof is correct and that it matches the <strong>on-chain verification key</strong>.</li>
</ul>
</li>
<li><p><strong>Proof Verification</strong>:</p>
<ul>
<li>Once the transaction is accepted by the network, the proof, along with the transaction, is recursively proven and bundled into Mina's <strong>recursive zero knowledge proof</strong>. This process ensures the integrity and privacy of the transaction.</li>
</ul>
</li>
<li><p><strong>Smart Contract Code Changes</strong>:</p>
<ul>
<li>If you modify the smart contract code, the associated <strong>verification key</strong> will change. You’ll need to follow the same steps to <strong>redeploy</strong> your zkApp with the updated code and key.</li>
</ul>
</li>
</ol>
</li>
</ul>
<h3 id="heading-permissions-for-typical-smart-contracts"><strong>Permissions for Typical Smart Contracts</strong></h3>
<p>            For most smart contracts, permissions are configured to <strong>only allow proof-based authorization</strong>. This means that only valid proofs can interact with the smart contract's state, ensuring privacy and security.</p>
<p>            In <strong>Tutorial 4: Build a zkApp UI in the Browser with React</strong>, you're building a <strong>browser UI</strong> using <strong>Next.js</strong> that interacts with the smart contract you deployed earlier.</p>
<h3 id="heading-steps-overview"><strong>Steps Overview</strong>:</h3>
<ol>
<li><p><strong>Building on Past Tutorials</strong>:</p>
<ul>
<li><p>In <strong>Tutorial 1: Hello World</strong>, you created the zkApp smart contract using <strong>o1js</strong>.</p>
</li>
<li><p>In <strong>Tutorial 3: Deploy to a Live Network</strong>, you deployed the zkApp to a <strong>live network</strong> using <strong>zkApp CLI</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Building the UI</strong>:</p>
<ul>
<li>Now, in this tutorial, you're going to create a <strong>React-based browser UI</strong> using <strong>Next.js</strong> that will interact with your smart contract. The UI will allow users to interact with your smart contract, such as calling its methods and displaying results on the front-end.</li>
</ul>
</li>
</ol>
<h3 id="heading-what-youll-learn"><strong>What You'll Learn</strong>:</h3>
<ul>
<li><p>How to <strong>integrate</strong> the deployed zkApp smart contract with a <strong>Next.js</strong> app.</p>
</li>
<li><p>How to create a <strong>front-end interface</strong> that interacts with the <strong>Mina blockchain</strong> through zkApps.</p>
</li>
</ul>
<p>            By the end of the tutorial, you'll be able to build and deploy a full-stack zkApp with a front-end interface that communicates with your <strong>smart contract on the Mina network</strong></p>
<p>            <strong>Prerequisites:</strong></p>
<ul>
<li><p>Ensure you have the latest zkApp CLI installed using:</p>
<pre><code class="lang-plaintext">  rubyCopyEdit$ npm install -g zkapp-cli
</code></pre>
</li>
<li><p>Ensure your environment meets the prerequisites for zkApp Developer Tutorials.</p>
</li>
<li><p>Install the Auro Wallet browser extension wallet that supports zkApp interactions and create a MINA account.</p>
</li>
</ul>
<p>            <strong>Tested Versions:</strong></p>
<ul>
<li><p>zkApp CLI version: 0.21.6</p>
</li>
<li><p>o1js version: 1.8.0</p>
</li>
<li><p>Auro Wallet version: 2.2.15</p>
<p>  <strong>High-Level Overview:</strong></p>
<p>  In this tutorial, you will:</p>
<ul>
<li><p>Create a new GitHub repository to deploy the UI to GitHub Pages.</p>
</li>
<li><p>Use example code and the zkApp CLI to build an application that:</p>
<ol>
<li><p>Loads a public key from an extension-based wallet.</p>
</li>
<li><p>Checks if the public key has funds; if not, directs the user to the Faucet.</p>
</li>
<li><p>Connects to the example zkApp Add smart contract, deployed on Devnet (or another network) at a fixed address.</p>
</li>
<li><p>Implements a button to send a transaction.</p>
</li>
<li><p>Implements a button to request the latest state of the smart contract.</p>
</li>
<li><p>Deploys the zkApp to GitHub Pages.</p>
</li>
</ol>
</li>
</ul>
</li>
</ul>
<p>                <strong>Create a project:</strong></p>
<ol>
<li><p>Change to a directory with write privileges.</p>
</li>
<li><p>Create a project using the <code>zk project</code> command:</p>
<pre><code class="lang-plaintext"> bashCopyEdit$ zk project 04-zkapp-browser-ui
</code></pre>
</li>
<li><p>When prompted, select <code>next</code> to scaffold the UI using the Next.js React framework:</p>
<pre><code class="lang-plaintext"> sqlCopyEdit? Create an accompanying UI project too? …
 &gt; next
 svelte
 nuxt
 empty
 none
</code></pre>
</li>
<li><p>If prompted to install the required Next packages, press <code>y</code> to proceed.</p>
</li>
<li><p>Select <code>yes</code> for the prompt: <code>Do you want to set up your project for deployment to Github Pages?</code></p>
</li>
<li><p>If prompted, press <code>y</code> to install the required packages.</p>
</li>
<li><p>For the prompts:</p>
<ul>
<li><p>Select <code>No</code> for: <code>Would you like to use ESLint with this project?</code></p>
</li>
<li><p>Select <code>No</code> for: <code>Would you like to use Tailwind CSS with this project?</code></p>
</li>
</ul>
</li>
<li><p>Your UI is created in the <code>04-zkapp-browser-ui/ui</code> directory, with two subdirectories:</p>
<ul>
<li><p><code>contracts</code>: Contains the smart contract code.</p>
</li>
<li><p><code>ui</code>: Where you will write the UI code.</p>
</li>
</ul>
</li>
<li><p>For this tutorial, run commands from the root of the <code>04-zkapp-browser-ui/ui</code> directory, and work in the <code>ui/app</code> directory on TypeScript files for the UI code.</p>
</li>
<li><p>Each time you make updates, the TypeScript code is compiled into JavaScript in the build directory.</p>
</li>
</ol>
<p>                <strong>Install the dependencies:</strong></p>
<p>                When you ran the <code>zk project</code> command, your UI was created in the <code>04-zkapp-browser-ui/ui</code> directory. This project has two subdirectories:</p>
<ul>
<li><p><code>contracts</code>: Contains the smart contract code.</p>
</li>
<li><p><code>ui</code>: Contains the UI application code.</p>
</li>
</ul>
<p>                The dependencies for both the <strong>contracts</strong> and <strong>ui</strong> subdirectories are automatically installed by the <code>zkApp CLI</code>. No additional installation steps are required for dependencies in these subdirectories.</p>
<p>                <strong>Create a Repository:</strong></p>
<p>                To interact with a deployed zkApp UI on GitHub Pages, you'll need to create a GitHub repository.</p>
<ol>
<li><p>Go to <a target="_blank" href="https://github.com/new">https://github.com/new</a>.</p>
</li>
<li><p>For the <strong>Repository name</strong>, enter <code>04-zkapp-browser-ui</code>.</p>
</li>
<li><p>Optionally, add a description and a README.</p>
</li>
</ol>
<p>                Your project repository is now ready to use!</p>
<p>                <strong>Preparing the Project:</strong></p>
<ol>
<li><p>In the <code>04-zkapp-browser-ui/ui</code> directory, delete the default <code>page.tsx</code> file to start with a clean project:</p>
<pre><code class="lang-plaintext"> bashCopyEdit$ rm app/page.tsx
</code></pre>
</li>
</ol>
<p>        In the <code>04-zkapp-browser-ui/ui</code> directory, install the <code>comlink</code> package to integrate web workers into the React application. This simplifies communication between the main thread and web workers by abstracting the postMessage API, allowing functions in the worker to be called as if they were local. Install it with:</p>
<pre><code class="lang-plaintext">        bashCopyEdit$ npm install comlink
</code></pre>
<p>        For more information, refer to the documentation.</p>
<p>        Download the helper files from the <code>examples/zkapps/04-zkapp-browser-ui</code> directory on GitHub:</p>
<ul>
<li><p><code>zkappWorker.ts</code>: Web worker code.</p>
</li>
<li><p><code>zkappWorkerClient.ts</code>: Client code to interact with the web worker from React.</p>
</li>
</ul>
<p>        Move these files to your local <code>04-zkapp-browser-ui/ui/app</code> directory.</p>
<p>        Review the files to understand how they work and how you can extend them for your zkApp. Web workers handle computational tasks to ensure the UI thread is not blocked during long computations like compiling a smart contract or proving a transaction.</p>
<h3 id="heading-steps-to-download-and-move-pagetsx"><strong>Steps to Download and Move</strong> <code>page.tsx</code>:</h3>
<ol>
<li><p><strong>Download the</strong> <code>page.tsx</code> example file</p>
<ul>
<li><p>If the file is hosted on a specific URL, download it using:</p>
<pre><code class="lang-plaintext">  shCopyEditwget &lt;URL_TO_PAGE_TSX&gt;
</code></pre>
</li>
<li><p>If provided as a ZIP or GitHub repo, clone or extract the file.</p>
</li>
</ul>
</li>
<li><p><strong>Move</strong> <code>page.tsx</code> to the correct directory<br /> Run the following command in your terminal to place it in your zkApp project:</p>
<pre><code class="lang-plaintext"> shCopyEditmv path/to/downloaded/page.tsx 04-zkapp-browser-ui/ui/app/
</code></pre>
</li>
<li><p><strong>Verify the file location</strong><br /> Navigate to the directory and confirm the file is there:</p>
<p> Build the default <code>Add</code> contract, which is always scaffolded with the <code>zk project</code> command.</p>
<p> To make the contract usable with the UI application, run the following command from the <code>04-zkapp-browser-ui/contracts</code> directory:</p>
<pre><code class="lang-plaintext"> arduinoCopyEdit$ npm run build
</code></pre>
<p> Outside this tutorial, the standard workflow involves modifying files in the <code>contracts</code> folder, rebuilding the contract, and then integrating it into the UI application code.</p>
<h2 id="heading-implement-the-ui">Implement the UI</h2>
<p> The UI application consists of multiple components, including the React page and the code that interacts with <code>o1js</code>.</p>
</li>
</ol>
<h3 id="heading-setup-web-workers">Setup web workers</h3>
<p>        The web worker code is located in the <code>04-zkapp-browser-ui/ui/app/zkappWorker.ts</code> file, where functions to be executed in the worker thread are defined.</p>
<h4 id="heading-defining-state">Defining State</h4>
<p>        The <code>state</code> object manages references to the zkApp instance, the <code>Add</code> contract instance, and transactions:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditconst state = {
          AddInstance: null as null | typeof Add,
          zkappInstance: null as null | Add,
          transaction: null as null | Transaction,
        };
</code></pre>
<h1 id="heading-defining-functions-that-will-run-in-the-worker-thread">Defining functions that will run in the worker thread</h1>
<p>        The <code>api</code> object defines functions that run in the web worker thread, handling tasks such as network setup, smart contract loading and compiling, account fetching, contract interactions, and transaction management:</p>
<pre><code class="lang-plaintext">        typescriptCopyEditexport const api = {
          async setActiveInstanceToDevnet() {
            const Network = Mina.Network('https://api.minascan.io/node/devnet/v1/graphql');
            console.log('Devnet network instance configured');
            Mina.setActiveInstance(Network);
          },
          async loadContract() {
            const { Add } = await import('../../contracts/build/src/Add.js');
            state.AddInstance = Add;
          },
          async compileContract() {
            await state.AddInstance!.compile();
          },
          async fetchAccount(publicKey58: string) {
            const publicKey = PublicKey.fromBase58(publicKey58);
            return fetchAccount({ publicKey });
          },
          async initZkappInstance(publicKey58: string) {
            const publicKey = PublicKey.fromBase58(publicKey58);
            state.zkappInstance = new state.AddInstance!(publicKey);
          },
          async getNum() {
            const currentNum = await state.zkappInstance!.num.get();
            return JSON.stringify(currentNum.toJSON());
          },
          async createUpdateTransaction() {
            state.transaction = await Mina.transaction(async () =&gt; {
              await state.zkappInstance!.update();
            });
          },
          async proveUpdateTransaction() {
            await state.transaction!.prove();
          },
          async getTransactionJSON() {
            return state.transaction!.toJSON();
          },
        };
</code></pre>
<h4 id="heading-expose-functions-to-the-main-thread-with-comlinkhttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactexpose-functions-to-the-main-thread-with-comlink">Expose functions to the main thread with <code>comlink</code><a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#expose-functions-to-the-main-thread-with-comlink">​</a></h4>
<pre><code class="lang-plaintext">        // Expose the API to be used by the main thread
        Comlink.expose(api);
</code></pre>
<p>        Creating the worker client<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client">​</a></p>
<ul>
<li><p>The web worker client code r<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client">e</a>sides in the <code>04-zkapp-browser-ui/ui/app/zkappWorkerClient.ts</code> file. Here you create a client in the main thread that interacts with the web worker.</p>
</li>
<li><p><code>worker</code> is a reference to the web worker instance and <code>remoteApi</code> is a reference to a proxy object that provides typesafe access to the worker's API methods.</p>
</li>
</ul>
<pre><code class="lang-plaintext">        export default class ZkappWorkerClient {
          worker: Worker;
          // Proxy to interact with the worker's methods as if they were local
          remoteApi: Comlink.Remote&lt;typeof import('./zkappWorker').api&gt;;
</code></pre>
<p>        In the constructor create a <a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client">n</a>ew Worker instance pointing to the <code>zkappWorker.ts</code> file.</p>
<pre><code class="lang-plaintext">        constructor() {
          // Initialize the worker from the zkappWorker module
          const worker = new Worker(new URL('./zkappWorker.ts', import.meta.url), { type: 'module' });
</code></pre>
<p>        With <code>Comlink.wrap</code>, create a <a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client">p</a>roxy object <code>remoteApi</code> that provides typesafe access the worker's API methods.</p>
<pre><code class="lang-plaintext">          // Wrap the worker with Comlink to enable direct method invocation
          this.remoteApi = Comlink.wrap(this.worker);
</code></pre>
<p>        Define methods in the ZkappW<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#creating-the-worker-client">o</a>rkerClient class that call the corresponding method on <code>remoteApi</code>, effectively forwarding the calls to the worker.</p>
<pre><code class="lang-plaintext">        async setActiveInstanceToDevnet() {
            return this.remoteApi.setActiveInstanceToDevnet();
          }

          async loadContract() {
            return this.remoteApi.loadContract();
          }

          async compileContract() {
            return this.remoteApi.compileContract();
          }

          async fetchAccount(publicKeyBase58: string) {
            return this.remoteApi.fetchAccount(publicKeyBase58);
          }

          async initZkappInstance(publicKeyBase58: string) {
            return this.remoteApi.initZkappInstance(publicKeyBase58);
          }

          async getNum(): Promise&lt;Field&gt; {
            const result = await this.remoteApi.getNum();
            return Field.fromJSON(JSON.parse(result as string));
          }

          async createUpdateTransaction() {
            return this.remoteApi.createUpdateTransaction();
          }

          async proveUpdateTransaction() {
            return this.remoteApi.proveUpdateTransaction();
          }

          async getTransactionJSON() {
            return this.remoteApi.getTransactionJSON();
          }
</code></pre>
<p>        The environment configuration ensures the UI interacts with the correct zkApp deployed on Devnet.</p>
<ul>
<li><p>In <code>page.tsx</code>, <code>ZKAPP_ADDRESS</code> holds the public key of the deployed smart contract. Users can deploy their own contract and update this variable if needed.</p>
</li>
<li><p>In <code>zkappWorker.ts</code>, <code>setActiveInstanceToDevnet()</code> configures the network instance using Mina’s Devnet GraphQL endpoint. If switching networks, update the endpoint accordingly while ensuring compatibility with Auro Wallet.</p>
</li>
</ul>
<p>        In this example, the o1js code runs on the client side within a client component after the page loads. If integrating o1js into a server component, Next.js's caching could lead to outdated data being returned. To prevent this, you can disable caching by adding <code>export const revalidate = 0;</code> to your component. For further details, check the Next.js caching documentation.</p>
<h3 id="heading-add-statehttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactadd-state">Add state<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#add-state">​</a></h3>
<p>        The following statements in <code>04-zkapp-browser-ui/ui/app/page.tsx</code> create mutable state to track various aspects of the UI, which updates as the application runs:</p>
<pre><code class="lang-plaintext">        tsxCopyEditconst [zkappWorkerClient, setZkappWorkerClient] = useState&lt;null | ZkappWorkerClient&gt;(null);
        const [hasWallet, setHasWallet] = useState&lt;null | boolean&gt;(null);
        const [hasBeenSetup, setHasBeenSetup] = useState(false);
        const [accountExists, setAccountExists] = useState(false);
        const [currentNum, setCurrentNum] = useState&lt;null | Field&gt;(null);
        const [publicKeyBase58, setPublicKeyBase58] = useState('');
        const [creatingTransaction, setCreatingTransaction] = useState(false);
        const [displayText, setDisplayText] = useState('');
        const [transactionlink, setTransactionLink] = useState('');
</code></pre>
<p>        These hooks track the state values, which can be referenced and updated as the application runs.</p>
<p>        For more information on <code>useState</code>, refer to the React API reference documentation on built-in hooks.</p>
<h3 id="heading-zkapp-setting-uphttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactzkapp-setting-up">zkApp setting up<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#zkapp-setting-up">​</a></h3>
<p>        This <code>04-zkapp-brow</code><a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance"><code>s</code></a><code>er-ui/ui/app/page.tsx</code> code adds a functions to set up zkApp:</p>
<ul>
<li><p>The Boolean <code>hasBee</code><a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance"><code>n</code></a><code>Setup</code> ensures that the react feature <code>use</code><a target="_blank" href="https://react.dev/reference/react/useEffect"><code>Effect</code> is</a> run only o<a target="_blank" href="https://react.dev/reference/react/useEffect">nce. To l</a>earn more about <code>useEffect</code> hooks, see <a target="_blank" href="https://react.dev/reference/react/useEffect">useEffect</a> in the React API reference <a target="_blank" href="https://react.dev/reference/react/useEffect">documenta</a>tion.</p>
</li>
<li><p>This code also set<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance">s</a> up your web worker client that interacts with the web worker running o1js code to ensure the computationally heavy o1js code doesn't block the <a target="_blank" href="https://react.dev/reference/react/useEffect">UI threa</a>d.</p>
</li>
</ul>
<h4 id="heading-load-web-worker-andhttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactload-web-worker-and-setup-mina-active-instance-setup-mina-active-instancehttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactload-web-worker-and-setup-mina-active-instance">Load web worker an<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance">d</a> setup Mina active instance<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#load-web-worker-and-setup-mina-active-instance">​</a></h4>
<pre><code class="lang-plaintext">        ...
          displayStep('Loading web worker...')
          const zkappWorkerClient = new ZkappWorkerClient();
          setZkappWorkerClient(zkappWorkerClient);
          await new Promise((resolve) =&gt; setTimeout(resolve, 5000));
          displayStep('Done loading web worker')

          await zkappWorkerClient.setActiveInstanceToDevnet();
        ...
</code></pre>
<p>        The code in <code>04-zkapp-browser-ui/ui/app/page.tsx</code> connects to Auro Wallet and sets up the fee payer account as follows:</p>
<ul>
<li><p>It checks if the <code>mina</code> object is available (from Auro Wallet).</p>
</li>
<li><p>If not, it sets <code>hasWallet</code> to <code>false</code> and displays an error message.</p>
</li>
<li><p>If Auro Wallet is found, it retrieves the public key using <code>mina.requestAccounts()</code>.</p>
</li>
<li><p>The public key is displayed and stored in <code>publicKeyBase58</code>.</p>
</li>
<li><p>It then checks if the fee payer account exists by calling <code>zkappWorkerClient.fetchAccount(publicKeyBase58)</code>.</p>
</li>
<li><p>The result (<code>accountExists</code>) is updated based on whether the account exists or not.</p>
</li>
</ul>
<pre><code class="lang-plaintext">        tsxCopyEditconst mina = (window as any).mina;
        if (mina == null) {
          setHasWallet(false);
          displayStep('Wallet not found.');
          return;
        }

        const publicKeyBase58: string = (await mina.requestAccounts())[0];
        setPublicKeyBase58(publicKeyBase58);
        displayStep(`Using key:${publicKeyBase58}`);

        displayStep('Checking if fee payer account exists...');
        const res = await zkappWorkerClient.fetchAccount(publicKeyBase58);
        const accountExists = res.error === null;
        setAccountExists(accountExists);
</code></pre>
<p>        The code in <code>04-zkapp-browser-ui/ui/app/page.tsx</code> imports the contract code, instantiates the zkApp instance, compiles the contract, and fetches the zkApp state as follows:</p>
<ol>
<li><p>It loads the contract using <code>zkappWorkerClient.loadContract()</code>.</p>
</li>
<li><p>The contract is compiled with <code>zkappWorkerClient.compileContract()</code>, and a message is displayed.</p>
</li>
<li><p>The zkApp instance is initialized with the deployed <code>ZKAPP_ADDRESS</code> using <code>zkappWorkerClient.initZkappInstance(ZKAPP_ADDRESS)</code>.</p>
</li>
<li><p>It fetches the current state of the zkApp by calling <code>zkappWorkerClient.fetchAccount(ZKAPP_ADDRESS)</code> and retrieves the current number from the zkApp with <code>zkappWorkerClient.getNum()</code>.</p>
</li>
<li><p>The retrieved state (<code>currentNum</code>) is stored in <code>currentNum</code> and logged to the console.</p>
</li>
</ol>
<pre><code class="lang-plaintext">        tsxCopyEditawait zkappWorkerClient.loadContract();

        displayStep('Compiling zkApp...');
        await zkappWorkerClient.compileContract();
        displayStep('zkApp compiled');

        await zkappWorkerClient.initZkappInstance(ZKAPP_ADDRESS);

        displayStep('Getting zkApp state...');
        await zkappWorkerClient.fetchAccount(ZKAPP_ADDRESS);
        const currentNum = await zkappWorkerClient.getNum();
        setCurrentNum(currentNum);
        console.log(`Current state in zkApp: ${currentNum}`);
</code></pre>
<p>        The state of the React application is updated as follows:</p>
<p>        The state of the React application is updated as follows:</p>
<ol>
<li><p>The <code>hasBeenSetup</code> state is set to <code>true</code> to indicate that the setup process is complete.</p>
</li>
<li><p>The <code>hasWallet</code> state is set to <code>true</code>, confirming that the wallet is found and connected.</p>
</li>
<li><p>The <code>displayText</code> state is reset to an empty string, likely to clear any previous messages shown during setup.</p>
</li>
</ol>
<pre><code class="lang-plaintext">        tsxCopyEditsetHasBeenSetup(true);
        setHasWallet(true);
        setDisplayText('');
</code></pre>
<h3 id="heading-run-the-react-app">Run the React app</h3>
<p>        o run the React app, follow these steps:</p>
<ol>
<li><p><strong>Start the development server</strong> in the <code>04-zkapp-browser-ui/ui/</code> directory:</p>
<pre><code class="lang-plaintext"> bashCopyEdit$ npm run dev
</code></pre>
<p> This will serve your UI application at <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a>.</p>
</li>
<li><p><strong>Change the default port</strong> by specifying the <code>--port</code> argument. For example, to run it on port 8001:</p>
<pre><code class="lang-plaintext"> bashCopyEdit$ npm run dev -- --port 8001
</code></pre>
</li>
<li><p><strong>Interacting with the app</strong>:</p>
<ul>
<li><p>The zkApp UI in the browser will display the current state of the zkApp.</p>
</li>
<li><p>It includes buttons for sending a transaction and fetching the latest on-chain state of the zkApp.</p>
</li>
<li><p>The browser will refresh automatically when the source code is updated.</p>
</li>
</ul>
</li>
<li><p><strong>Faucet Request</strong>: If prompted, request funds from the Testnet Faucet service to fund your fee payer account.</p>
</li>
<li><p><strong>Start TypeScript watch mode</strong>: In a second terminal window, run the following command to start the TypeScript compiler in watch mode:</p>
<pre><code class="lang-plaintext"> bashCopyEdit$ npm run ts-watch
</code></pre>
<p> This allows the TypeScript compiler to react to any changes in the code.</p>
</li>
</ol>
<h3 id="heading-wait-for-the-fee-payer-account-to-be-fundedhttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactwait-for-the-fee-payer-account-to-be-funded">Wait for the fee payer account to be funded<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded">​</a></h3>
<p>        Now that the UI setup is finished, a new useE<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded">f</a>fect waits for the fee payer account to be funded if it didn't before by checking the account presence in ledger.</p>
<p>        Don't forget that if the account has been new<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#wait-for-the-fee-payer-account-to-be-funded">l</a>y created, it must be funded from the Faucet.</p>
<pre><code class="lang-plaintext">        ...
          useEffect(() =&gt; {
            const checkAccountExists = async () =&gt; {
              if (hasBeenSetup &amp;&amp; !accountExists) {
                try { 
                  for (;;) {
                    displayStep('Checking if fee payer account exists...');

                    const res = await zkappWorkerClient!.fetchAccount(publicKeyBase58);
                    const accountExists = res.error == null;
                    if (accountExists) {
                      break;
                    }
                    await new Promise((resolve) =&gt; setTimeout(resolve, 5000));
                  } 
                } catch (error: any) {
                  displayStep(`Error checking account: ${error.message}`);
                }

              }
              setAccountExists(true);
            };

            checkAccountExists();
          }, [zkappWorkerClient, hasBeenSetup, accountExists]); 
        ...
</code></pre>
<h3 id="heading-let-ui-buttons-do-some-useful-workhttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reactlet-ui-buttons-do-some-useful-work">Let UI buttons do some useful work<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#let-ui-buttons-do-some-useful-work">​</a></h3>
<p>        These functions will be triggered on buttons press.</p>
<pre><code class="lang-plaintext">        ...
          const onSendTransaction = async () =&gt; {
            setCreatingTransaction(true);
            displayStep('Creating a transaction...');

            console.log('publicKeyBase58 sending to worker', publicKeyBase58);
            await zkappWorkerClient!.fetchAccount(publicKeyBase58);

            await zkappWorkerClient!.createUpdateTransaction();

            displayStep('Creating proof...');
            await zkappWorkerClient!.proveUpdateTransaction();

            displayStep('Requesting send transaction...');
            const transactionJSON = await zkappWorkerClient!.getTransactionJSON();

            displayStep('Getting transaction JSON...');
            const { hash } = await (window as any).mina.sendTransaction({
              transaction: transactionJSON,
              feePayer: {
                fee: transactionFee,
                memo: '',
              },
            });

            const transactionLink = `https://minascan.io/devnet/tx/${hash}`;
            setTransactionLink(transactionLink);
            setDisplayText(transactionLink);

            setCreatingTransaction(true);
          };

          const onRefreshCurrentNum = async () =&gt; {
            try {
              displayStep('Getting zkApp state...');
              await zkappWorkerClient!.fetchAccount(ZKAPP_ADDRESS);
              const currentNum = await zkappWorkerClient!.getNum();
              setCurrentNum(currentNum);
              console.log(`Current state in zkApp: ${currentNum}`);
              setDisplayText('');
            } catch (error: any) {
              displayStep(`Error refreshing state: ${error.message}`);
            }
          };
</code></pre>
<h3 id="heading-take-care-of-the-page-markuphttpsdocsminaprotocolcomzkappstutorialszkapp-ui-with-reacttake-care-of-the-page-markup">Take care of the page markup<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/zkapp-ui-with-react#take-care-of-the-page-markup">​</a></h3>
<pre><code class="lang-plaintext">        ...
          let auroLinkElem;
          if (hasWallet === false) {
            const auroLink = 'https://www.aurowallet.com/';
            auroLinkElem = (
              &lt;div&gt;
                Could not find a wallet.{' '}
                &lt;a href="https://www.aurowallet.com/" target="_blank" rel="noreferrer"&gt;
                  Install Auro wallet here
                &lt;/a&gt;
              &lt;/div&gt;
            );
          }

          const stepDisplay = transactionlink ? (
            &lt;a
              href={transactionlink}
              target="_blank"
              rel="noreferrer"
              style={{ textDecoration: 'underline' }}
            &gt;
              View transaction
            &lt;/a&gt;
          ) : (
            displayText
          );

          let setup = (
            &lt;div
              className={styles.start}
              style={{ fontWeight: 'bold', fontSize: '1.5rem', paddingBottom: '5rem' }}
            &gt;
              {stepDisplay}
              {auroLinkElem}
            &lt;/div&gt;
          );

          let accountDoesNotExist;
          if (hasBeenSetup &amp;&amp; !accountExists) {
            const faucetLink =
              `https://faucet.minaprotocol.com/?address='${publicKeyBase58}`;
            accountDoesNotExist = (
              &lt;div&gt;
                &lt;span style={{ paddingRight: '1rem' }}&gt;Account does not exist.&lt;/span&gt;
                &lt;a href={faucetLink} target="_blank" rel="noreferrer"&gt;
                  Visit the faucet to fund this fee payer account
                &lt;/a&gt;
              &lt;/div&gt;
            );
          }

          let mainContent;
          if (hasBeenSetup &amp;&amp; accountExists) {
            mainContent = (
              &lt;div style={{ justifyContent: 'center', alignItems: 'center' }}&gt;
                &lt;div className={styles.center} style={{ padding: 0 }}&gt;
                  Current state in zkApp: {currentNum?.toString()}{' '}
                &lt;/div&gt;
                &lt;button
                  className={styles.card}
                  onClick={onSendTransaction}
                  disabled={creatingTransaction}
                &gt;
                  Send Transaction
                &lt;/button&gt;
                &lt;button className={styles.card} onClick={onRefreshCurrentNum}&gt;
                  Get Latest State
                &lt;/button&gt;
              &lt;/div&gt;
            );
          }

          return (
            &lt;GradientBG&gt;
              &lt;div className={styles.main} style={{ padding: 0 }}&gt;
                &lt;div className={styles.center} style={{ padding: 0 }}&gt;
                  {setup}
                  {accountDoesNotExist}
                  {mainContent}
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/GradientBG&gt;
          );
</code></pre>
<p>        The UI has three sections:</p>
<ol>
<li><p><strong>setup</strong>: Informs the user when the zkApp has finished loading.</p>
</li>
<li><p><strong>accountDoesNotExist</strong>: Provides a link to the Faucet if the user's account hasn't been funded yet.</p>
</li>
<li><p><strong>mainContent</strong>: Displays the current zkApp on-chain state and provides buttons for users to interact with the zkApp. These buttons let users create transactions to update the on-chain zkApp state and refresh the current state.</p>
</li>
</ol>
<p>        Once the code is set up, you can interact with the UI application at <a target="_blank" href="http://localhost:3000"><code>localhost:3000</code></a> if you’re running it with <code>npm run dev</code>.</p>
<p>        To deploy the application to GitHub Pages, follow these steps:</p>
<ol>
<li><p><strong>Push the project to GitHub</strong>: First, ensure that your project is pushed to the GitHub repository you created at the beginning of the tutorial. The repository name must match the project name (<code>04-zkapp-browser-ui</code>).</p>
</li>
<li><p><strong>Verify project name consistency</strong>: Ensure the GitHub repository name matches your project name. The <code>zk project</code> command has already set the project name in the <code>next.config.js</code> and <code>src/pages/reactCOIServiceWorker.ts</code> files.</p>
</li>
</ol>
<p>        After confirming the project is correctly set up and pushed to GitHub, you can proceed with deploying it to GitHub Pages.</p>
<p>        To deploy your UI to GitHub Pages:</p>
<ol>
<li><p><strong>Navigate to the UI directory</strong>: Change to the <code>04-zkapp-browser-ui/ui/</code> directory.</p>
<pre><code class="lang-plaintext"> bashCopyEditcd 04-zkapp-browser-ui/ui/
</code></pre>
</li>
<li><p><strong>Run the deploy script</strong>: Execute the following command to deploy your UI to GitHub Pages.</p>
<pre><code class="lang-plaintext"> bashCopyEditnpm run deploy
</code></pre>
<p> This script builds your application and automatically publishes it to GitHub Pages.</p>
</li>
<li><p><strong>Access the deployed zkApp UI</strong>: After the deployment is complete, your zkApp UI will be available at the following URL:</p>
<pre><code class="lang-plaintext"> cppCopyEdithttps://&lt;username&gt;.github.io/04-zkapp-browser-ui/
</code></pre>
<p> Replace <code>&lt;username&gt;</code> with your GitHub username.</p>
<h1 id="heading-tutorial-5-common-types-and-functions">Tutorial 5: Common Types and Functions</h1>
<p> In previous tutorials, you learned how to deploy smart contracts to the network interact with them from a React UI and NodeJS.</p>
<p> In this tutorial, you learn about types you can use when building with o1js. Earlier tutorials mostly use the <code>Field</code> type. o1js provides other higher-order types built from Fields that are useful for zkApp development and expand the possibilities for more applications.</p>
<p> The <a target="_blank" href="https://github.com/o1-labs/docs2/tree/main/examples/zkapps/05-common-types-and-functions/src">example project</a> includes a <a target="_blank" href="https://github.com/o1-labs/docs2/blob/main/examples/zkapps/05-common-types-and-functions/src/main.ts">main.ts</a> file that shows all of the concepts presented in this tutorial, along with smart contracts showing more advanced usage of some of the concepts, particularly Merkle Trees.</p>
<p> <strong>Prerequisites</strong>:</p>
<ul>
<li><p>zkApp CLI version 0.20.1</p>
</li>
<li><p>o1js version 1.1.0</p>
</li>
</ul>
</li>
</ol>
<p>            Ensure your environment is set up according to the zkApp Developer Tutorials prerequisites.</p>
<h2 id="heading-basic-types">Basic Types</h2>
<p>            In this section, five basic types are introduced, all derived from Fields. These types are:</p>
<ul>
<li><p><code>Bool</code></p>
</li>
<li><p><code>UInt32</code></p>
</li>
<li><p><code>UInt64</code></p>
</li>
<li><p><code>Int64</code></p>
</li>
<li><p><code>Character</code></p>
</li>
</ul>
<p>            Each type follows standard programming language semantics. Here's an example with different types:</p>
<ul>
<li><p><strong>UInt32 and UInt64</strong>:</p>
<ul>
<li><p><code>num1</code> is created as a <code>UInt32</code> with the value 40.</p>
</li>
<li><p><code>num2</code> is created as a <code>UInt64</code> with the same value.</p>
</li>
<li><p>A comparison is made between <code>num1</code> and <code>num2</code>, resulting in <code>num1EqualsNum2</code> being <code>true</code> as the values are equal after conversion.</p>
</li>
</ul>
</li>
<li><p><strong>Int64</strong>:</p>
<ul>
<li><p><code>signedNum1</code> and <code>signedNum2</code> are created with values -3 and 45, respectively.</p>
</li>
<li><p>The sum of these two numbers is computed, resulting in 42.</p>
</li>
</ul>
</li>
<li><p><strong>Character</strong>:</p>
<ul>
<li><p><code>char1</code> is created from the string 'c', and <code>char2</code> from 'd'.</p>
</li>
<li><p>A comparison between <code>char1</code> and <code>char2</code> returns <code>false</code> because they are different characters.</p>
</li>
</ul>
</li>
</ul>
<p>            <strong>Output of the code</strong>:</p>
<pre><code class="lang-plaintext">            yamlCopyEditnum1 === num2: true
            Fields in num1: 1
            signedNum1 + signedNum2: 42
            Fields in signedNum1: 2
            char1: c
            char1 === char2: false
            Fields in char1: 1
</code></pre>
<h2 id="heading-more-advanced-types">More Advanced Types</h2>
<p>        This section introduces four advanced types:</p>
<ul>
<li><p><code>CircuitString</code></p>
</li>
<li><p><code>PrivateKey</code></p>
</li>
<li><p><code>PublicKey</code></p>
</li>
<li><p><code>Signature</code></p>
</li>
</ul>
<h3 id="heading-key-points-1">Key Points:</h3>
<ul>
<li><p><strong>CircuitString</strong>:</p>
<ul>
<li><p>The default <code>CircuitString</code> has a maximum length of 128 characters, but it can be treated like a dynamic-length string. You can create custom types to modify the length.</p>
</li>
<li><p>Example:</p>
<pre><code class="lang-plaintext">  javascriptCopyEditconst str1 = CircuitString.fromString('abc..xyz');
  console.log(`str1: ${str1}`);
  console.log(`Fields in str1: ${CircuitString.toFields(str1).length}`);
</code></pre>
</li>
</ul>
</li>
<li><p><strong>PrivateKey and PublicKey</strong>:</p>
<ul>
<li><p>A <code>PrivateKey</code> can be generated randomly, and its corresponding <code>PublicKey</code> can be derived from it.</p>
</li>
<li><p>Example:</p>
<pre><code class="lang-plaintext">  javascriptCopyEditconst zkAppPrivateKey = PrivateKey.random();
  const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Signature</strong>:</p>
<ul>
<li><p>Signatures are created using the <code>PrivateKey</code> and verified against the <code>PublicKey</code>.</p>
</li>
<li><p>Example:</p>
<pre><code class="lang-plaintext">  javascriptCopyEditconst signature = Signature.create(zkAppPrivateKey, data2);
  const verifiedData1 = signature.verify(zkAppPublicKey, data1).toString();
  const verifiedData2 = signature.verify(zkAppPublicKey, data2).toString();
</code></pre>
</li>
</ul>
</li>
</ul>
<h3 id="heading-output">Output:</h3>
<pre><code class="lang-plaintext">        vbnetCopyEditstr1: abc..xyz
        Fields in str1: 128
        private key: EKF714j3wgH3tuuQncL93ruQFbJGnhDzfWossAHUp15PdATKE7Ka
        public key: B62qrhsTdExJDAxQx76V1mc13ibzikpmNaNRShTG3MWedCXESBhQ2Ch
        Fields in private key: 2
        Fields in public key: 2
        signature verified for data1: false
        signature verified for data2: true
        Fields in signature: 3
</code></pre>
<h3 id="heading-notes">Notes:</h3>
<ul>
<li><p><strong>Private Key Security</strong>: Never expose private keys in real applications.</p>
</li>
<li><p><strong>Field Sizes</strong>: A private key has 255 Fields, and a signature has 256 Fields due to cryptographic reasons related to elliptic curve scalars.</p>
</li>
</ul>
<h3 id="heading-struct">Struct</h3>
<p>        You can create custom compound data types using the <code>Struct</code> type in o1js. This allows you to define data structures that combine different data types (e.g., <code>Field</code>, higher-order types, or other <code>Struct</code> types). Additionally, you can define methods for these <code>Struct</code> types to operate on their data.</p>
<p>        In o1js, data structures need to be fixed-size because programs are compiled into circuits that must handle static-sized data.</p>
<h3 id="heading-example-1-point-structure-and-addition-method">Example 1: Point Structure and Addition Method</h3>
<pre><code class="lang-plaintext">        javascriptCopyEditclass Point extends Struct({ x: Field, y: Field }) {
          static add(a: Point, b: Point) {
            return { x: a.x.add(b.x), y: a.y.add(b.y) };
          }
        }

        const point1 = { x: Field(10), y: Field(4) };
        const point2 = { x: Field(1), y: Field(2) };

        const pointSum = Point.add(point1, point2);

        console.log(`pointSum Fields: ${Point.toFields(pointSum)}`);
</code></pre>
<h3 id="heading-example-2-points8-structure-array-of-8-points">Example 2: Points8 Structure (Array of 8 Points)</h3>
<pre><code class="lang-plaintext">        javascriptCopyEditclass Points8 extends Struct({
          points: [Point, Point, Point, Point, Point, Point, Point, Point],
        }) {}

        const points = new Array(8)
          .fill(null)
          .map((_, i) =&gt; ({ x: Field(i), y: Field(i * 10) }));
        const points8: Points8 = { points };

        console.log(`points8 JSON: ${JSON.stringify(points8)}`);
</code></pre>
<h3 id="heading-console-output">Console Output:</h3>
<pre><code class="lang-plaintext">        cssCopyEditpointSum Fields: 11,6
        points8 Fields: {"points":[{"x":"0","y":"0"},{"x":"1","y":"10"},{"x":"2","y":"20"},{"x":"3","y":"30"},{"x":"4","y":"40"},{"x":"5","y":"50"},{"x":"6","y":"60"},{"x":"7","y":"70"}]}
</code></pre>
<h3 id="heading-explanation">Explanation:</h3>
<ul>
<li><p><strong>Point Structure</strong>: A <code>Point</code> is defined as a <code>Struct</code> with two fields (<code>x</code> and <code>y</code>), both of which are of type <code>Field</code>. The <code>add</code> method adds the <code>x</code> and <code>y</code> values of two <code>Point</code> objects.</p>
</li>
<li><p><strong>Points8 Structure</strong>: The <code>Points8</code> structure is an array of 8 <code>Point</code> objects. The <code>points</code> array is fixed in size, as required for o1js programs.</p>
</li>
</ul>
<p>        This demonstrates how to use <code>Struct</code> to build more complex data types that are compatible with zkApps.</p>
<h3 id="heading-control-flow-in-o1js">Control Flow in o1js</h3>
<p>        o1js provides two main functions for control flow in zkApps:</p>
<ol>
<li><p><strong>Provable.if</strong>: Similar to a ternary operator in JavaScript. It allows conditional execution based on a test condition.</p>
</li>
<li><p><strong>Provable.switch</strong>: Similar to a switch-case statement in JavaScript. It evaluates multiple conditions and returns the corresponding value.</p>
</li>
</ol>
<p>        Both functions help manage control flow inside zkApps when building logic that needs conditional execution.</p>
<h3 id="heading-example-1-using-provableif">Example 1: Using <code>Provable.if</code></h3>
<pre><code class="lang-plaintext">        javascriptCopyEditconst input1 = Int64.from(10);
        const input2 = Int64.from(-15);

        const inputSum = input1.add(input2);

        const inputSumAbs = Provable.if(
          inputSum.isPositive(),
          inputSum,
          inputSum.mul(Int64.minusOne)
        );

        console.log(`inputSum: ${inputSum.toString()}`);
        console.log(`inputSumAbs: ${inputSumAbs.toString()}`);
</code></pre>
<h3 id="heading-example-2-using-provableswitch">Example 2: Using <code>Provable.switch</code></h3>
<pre><code class="lang-plaintext">        javascriptCopyEditconst input3 = Int64.from(22);

        const input1largest = input1
          .sub(input2)
          .isPositive()
          .and(input1.sub(input3).isPositive());
        const input2largest = input2
          .sub(input1)
          .isPositive()
          .and(input2.sub(input3).isPositive());
        const input3largest = input3
          .sub(input1)
          .isPositive()
          .and(input3.sub(input2).isPositive());

        const largest = Provable.switch(
          [input1largest, input2largest, input3largest],
          Int64,
          [input1, input2, input3]
        );

        console.log(`largest: ${largest.toString()}`);
</code></pre>
<h3 id="heading-output-1">Output:</h3>
<pre><code class="lang-plaintext">        makefileCopyEditinputSum: -5
        inputSumAbs: 5
        largest: 22
</code></pre>
<h3 id="heading-explanation-1">Explanation:</h3>
<ul>
<li><p><strong>Provable.if</strong>: This acts similarly to a ternary operation. Both branches (the "true" branch and the "false" branch) are evaluated to maintain the logic for zk circuits. Here, <code>inputSumAbs</code> returns the absolute value of the sum by checking if the sum is positive.</p>
</li>
<li><p><strong>Provable.switch</strong>: This function evaluates a series of boolean conditions (e.g., which input is largest) and switches to the corresponding value based on the conditions. In this example, it checks whether <code>input3</code> is the largest number and returns the largest of the three values (<code>input1</code>, <code>input2</code>, or <code>input3</code>).</p>
</li>
</ul>
<p>        These control flow methods ensure proper conditional logic while building zkApps with o1js.</p>
<h3 id="heading-assertions-and-constraints-in-o1js">Assertions and Constraints in o1js</h3>
<p>        In o1js, functions are compiled into zk circuits, which are used to prove that the logic in your program has been correctly executed and that all assertions hold true. The key idea is that when a transaction is proven in o1js, it ensures that the computations follow the program's logic and all assertions are valid.</p>
<h3 id="heading-key-points-2">Key Points:</h3>
<ul>
<li><p><strong>Assertions</strong>: These verify that certain conditions hold true during execution. For example, <code>.assertEquals(a, b)</code> ensures <code>a</code> equals <code>b</code>. Similarly, <code>.assertTrue()</code> can be used to assert that a boolean condition is true, which is useful for controlling logic flow.</p>
</li>
<li><p><strong>Circuit Size Constraints</strong>: o1js operates within fixed-size circuits, and every operation performed in your code counts toward the maximum size of the circuit. The size limits are:</p>
<ul>
<li><p>Approximately <strong>5,200 hashes</strong> for circuits involving two fields.</p>
</li>
<li><p>About <strong>2,600 hashes</strong> for circuits involving four fields.</p>
</li>
<li><p>Roughly <strong>2^17 field multiplies</strong>.</p>
</li>
<li><p>Around <strong>2^17 field additions</strong>.</p>
</li>
</ul>
</li>
</ul>
<p>        These constraints limit how complex a circuit can be. If the program exceeds these limits, it may need to be broken down into smaller pieces, each of which can be verified in a separate proof. This is where <strong>Recursion</strong> comes into play.</p>
<h3 id="heading-recursion">Recursion:</h3>
<p>        If the program is too large for the circuit size limits, <strong>recursion</strong> can be used to break the program into smaller, manageable parts. Each part is verified independently, and the overall correctness of the program can still be proven, while staying within the circuit size constraints.</p>
<p>        In summary, assertions ensure correctness, while circuit size constraints limit the complexity. If needed, recursion allows breaking down complex programs into smaller verifiable chunks.</p>
<h3 id="heading-merkle-trees-in-o1js">Merkle Trees in o1js</h3>
<p>        Merkle trees are used in o1js to manage large amounts of data efficiently within a zk-SNARK circuit. This is useful when you need to handle data in a way that proves its inclusion in a tree structure without revealing the entire dataset.</p>
<p>        The example project for this tutorial demonstrates how to work with Merkle trees using the <code>BasicMerkleTreeContract.ts</code> contract and <code>main.ts</code> to interact with Merkle trees.</p>
<h4 id="heading-steps-to-create-a-merkle-tree">Steps to Create a Merkle Tree:</h4>
<ol>
<li><p><strong>Importing MerkleTree</strong>:<br /> Import the <code>MerkleTree</code> class from <code>o1js</code>:</p>
<pre><code class="lang-plaintext"> tsCopyEditimport { MerkleTree } from 'o1js';
</code></pre>
</li>
<li><p><strong>Create a Merkle Tree</strong>:<br /> Define the height of the tree (which determines how many leaves the tree will have):</p>
<pre><code class="lang-plaintext"> tsCopyEditconst height = 20; // This creates a tree with 2^(20-1) = 524,288 leaves
 const tree = new MerkleTree(height);
</code></pre>
</li>
<li><p><strong>Store the Merkle Tree in a Smart Contract</strong>:<br /> Merkle trees are stored in a smart contract as the hash of the tree's root. You can update the Merkle root by providing a Merkle witness (which represents the Merkle path to a leaf).</p>
</li>
<li><p><strong>Example of a Contract Updating a Merkle Tree</strong>: Here’s a simplified example of how to define a smart contract that updates a Merkle tree by checking conditions:</p>
<pre><code class="lang-plaintext"> tsCopyEdit@state(Field) treeRoot = State&lt;Field&gt;();

 @method async initState(initialRoot: Field) {
   this.treeRoot.set(initialRoot);
 }

 @method async update(
   leafWitness: MerkleWitness20,
   numberBefore: Field,
   incrementAmount: Field
 ) {
   const initialRoot = this.treeRoot.get();
   this.treeRoot.requireEquals(initialRoot);

   incrementAmount.assertLt(Field(10));

   // Check initial state matches expectation
   const rootBefore = leafWitness.calculateRoot(numberBefore);
   rootBefore.assertEquals(initialRoot);

   // Compute root after increment
   const rootAfter = leafWitness.calculateRoot(numberBefore.add(incrementAmount));

   // Set new root
   this.treeRoot.set(rootAfter);
 }
</code></pre>
</li>
<li><p><strong>Interacting with the Smart Contract</strong>:</p>
<ul>
<li><p><strong>Initialize the zkApp</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst zkApp = new BasicMerkleTreeContract(basicTreeZkAppAddress);
  await BasicMerkleTreeContract.compile();
</code></pre>
</li>
<li><p><strong>Create a Merkle Tree</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst height = 20;
  const tree = new MerkleTree(height);
</code></pre>
</li>
<li><p><strong>Deploy the Smart Contract</strong>: Deploy the contract and initialize the tree state:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst deployTxn = await Mina.transaction(deployerAccount, async () =&gt; {
    AccountUpdate.fundNewAccount(deployerAccount);
    await zkApp.deploy();
    await zkApp.initState(tree.getRoot());
  });
  await deployTxn.prove();
  deployTxn.sign([deployerKey, basicTreeZkAppPrivateKey]);
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Update Tree Data</strong>:</p>
<ul>
<li><p><strong>Get the Witness for the Tree</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst witness = new MerkleWitness20(tree.getWitness(incrementIndex));
</code></pre>
</li>
<li><p><strong>Update the Tree Locally</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEdittree.setLeaf(incrementIndex, incrementAmount);
</code></pre>
</li>
<li><p><strong>Update the Smart Contract</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst txn1 = await Mina.transaction(senderPublicKey, async () =&gt; {
    await zkApp.update(witness, Field(0), incrementAmount);
  });
  await txn1.prove();
  const pendingTx = await txn1.sign([senderPrivateKey, basicTreeZkAppPrivateKey]).send();
  await pendingTx.wait();
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Compare Roots</strong>: After the transaction, you can compare the root of the local tree and the root stored in the smart contract:</p>
<pre><code class="lang-plaintext"> tsCopyEditconsole.log(`BasicMerkleTree: local tree root hash after send1: ${tree.getRoot()}`);
 console.log(`BasicMerkleTree: smart contract root hash after send1: ${zkApp.treeRoot.get()}`);
</code></pre>
</li>
</ol>
<h3 id="heading-advanced-example">Advanced Example:</h3>
<p>        A more advanced example uses a <strong>LedgerContract</strong> to implement a basic ledger of tokens, with checks to ensure that the sender has signed their transaction and that the amounts sent match what is received.</p>
<h4 id="heading-benefits-of-using-merkle-trees">Benefits of Using Merkle Trees:</h4>
<ul>
<li><p><strong>Efficient Data Proof</strong>: Merkle trees allow for efficient inclusion proofs, enabling you to prove that a piece of data exists in a large dataset without revealing the entire dataset.</p>
</li>
<li><p><strong>Secure Updates</strong>: By using Merkle witnesses and hashes, updates to the data can be securely and efficiently verified.</p>
</li>
</ul>
<h3 id="heading-merkle-map-in-o1js">Merkle Map in o1js</h3>
<p>        Merkle Maps are similar to Merkle Trees, but instead of using an index to access the data, they use keys (e.g., fields) to store and retrieve values. This is particularly useful for implementing key-value stores within zk-SNARK smart contracts.</p>
<h4 id="heading-basic-example-of-using-merkle-map">Basic Example of Using Merkle Map</h4>
<ol>
<li><p><strong>Create and Populate a Merkle Map</strong>:</p>
<pre><code class="lang-plaintext"> tsCopyEditconst map = new MerkleMap();

 const key = Field(100);
 const value = Field(50);

 map.set(key, value);
 console.log('value for key', key.toString() + ':', map.get(key));
</code></pre>
<p> This will output:</p>
<pre><code class="lang-plaintext"> rustCopyEditvalue for key 100: 50
</code></pre>
</li>
<li><p><strong>Smart Contract Usage</strong>: Similar to Merkle Trees, you can use Merkle Maps in smart contracts. The contract uses a Merkle Map to store the root of the key-value map, and it uses witnesses to prove changes to the map.</p>
<ul>
<li><p><strong>Smart Contract Definition</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEdit@state(Field) mapRoot = State&lt;Field&gt;();

  @method async init(initialRoot: Field) {
    this.mapRoot.set(initialRoot);
  }

  @method async update(
    keyWitness: MerkleMapWitness,
    keyToChange: Field,
    valueBefore: Field,
    incrementAmount: Field,
  ) {
    const initialRoot = this.mapRoot.get();
    this.mapRoot.requireEquals(initialRoot);

    incrementAmount.assertLt(Field(10));

    // Check the initial state matches what we expect
    const [rootBefore, key] = keyWitness.computeRootAndKey(valueBefore);
    rootBefore.assertEquals(initialRoot);

    key.assertEquals(keyToChange);

    // Compute the root after incrementing
    const [rootAfter, _] = keyWitness.computeRootAndKey(valueBefore.add(incrementAmount));

    // Set the new root
    this.mapRoot.set(rootAfter);
  }
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Interacting with the Smart Contract</strong>: Similar to Merkle Trees, you interact with Merkle Maps by getting the witness for the key you want to update, and then sending the update to the smart contract.</p>
<ul>
<li><p><strong>Example of Interacting with the Map</strong>:</p>
<pre><code class="lang-plaintext">  tsCopyEditconst map = new MerkleMap();

  const rootBefore = map.getRoot();

  const key = Field(100);

  const witness = map.getWitness(key);

  // Update the smart contract with the new value for the key
  const txn1 = await Mina.transaction(deployerAccount, async () =&gt; {
    await zkApp.update(
      contract.update(
        witness,
        key,
        Field(50),  // Previous value
        Field(5)    // Increment value
      )
    );
  });
</code></pre>
</li>
</ul>
</li>
</ol>
<h4 id="heading-use-cases-for-merkle-maps">Use Cases for Merkle Maps:</h4>
<ol>
<li><p><strong>Key-Value Store</strong>:<br /> You can implement a key-value store, such as a mapping of public keys to booleans (for token accounts) or other types of data.</p>
</li>
<li><p><strong>Nullifiers</strong>:<br /> Merkle Maps can be used to privately track whether an input has been used (e.g., in voting systems), without revealing the value of the input.</p>
</li>
</ol>
<p>        for more information:<a target="_blank" href="https://docs.minaprotocol.com/zkapps/tutorials/common-types-and-functions">https://docs.minaprotocol.com/zkapps/tutorials/common-types-and-functions</a></p>
]]></content:encoded></item><item><title><![CDATA[O1js: TypeScript library for zkApp development]]></title><description><![CDATA[ZKP Labs Vietnam hosted a workshop on o1js, a powerful TypeScript library for zk-SNARKs and zkApps designed by O(1) Labs. Led by Chiro8x, founder of Orochi…]]></description><link>https://nwa-eddy84.hashnode.dev/o1js-typescript-library-for-zkapp-development</link><guid isPermaLink="true">https://nwa-eddy84.hashnode.dev/o1js-typescript-library-for-zkapp-development</guid><dc:creator><![CDATA[Samuel Esther]]></dc:creator><pubDate>Sat, 18 Jan 2025 13:46:55 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-introduction-to-o1js"><strong>Introduction to o1js</strong></h1>
<p>ZKP Labs Vietnam hosted a workshop on o1js, a powerful TypeScript library for zk-SNARKs and zkApps designed by O(1) Labs. Led by Chiro8x, founder of Orochi Network, and David from Mina Foundation, the workshop delved deep into the functionalities and applications of o1js in the Mina ecosystem.</p>
<h1 id="heading-what-are-zkapps">What are zkApps?</h1>
<p>zkApps (zero knowledge apps) are Mina Protocol smart contracts that utilize zero knowledge proofs, specifically zk-SNARKs.</p>
<p>zkApps operate using an off-chain execution and mostly off-chain state model. This design enables private computation and allows the state to be either private or public.</p>
<p>zkApps can carry out arbitrarily complex computations off-chain, requiring only a flat fee to send the resulting zero knowledge proof to the chain for verification. This approach offers cost savings compared to other blockchains, which execute computations on-chain and rely on a variable gas-fee model.</p>
<h1 id="heading-what-is-typescript">What is TypeScript?</h1>
<p>JavaScript and More</p>
<p>TypeScript adds additional syntax to JavaScript to support a <strong>tighter integration with your editor</strong>. Catch errors early in your editor.</p>
<p>A Result You Can Trust</p>
<p>TypeScript code converts to JavaScript, which <strong>runs anywhere JavaScript runs</strong>: In a browser, on Node.js, Deno, Bun and in your apps.</p>
<p>Safety at Scale</p>
<p>TypeScript understands JavaScript and uses <strong>type inference to give you great tooling</strong> without additional code.</p>
<h1 id="heading-typescript"><strong>TypeScript</strong></h1>
<p>zkApps are written in TypeScript.</p>
<p>TypeScript offers an accessible and familiar language (JavaScript) while incorporating type safety, making it straightforward to begin developing zkApps. If you're new to TypeScript, you can explore this helpful 12-minute introductory video: <em>TypeScript - The Basics</em>.</p>
<h1 id="heading-how-zkapps-work"><strong>How zkApps Work</strong></h1>
<p>zkApps run in the latest versions of Chrome, Firefox, Edge, and Brave web browsers.</p>
<p>They are written in TypeScript using the zkApp CLI.</p>
<p>A zkApp is made up of two components:</p>
<ol>
<li><p>A <strong>smart contract</strong></p>
</li>
<li><p>A <strong>user interface (UI)</strong> for users to interact with the zkApp.:</p>
</li>
</ol>
<h1 id="heading-zero-knowledge-based-smart-contracts"><strong>Zero knowledge-based smart contracts</strong></h1>
<p>zkApps are based on zero knowledge proofs (zk-SNARKs). As a zkApp developer, you use the zkApp CLI to scaffold and deploy your project.</p>
<p>[if !supportLists]3.      [endif]Provable code is written using o1js and generates a prover function and a corresponding verifier function that are derived during the build process.</p>
<p>[if !supportLists]4.      [endif]The prover function is the function that executes a smart contract's custom logic and runs in an end user's web browser as part of the zkApp. The prover function generates a proof of the executed code.</p>
<p>[if !supportLists]5.      [endif]When interacting with a zkApp UI, users enter any data (for example, buy ABC for y price) that is required as input to the prover function, which then generates a zero knowledge proof.</p>
<h1 id="heading-private-and-public-inputs"><strong>Private and Public Inputs</strong></h1>
<p>Private and public inputs represent data that must be provided to the prover function when it runs in the end user's web browser.</p>
<ul>
<li><p><strong>Private inputs</strong> are not required again.</p>
</li>
<li><p><strong>Public inputs</strong> must also be provided to the verifier function when it runs on the Mina network. Public inputs should not be used for data that needs to remain private.</p>
</li>
</ul>
<p>The <strong>verifier function</strong> validates whether a zero knowledge proof successfully passes all the constraints defined in the prover function. The verifier function always runs quickly and efficiently, irrespective of the prover function's complexity.</p>
<p>Within the <strong>Mina network</strong>, Mina acts as the verifier and runs the verifier function.</p>
<h1 id="heading-prover-function-and-verification-key"><strong>Prover Function and Verification Key</strong></h1>
<p>After you write a smart contract, build it by running the npm run build command. The build process compiles the TypeScript code into JavaScript and outputs the smart_contract.js file.</p>
<p>From this file, you can:</p>
<ul>
<li><p>Run a prover function to execute your smart contract.</p>
</li>
<li><p>Generate a verification key to deploy your smart contract.</p>
</li>
</ul>
<p>While the prover function runs in an end user's web browser, the verification key lives on-chain for a given zkApp account and is used by the Mina network to verify that a zero knowledge proof has met all constraints defined in the prover. A verification key is required to create a zkApp account.</p>
<p>You can also use the verifier function or verification key to verify proofs off-chain.</p>
<h1 id="heading-deploy-a-smart-contract"><strong>Deploy a smart contract</strong></h1>
<p>zkApp developers use the zkApp CLI to deploy smart contracts to the Mina network. The deployment process sends a transaction that contains the verification key, which is an output of the verifier function, to an address on the Mina blockchain.</p>
<h1 id="heading-deploy-a-zkapp-ui"><strong>Deploy a zkApp UI</strong></h1>
<p>A zkApp consists of a smart contract and a UI to interact with it.</p>
<p>To enable users to interact with your smart contract in a web browser, you build a website UI and then deploy this interactive UI as a static website. Choosing a host that offers a global content delivery network (CDN) ensures the best experience for all users.</p>
<h1 id="heading-how-users-interact-with-a-zkapp"><strong>How users interact with a zkApp</strong></h1>
<p>To use a zkApp, end users must install a wallet that supports interactions with zkApps.</p>
<p>After a zkApp is deployed to a host (for example, <a target="_blank" href="http://mycoolzkapp.com">mycoolzkapp.com</a>), end users can interact with it:</p>
<ol>
<li><p>The user visits <a target="_blank" href="http://mycoolzkapp.com"><em>mycoolzkapp.com</em></a>.</p>
</li>
<li><p>The user interacts with the zkApp and enters the required data. For example, if this were an automated market maker, the user might specify to buy x amount of ABC at y price.</p>
</li>
<li><p>The prover function in the zkApp generates a zero knowledge proof locally using the data entered by the user. This data can be either:</p>
<ul>
<li><p><strong>Private</strong>: The data is never seen by the blockchain.</p>
</li>
<li><p><strong>Public</strong>: The data is stored on-chain or off-chain, depending on what the zkApp specified as required for a given use case.</p>
</li>
</ul>
</li>
<li><p>A list of state updates (called account updates) to be created by the transaction is generated. The account updates are associated with this proof.</p>
</li>
<li><p>The user selects <em>Submit to chain</em> in the zkApp UI.</p>
</li>
<li><p>The user confirms the transaction on their wallet.</p>
</li>
<li><p>The wallet signs the transaction containing the proof and the associated description of the state to update.</p>
</li>
<li><p>The wallet sends the transaction to the Mina network.</p>
</li>
<li><p>The Mina network receives this transaction and verifies that the proof successfully passes the verifier method listed on the zkApp account. If the network accepts this transaction, the proof and the requested state changes are valid and allowed to update the zkApp state.</p>
</li>
</ol>
<p>The end user's privacy is maintained because their interaction occurs locally in a web browser using JavaScript on the client.</p>
<h1 id="heading-how-state-is-updated-on-chain"><strong>How state is updated on-chain</strong></h1>
<p>The zkApp account gets updated on-chain.</p>
<p>When the prover function runs in a web browser, the smart contract outputs a proof and some associated data called "account updates" that are sent to a zkApp address as part of the transaction. The account updates are a JSON plain text description that describes how to update the state on a zkApp account.</p>
<p>The integrity of these account updates is ensured by passing a hash of the account updates as a public input to the smart contract. The account updates must be present and unmodified for the verification function to pass successfully when it runs on Mina. In this way, the Mina network can confirm the integrity of both the proof and the associated account updates that describe how to update the zkApp account state.</p>
<h1 id="heading-zkapp-state"><strong>zkApp state</strong></h1>
<ul>
<li><p><strong>On-chain state</strong> describes state that lives on the Mina blockchain.</p>
</li>
<li><p><strong>Off-chain state</strong> describes state stored anywhere else.</p>
</li>
</ul>
<hr />
<h1 id="heading-on-chain-state"><strong>On-chain state</strong></h1>
<p>Each zkApp account provides 8 fields of 32 bytes each of arbitrary storage. You may store anything here as long as it fits in the size provided.</p>
<p>If you anticipate your state to be larger, or if the state accumulates per user with your zkApp, then use off-chain state instead.</p>
<hr />
<h1 id="heading-off-chain-state"><strong>Off-chain state</strong></h1>
<p>For larger data, you might want to consider storing the root of a Merkle tree or a similar data structure within your zkApp's on-chain storage that references self-hosted off-chain state stored elsewhere. Mina doesn't offer an out-of-the-box solution for off-chain storage.</p>
<p>When the zkApp runs in a user's web browser, it can insert state to an external storage, such as IPFS. When the transaction is sent to the Mina network, if the network accepts this zkApp transaction and confirms the proof and state are valid, the zkApp transaction can update the root of the Merkle tree that is stored on-chain.</p>
<h1 id="heading-on-chain-values"><strong>On-Chain Values</strong></h1>
<p>In a zkApp, you can access the current on-chain state and many other on-chain values of the account.</p>
<p>The zkApp account's on-chain state can be updated by account updates included in a transaction (see Tutorial 10: Account Updates). On the Mina blockchain, each zkApp account provides eight fields of ~32 bytes each of arbitrary storage for the on-chain state.</p>
<hr />
<p><strong>Two possible use cases</strong>:</p>
<ol>
<li><p><strong>Voting</strong>: You want to let users vote on a proposal, but only within a specific timespan. To restrict the dates, your zkApp can require that the current timestamp lies in a certain range.</p>
</li>
<li><p><strong>DeFi</strong>: You want to compute amounts relative to a balance. For example, paying a yield of 0.001 times the account balance requires the current on-chain balance.</p>
</li>
</ol>
<hr />
<p>There are two categories of on-chain values:</p>
<ol>
<li><p><strong>Network</strong>: Includes the current timestamp, block height, total Mina in circulation, and other network state.</p>
</li>
<li><p><strong>Account</strong>: Includes fields and properties of the zkApp account, such as balance, nonce, and delegate.</p>
</li>
</ol>
<p>In a smart contract, the subfields are accessible via <a target="_blank" href="http://this.network">this.network</a> and this.account. For example, the timestamp on <a target="_blank" href="http://this.network">this.network</a>.timestamp has four methods:</p>
<h1 id="heading-the-familiar-on-chain-state"><strong>The familiar on-chain state</strong></h1>
<p>On-chain state values in zkApps provide the same familiar methods, such as get() and requireEquals().</p>
<p>Additionally, the requireBetween() method offers enhanced functionality, allowing you to assert that a timestamp lies between a specified lower and upper bound (inclusive).</p>
<hr />
<p><strong>Example: Restricting timestamps</strong><br />To use the requireBetween() method in a voting scenario, you can restrict voting to occur only during September 2024. Timestamps are represented as a UInt64 in milliseconds since the UNIX epoch. The JavaScript Date object can be used to easily convert human-readable dates into this representation.</p>
<p>In the simplest case, a zkApp can hard-code the dates:</p>
<p><strong>A more refined example</strong><br />A more refined approach could store the current start date in an on-chain state variable. This start date can then be updated by a process encoded within the zkApp, allowing for more dynamic behavior based on use cases.</p>
<hr />
<h1 id="heading-network-reference"><strong>Network reference</strong></h1>
<p>For completeness, here is a list of network states you can access and make assertions about in your zkApp.</p>
<p>All of these fields provide:</p>
<ul>
<li><p><strong>get()</strong>: To retrieve the current value.</p>
</li>
<li><p><strong>requireEquals()</strong>: To assert that the value matches an expected value.</p>
</li>
</ul>
<p>Additionally, fields that represent <strong>ordered values</strong> (such as those stored as UInt32 or UInt64) also support the requireBetween() method for range-based assertions.</p>
<h1 id="heading-account-reference"><strong>Account reference</strong></h1>
<p>Here is the complete list of values accessible on the zkApp account.</p>
<p>Like network states, these account values provide:</p>
<ul>
<li><p><strong>get()</strong>: To retrieve the current value.</p>
</li>
<li><p><strong>Require Equals()</strong>: To assert that the value matches an expected value.</p>
</li>
</ul>
<p>Additionally, <strong>balance</strong> and <strong>nonce</strong> support the <strong>require Between()</strong> method, enabling range-based assertions.</p>
<p><strong>Bailing out</strong><br />In rare cases, you might want to retrieve an on-chain value using <strong>get()</strong> without placing any constraints on it. By default, o1js will throw a helpful error reminding you to use <strong>require Equals()</strong> or <strong>require Between()</strong> for constraint validation.</p>
<p>However, as an escape hatch, if you're absolutely certain you do not want to apply any constraints to the on-chain value, you can use <strong>require</strong></p>
<p><strong>Nothing()</strong> on all of these fields (including on-chain state).</p>
<hr />
<p><strong>Danger</strong><br /><strong>require Nothing()</strong> should be used sparingly, as it can introduce security risks through unexpected behavior if misused. It effectively bypasses the normal checks, which could lead to unintended consequences. Be absolutely certain of your intentions before using this method.</p>
<p><strong>Setting account fields</strong><br />Just like on-chain state, some account fields can be written to. The API for setting these values is consistent with how you handle state: this.account.&lt;field&gt;.set(newValue).</p>
<p>For example, to change permissions on an account, you would use this method to set the desired new value:</p>
<p>javascript</p>
<p>CopyEdit</p>
<p>this.account.permissions.set(newPermissions);</p>
<p>This allows for modification of specific account properties, such as permissions or other fields, directly within the zkApp.</p>
<p>The fields that you can set are not the same as the fields that you can make assertions about.</p>
<p>Here is the full list of fields that have a .set():</p>
<ul>
<li><p><strong>delegate</strong>: Sets the delegate public key for staking purposes.</p>
</li>
<li><p><strong>permissions</strong>: Sets the permissions for the account.</p>
</li>
<li><p><strong>balance</strong>: Sets the account balance (in some cases).</p>
</li>
<li><p><strong>nonce</strong>: Sets the nonce for the account.</p>
</li>
</ul>
<p>Note: The specific fields that can be set might depend on the implementation of the zkApp and what permissions or changes are allowed for each account.</p>
<h1 id="heading-accessing-accounts-other-than-the-zkapps-account"><strong>Accessing accounts other than the zkApp's account</strong></h1>
<p>The API described in this section (e.g., get(), set(), assertEquals(), etc.) can be used not only to access the zkApp's own account but also any other account. Account updates are a flexible and powerful data structure that can express a variety of updates, events, and preconditions used in smart contract development. For more details, refer to <strong>Tutorial 10: Account Updates</strong>.</p>
<p>To create an account update to interact with the same account and network fields, you can:</p>
<p>javascript</p>
<p>CopyEdit</p>
<p>const accountUpdate = this.account.update();</p>
<p>accountUpdate.setField('fieldName', newValue);</p>
<p>This allows you to access and modify fields in other accounts, provided you have the necessary permissions and context to do so.</p>
<p>Account updates enable dynamic and complex interactions across accounts within the Mina ecosystem.</p>
<h1 id="heading-offchain-storage"><strong>Offchain Storage</strong></h1>
<p>One of Mina's unique features is its succinctness, both in computation and storage. To prevent state bloat and maintain Mina's efficiency and verifiability, offchain storage solutions are used to handle large volumes of data.</p>
<p>In a previous section, we introduced the concept of <strong>on-chain values</strong>. Since Mina currently supports a total of only 8 on-chain field elements, leveraging offchain storage is necessary to extend that capacity. This approach allows for efficient storage without compromising on security.</p>
<p>Offchain storage maintains a <strong>provably secure connection</strong> between the on-chain smart contract and the offchain data, such as that stored in an archive node. By storing larger datasets offchain, Mina ensures that the blockchain remains lightweight and efficient while still being able to reference and validate extensive data securely when needed.</p>
<h1 id="heading-design"><strong>Design</strong></h1>
<p>Currently, offchain storage in Mina supports two types of state:</p>
<ol>
<li><p><strong>OffchainState.Field</strong>: Represents a single field of state.</p>
</li>
<li><p><a target="_blank" href="http://OffchainState.Map"><strong>OffchainState.Map</strong></a>: Similar to key-value maps found in JavaScript, like let myMap = new Map&lt;string, number&gt;();.</p>
</li>
</ol>
<p>All offchain state resides within a single <strong>Merkle Map</strong>, which is essentially a wrapper around a Merkle Tree. Practically speaking, there are no limits on the number of state fields and maps that a developer can store in a smart contract using offchain storage.</p>
<p><strong>Utilizing Offchain Storage</strong><br /><strong>Prerequisites</strong><br />The <strong>OffchainState</strong> API is accessible within the <strong>Experimental</strong> namespace. To use OffchainState, import <strong>Experimental</strong> from <strong>o1js</strong> version 1.9.1 or higher.</p>
<p><strong>Setting up Offchain Storage</strong><br />To integrate Offchain storage, developers must first define an <strong>Offchain state configuration</strong> and a <strong>state proof type</strong>, and then prepare the smart contract.</p>
<ul>
<li><p>The <strong>OffchainState configuration</strong> allows the specification of the desired Offchain state type, including key-value pairs in a map and any additional required state.</p>
</li>
<li><p>The <strong>StateProof type</strong> will then be used to finalize published state changes using a recursive reducer.</p>
</li>
<li><p>The <strong>OffchainStateInstance</strong> stores internal data, such as the associated contract instance and the Merkle trees of data.</p>
</li>
</ul>
<p>Developers also need to set the <strong>smart contract instance</strong> and assign it to the offchain storage. This process compiles the recursive <strong>Offchain zkProgram</strong> in the background and assigns the Offchain state to the smart contract instance property.</p>
<hr />
<h1 id="heading-framework-for-state-management"><strong>Framework for State Management</strong></h1>
<p>Under this framework, <strong>Actions</strong> and <strong>Reducers</strong> are used to manage state changes:</p>
<ul>
<li><p><strong>Actions</strong> dispatch state updates.</p>
</li>
<li><p><strong>Reducers</strong> settle these updates and finalize changes.</p>
</li>
</ul>
<p>A <strong>Merkle Tree</strong> is employed to maintain a <strong>provably secure commitment</strong> to the data, with the root stored on-chain. This ensures that the integrity of offchain data is verifiable.</p>
<hr />
<h1 id="heading-state-settlement"><strong>State Settlement</strong></h1>
<p>Before users can access published state, it must first undergo <strong>settlement</strong>. Thanks to the design of offchain storage, all state is recoverable from actions alone, removing the need for additional events or external data storage. This makes state management both efficient and secure, with the guarantee that the state can be reconstructed and validated without relying on external systems.</p>
<h1 id="heading-permissions"><strong>Permissions</strong></h1>
<p>Permissions are crucial in zkApp development as they define who has the authority to interact with and modify specific parts of a smart contract.</p>
<p>Proper permissions are essential to prevent attacks or security vulnerabilities. Permissions are stored on-chain, making them part of the account's representation on the network. They are verified every time an account update attempts to interact with an account.</p>
<p><strong>Types of Permissions</strong></p>
<p>There are 13 permissions that define and guard interactions with a zkApp account:</p>
<ol>
<li><p><strong>editState</strong>: Controls how the zkApp account's eight on-chain state fields can be manipulated.</p>
</li>
<li><p><strong>send</strong>: Governs the ability to send transactions from the account, such as transferring MINA.</p>
</li>
<li><p><strong>receive</strong>: Determines whether the account can receive transactions, such as deposits of MINA.</p>
</li>
<li><p><strong>setDelegate</strong>: Manages the ability to set the delegate field, specifying another account to delegate the account’s MINA for staking.</p>
</li>
<li><p><strong>setPermissions</strong>: Defines who can change the permissions of the account.</p>
</li>
<li><p><strong>setVerificationKey</strong>: Regulates the ability to change the verification key used to verify off-chain proofs, essentially defining smart contract "upgradeability."</p>
</li>
<li><p><strong>setZkappUri</strong>: Controls the ability to update the zkApp URI field, which stores metadata about the smart contract, like a source code link.</p>
</li>
<li><p><strong>editActionsState</strong>: Allows changes to the actions state of the account, which commits dispatched actions on-chain.</p>
</li>
<li><p><strong>setTokenSymbol</strong>: Governs the ability to set the token symbol associated with the account.</p>
</li>
<li><p><strong>incrementNonce</strong>: Determines whether the nonce can be incremented via an account update and specifies who can perform this action.</p>
</li>
<li><p><strong>setVotingFor</strong>: Controls the ability to set the chain hash for voting on a hard fork via the account's votingFor field.</p>
</li>
<li><p><strong>access</strong>: Restricts any account updates for the account, including no-op updates. Typically, access requires no authorization, but for token manager contracts, it demands proof authorization.</p>
</li>
<li><p><strong>setTiming</strong>: Manages the vesting schedule for time-locked accounts.</p>
</li>
</ol>
<h1 id="heading-authorization"><strong>Authorization</strong></h1>
<p>Authorization specifies what resources can be accessed, while permissions define who has the ability to perform actions.</p>
<p>A transaction is composed of multiple <strong>account updates</strong> (instructions to the network), each of which must be authorized. In o1js or a blockchain explorer, the <strong>authorization field</strong> of an account update indicates how it is authorized:</p>
<ol>
<li><p><strong>Proof</strong>: If the authorization field contains a proof, the transaction is authorized by a proof verified against the account's verification key.</p>
</li>
<li><p><strong>Signature</strong>: If the authorization field contains a signature, the transaction is authorized by a signature.</p>
</li>
</ol>
<p><strong>Types of Authorizations</strong></p>
<ol>
<li><p><strong>none</strong>: Fields with this permission can be accessed and manipulated by anyone without restriction.</p>
</li>
<li><p><strong>impossible</strong>: Fields with this permission cannot be changed under any circumstances.</p>
</li>
<li><p><strong>signature</strong>: Only account updates authorized by a valid signature can manipulate these fields.</p>
</li>
<li><p><strong>proof</strong>: Only account updates authorized by a valid proof, generated by executing a smart contract method, can manipulate these fields. The proof is checked against the account's verification key to ensure correctness.</p>
</li>
<li><p><strong>proofOrSignature</strong>: These permissions accept either a valid signature or a valid proof for authorization.</p>
</li>
</ol>
<p>This example account update is authorized by a <strong>signature</strong>, and it attempts to update the app state of the smart contract.</p>
<p>However, if a smart contract's <strong>editState</strong> permission is set to <strong>none</strong>, anyone can change the state of the smart contract freely, which is highly insecure.</p>
<p>To restrict state changes, you should set the authorization to <strong>proof</strong>. This ensures that a valid proof accompanies any account update attempting to modify the state. The proof is checked against the account's verification key, guaranteeing that state changes occur only if the user has executed a smart contract method correctly and generated a valid proof.</p>
<p>When a smart contract is deployed, it begins with the following <strong>default permissions</strong>:</p>
<ul>
<li><p><strong>editState</strong>: proof</p>
</li>
<li><p><strong>send</strong>: proof</p>
</li>
<li><p><strong>receive</strong>: none</p>
</li>
<li><p><strong>setDelegate</strong>: signature</p>
</li>
<li><p><strong>setPermissions</strong>: signature</p>
</li>
<li><p><strong>setVerificationKey</strong>: signature</p>
</li>
<li><p><strong>setZkappUri</strong>: signature</p>
</li>
<li><p><strong>editActionsState</strong>: proof</p>
</li>
<li><p><strong>setTokenSymbol</strong>: signature</p>
</li>
</ul>
<p>To enhance the security of your smart contract, refer to examples illustrating how to configure and utilize permissions effectively.</p>
<p>An <strong>UnsecureContract</strong> example demonstrates how smart contracts managing state and tokens, such as the native MINA token, might inadvertently allow vulnerabilities. Without proper permission configurations, malicious actors could exploit the contract to withdraw all funds.</p>
<p>This type of example is often provided as a starting point to emphasize the importance of securing contracts through permissions. A similar example, <strong>simple-zkapp-payment.ts</strong>, can typically be found in the provided examples folder. It highlights the need to enforce secure configurations to protect against unauthorized access and fund manipulation.</p>
<p>The <strong>UnsecureContract</strong> example defines a withdraw() method that allows funds to be withdrawn from the smart contract account. However, the contract's init() method sets the send permission to Permissions.none(). This configuration is highly insecure because Permissions.none() allows anyone to interact with the contract without any form of authorization.</p>
<p><strong>Exploit Scenario</strong></p>
<p>With Permissions.none() for the send action, a malicious actor could construct and execute a transaction that drains all funds from the smart contract account. This happens because no signature or proof is required to authorize the transaction.</p>
<p>The following malicious transaction demonstrates how this vulnerability can be exploited:</p>
<ul>
<li><p>A malicious actor initiates a transaction to withdraw all funds.</p>
</li>
<li><p>The network does not enforce any checks for authorization due to the Permissions.none() configuration.</p>
</li>
<li><p>As a result, the attacker successfully drains the contract account.</p>
</li>
</ul>
<p><strong>Lesson</strong></p>
<p>This example illustrates why setting Permissions.none() for critical actions like send or editState is a poor security practice. Instead, permissions should be configured more securely, such as using Permissions.proof() or Permissions.signature() to require proper authorization mechanisms for sensitive operations.</p>
<p>By changing the send permission to Permissions.signature() in the <strong>UnsecureContract</strong>, the vulnerability allowing unauthorized transactions is mitigated. Here's what happens after this change:</p>
<h1 id="heading-updated-permission"><strong>Updated Permission</strong></h1>
<p>The send permission in the init() method is updated as follows:</p>
<p>javascript</p>
<p>CopyEdit</p>
<p>this.account.permissions.set({</p>
<p>  ...Permissions.default(),</p>
<p>  send: Permissions.signature(),</p>
<p>});</p>
<p><strong>Effects of the Change</strong></p>
<ol>
<li><p><strong>Authorization Required:</strong> The Permissions.signature() setting requires that any transaction attempting to send funds from the smart contract be signed by the private key of the smart contract account.</p>
</li>
<li><p><strong>Malicious Transaction Blocked:</strong> The previous exploit, where a fee payer's private key authorized the transaction, will no longer work because the malicious transaction lacks the required signature from the smart contract account.</p>
</li>
<li><p><strong>Security Enhancement:</strong> This ensures that only the entity in possession of the smart contract's private key can authorize transactions involving the send permission.</p>
</li>
</ol>
<p><strong>Best Practices</strong></p>
<ol>
<li><p>Use <strong>appropriate permissions</strong> to secure critical actions in your zkApp.</p>
</li>
<li><p>Regularly review permissions during development and testing to identify and address potential vulnerabilities.</p>
</li>
<li><p>Consider requiring <strong>proof-based authorizations</strong> (using Permissions.proof()) for complex or sensitive operations that need to enforce specific rules defined in the zkApp logic.</p>
</li>
</ol>
<p>[if !supportLists]4.      [endif]The upgradeability of a smart contract on the Mina blockchain is directly tied to the <code>setVerificationKey</code> permission. The verification key, generated from the contract's source code, is stored on-chain and used for verifying proofs. To control whether the smart contract can be upgraded after deployment, you adjust the <code>setVerificationKey</code> permission.</p>
<h1 id="heading-allowing-upgradeability"><strong>Allowing Upgradeability</strong></h1>
<p>To allow a smart contract to be upgraded (i.e., the verification key can be changed), you set the <code>setVerificationKey</code> permission to <code>Permissions.signature()</code> or <code>Permissions.proof()</code> depending on how you want the upgrade process to be authorized. This means that after the contract is deployed, the contract's verification key can be modified by submitting a valid signature or proof.</p>
<h3 id="heading-upgrading-after-an-update-to-the-mina-protocol"><strong>Upgrading After an Update to the Mina Protocol</strong></h3>
<p>When Mina Protocol undergoes a non-backwards compatible update, zkApps that were previously deployed might need to upgrade their verification key to stay compatible with the new protocol version. If a zkApp fails to upgrade its verification key, it won't be able to verify proofs, and as a result, it will no longer be able to interact with the network, essentially becoming non-functional.</p>
<p>To address this, Mina has special rules regarding the permissions for modifying the verification key (specifically the <strong>Impossible</strong> and <strong>Proof</strong> permissions) that allow zkApps to update their verification key even after a protocol update.</p>
<h3 id="heading-permissions-for-verification-key-impossible-and-proof"><strong>Permissions for Verification Key: Impossible and Proof</strong></h3>
<p>[if !supportLists]·         [endif]<strong>Impossible Permission</strong>: Normally, if the <strong>Impossible</strong> permission is set for the verification key, it means the verification key cannot be changed under any circumstances. This is designed to lock the verification key for security reasons. However, in the case of a protocol update, the Impossible permission is automatically treated as <strong>Signature</strong> when the zkApp's transaction version is lower than the current protocol version. This allows the zkApp to update its verification key to remain compatible with the new protocol.</p>
<p>[if !supportLists]·         [endif]<strong>Proof Permission</strong>: If the <strong>Proof</strong> permission is set, it means that only a valid proof can change the verification key. Similarly, when a protocol update occurs and the zkApp's transaction version is outdated, the Proof permission is automatically treated as <strong>Signature</strong> to allow for the necessary verification key upgrade.</p>
<h3 id="heading-verification-key-permissions-representation"><strong>Verification Key Permissions Representation</strong></h3>
<p>The permissions for the verification key are internally represented as a <strong>tuple</strong> consisting of two fields:</p>
<ol>
<li><p><strong>Mechanism</strong>: Defines how the verification key can be modified (e.g., Impossible, Signature, Proof).</p>
</li>
<li><p><strong>Transaction Version</strong>: Specifies the version of the Mina Protocol that was in use when the zkApp's verification key was deployed. This version field ensures that the zkApp is properly aligned with the protocol version and can be upgraded when needed.</p>
</li>
<li><p>ZkApp Upgradability                                                                                                                  ZkApp Upgradability on Mina Protocol is unique because upgrades are essentially restricted to changes in the verification key, ensuring that the underlying logic of the smart contract does not change unexpectedly. This is a crucial distinction compared to other blockchains, where a contract upgrade could lead to unexpected behavior. On Mina, the contract logic remains consistent, and only the verification key is upgraded on-chain, allowing for a secure and predictable upgrade process.</p>
<h3 id="heading-key-points">Key points:</h3>
<p> [if !supportLists]1.      [endif]<strong>Permissions for Upgrades</strong>: To upgrade a ZkApp, specific permissions related to the verification key must be configured. The <code>setVerificationKey</code> permission governs whether the verification key can be modified.</p>
<p> [if !supportLists]2.      [endif]<strong>Execution Model on Mina</strong>: Mina's execution model ensures that users always interact with the same program, even after an upgrade. Unlike other blockchains, where upgrades may change the contract's behavior, Mina's upgrades only involve changes to the verification key, ensuring that users interact with the same program (but the newer, upgraded version) after the upgrade.</p>
<p> [if !supportLists]3.      [endif]<strong>Proof Compatibility</strong>: When the verification key is changed, proofs generated with the previous key will no longer be valid. Users must download the new prover function (the program used to generate valid proofs) to continue interacting with the updated ZkApp.</p>
<p> By adhering to this execution model and ensuring that only the verification key changes on-chain, Mina ensures that contract upgrades remain predictable, secure, and transparent for all users.</p>
<h2 id="heading-baseline-zkapphttpsdocsminaprotocolcomzkappswriting-a-zkappfeature-overviewupgradabilitybaseline-zkapp">Baseline ZkApp<a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#baseline-zkapp">​</a></h2>
<p> For example, let's use our standard <code>Add</code> example smart contract as the baseline ZkApp.</p>
<p> This contract has a verification key of <code>"27729068461170601362912907281403262888852363473424470267835507636847418791713"</code></p>
<h2 id="heading-upgraded-zkapphttpsdocsminaprotocolcomzkappswriting-a-zkappfeature-overviewupgradabilityupgraded-zkapp">Upgraded ZkApp<a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgraded-zkapp">​</a></h2>
<p> For our upgraded contract, let's use this updated example which adds by 4 instead of by 2.</p>
<p> This contract has a verification key of <code>"18150279532259194644722165513074833862035641840431153413486908511595437348455"</code></p>
<h2 id="heading-upgrading-a-zkapphttpsdocsminaprotocolcomzkappswriting-a-zkappfeature-overviewupgradabilityupgrading-a-zkapp">Upgrading a ZkApp<a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgrading-a-zkapp">​</a></h2>
<p> Upgrading a ZkApp by signature can be done if you control the private key of a ZkApp. To do this, you need to sign a transaction that upgrades the ZkApp with that key.</p>
<p> Imagine we have already deployed the <code>Add</code> contract, and we have the private key available as <code>zkAppKey</code></p>
<p> And just like that, when the transaction is applied to the blockchain, the verification key at the ZkApp address will be updated from <code>"27729068461170601362912907281403262888852363473424470267835507636847418791713"</code> to <code>"18150279532259194644722165513074833862035641840431153413486908511595437348455"</code>!</p>
<h2 id="heading-upgrades-with-more-surface-areahttpsdocsminaprotocolcomzkappswriting-a-zkappfeature-overviewupgradabilityupgrades-with-more-surface-area">Upgrades with More Surface Area<a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/upgradability#upgrades-with-more-surface-area">​</a></h2>
<p> In the previous example, we changed one small variable in the smart contract but kept the state and methods the same. However, there is no limit to what you can change via upgrade. Let's go through one more example where more things have changed.</p>
<p> This new contract is more of a departure from our original design. It has an extra piece of state that tracks how many times it has been called, and it allows for different operands to be used in the addition. It is a valid upgrade path to go from <code>AddV1</code> to <code>AddV3</code>.</p>
</li>
</ol>
<p>    When upgrading a ZkApp on Mina, it's important to remember the following:</p>
<ol>
<li><p><strong>State Order Consistency</strong>: If you change the order of state variables in your upgraded contract, the upgrade will fail because the contract's state will no longer match the expected order. Mina depends on the exact layout of state variables to maintain consistency, so reordering them will break the upgrade process.</p>
</li>
<li><p><strong>No State Reset</strong>: The state of your deployed contract will <strong>not be reset</strong> upon upgrade. This means that the data stored in the contract's state will persist across upgrades, and the contract will continue from its previous state.</p>
</li>
<li><p><strong>No Re-initialization</strong>: The init function will <strong>not be called</strong> again during an upgrade. This is important because it means you cannot use the upgrade process to modify or reinitialize the state, except for updating the verification key.</p>
</li>
<li><p><strong>Only Verification Key Changes</strong>: The only aspect of the smart contract that will be directly</p>
</li>
</ol>
<h1 id="heading-events"><strong>Events</strong></h1>
<p>    To use events in a ZkApp, you need to declare an <code>events</code> field in the smart contract. This field contains the names and types of the events that the contract can emit. Below is an example of how to define events in a smart contract:</p>
<pre><code class="lang-plaintext">    javascript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    // Declare an events field at the top level of the contract
</code></pre>
<pre><code class="lang-plaintext">    const events = {
</code></pre>
<pre><code class="lang-plaintext">      MessagePublished: Event({
</code></pre>
<pre><code class="lang-plaintext">        message: Field,
</code></pre>
<pre><code class="lang-plaintext">      }),
</code></pre>
<pre><code class="lang-plaintext">      StateUpdated: Event({
</code></pre>
<pre><code class="lang-plaintext">        stateRoot: Field,
</code></pre>
<pre><code class="lang-plaintext">      }),
</code></pre>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>    In this example:</p>
<p>    [if !supportLists]1.      [endif]<strong>Publishing Events</strong>: Once events are declared in the contract, you can emit them using the <code>emit</code> keyword within the smart contract's methods. This attaches arbitrary information to the transaction that observers can use.</p>
<p>    [if !supportLists]2.      [endif]<strong>Event Types</strong>: Events can include various types like <code>Field</code>, which represents a basic data type, or more complex structures like a Merkle tree root.</p>
<p>    [if !supportLists]3.      [endif]<strong>Off-Chain State</strong>: If your contract only stores a commitment (such as the root of a Merkle tree) on-chain, you can use events to communicate the changes in full to off-chain participants. This helps keep the full state updated off-chain by sending the relevant changes (like Merkle leaf changes) as events.</p>
<p>    In essence, events serve as a way to carry additional information that is not stored directly on-chain but can still be observed and used by external parties, enhancing the interactivity and functionality of ZkApps.</p>
<p>    [if !supportLists]1.      [endif]<strong>Event Types</strong>: While <code>Field</code> is simple for basic data, you can also use custom types like <code>Struct</code> to create more complex event data. For example, for Merkle tree leaves, it would be better to define a custom <code>Struct</code> to hold all the relevant information.</p>
<p>    [if !supportLists]2.      [endif]<strong>Custom Struct Example</strong>:</p>
<pre><code class="lang-plaintext">    javascript
</code></pre>
<pre><code class="lang-plaintext">    CopyEdit
</code></pre>
<pre><code class="lang-plaintext">    const MerkleLeaf = Struct({
</code></pre>
<pre><code class="lang-plaintext">      leafData: Field,
</code></pre>
<pre><code class="lang-plaintext">      proof: Field,
</code></pre>
<pre><code class="lang-plaintext">    });
</code></pre>
<pre><code class="lang-plaintext">    // Use this in events
</code></pre>
<pre><code class="lang-plaintext">    const events = {
</code></pre>
<pre><code class="lang-plaintext">      "add-merkle-leaf": Event({
</code></pre>
<pre><code class="lang-plaintext">        leaf: MerkleLeaf,
</code></pre>
<pre><code class="lang-plaintext">      }),
</code></pre>
<pre><code class="lang-plaintext">      "update-merkle-leaf": Event({
</code></pre>
<pre><code class="lang-plaintext">        leaf: MerkleLeaf,
</code></pre>
<pre><code class="lang-plaintext">      }),
</code></pre>
<pre><code class="lang-plaintext">    };
</code></pre>
<p>    In this scenario, each event would now carry a <code>MerkleLeaf</code> struct containing the relevant data for each leaf, making the event much more useful for tracking changes to the Merkle tree.</p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>    Events are a powerful tool for allowing off-chain observers to track changes in the smart contract's state. By using events like <code>add-merkle-leaf</code> and <code>update-merkle-leaf</code>, you can pass along valuable information with each transaction, ensuring that changes to things like a Merkle tree can be followed off-chain without needing to store all the tree data on-chain.</p>
<p>    Some important facts about events:</p>
<ul>
<li><p>Events are not stored on-chain. Only events from the most recent couple of transactions are retained by consensus nodes. After that, the events are discarded, but are still accessible on archive nodes.</p>
</li>
<li><p>You can't refer to previously emitted events in a smart contract, because there is no way of proving that the events you refer to are actually the events emitted by that contract.</p>
</li>
</ul>
<h1 id="heading-actions-amp-reducer"><strong>Actions &amp; Reducer</strong></h1>
<p>    In zkApps, <strong>actions</strong> provide a powerful mechanism for handling state changes and interactions between users, going beyond what is possible with events. Here are some key concepts about actions and their use in zkApps:</p>
<ol>
<li><p><strong>Actions vs. Events</strong>:</p>
<ul>
<li><p><strong>Events</strong> are used to emit information without interacting with the contract's internal state. They are not stored on-chain and cannot be referred to within a contract.</p>
</li>
<li><p><strong>Actions</strong>, on the other hand, are used to change the state and can be processed in the smart contract. Unlike events, actions are tied to the contract’s state history and can be proven to have been dispatched, making them more powerful and versatile.</p>
</li>
</ul>
</li>
<li><p><strong>ActionState</strong>:</p>
<ul>
<li>Each account in a zkApp has an <strong>actionState</strong> that stores a history of actions dispatched to it. This enables the smart contract to process past actions, giving it the ability to work with a history of state changes.</li>
</ul>
</li>
</ol>
<p>        for more info: <a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/fetch-events-and-actions#events">https://docs.minaprotocol.com/zkapps/writing-a-zkapp/feature-overview/fetch-events-and-actions#events</a>, <a target="_blank" href="https://docs.minaprotocol.com/zkapps/writing-a-zkapp">https://docs.minaprotocol.com/zkapps/writing-a-zkapp</a></p>
]]></content:encoded></item></channel></rss>