<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by こみー / Ryo Komiyama on Medium]]></title>
        <description><![CDATA[Stories by こみー / Ryo Komiyama on Medium]]></description>
        <link>https://medium.com/@ryokomy?source=rss-79baae68da79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*wL9OIMdNBQaxl4y5Xx4TdA.png</url>
            <title>Stories by こみー / Ryo Komiyama on Medium</title>
            <link>https://medium.com/@ryokomy?source=rss-79baae68da79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:55:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryokomy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kyuzan NFT Marketplace]]></title>
            <link>https://medium.com/kyuzan/kyuzan-nft-marketplace-1b81a3250a07?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b81a3250a07</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[marketplaces]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 09:32:24 GMT</pubDate>
            <atom:updated>2019-05-21T09:35:51.042Z</atom:updated>
            <content:encoded><![CDATA[<h4>ERC721規格のNon-Fungible Token (NFT) をC2Cで取引できる多機能マーケットプレイスの提供</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ieT8cGtusFm5SYqM" /><figcaption>Photo by <a href="https://unsplash.com/@staticlaw?utm_source=medium&amp;utm_medium=referral">Fabrizio Conti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>こんにちは、株式会社Kyuzanの小宮山です。</p><p>本記事では、我々がブロックチェーン事業者向けに開発した「Kyuzan NFT Marketplace」を紹介し、そのシステム構成や開発した上で得たTipsを共有します。より詳細な情報を知りたい方や実際に動いているデモを見たい方は気軽に<a href="https://kyuzan.com/contact-us">HP</a>か<a href="http://contact@kyuzan.com/">メール</a>にてご連絡ください。</p><p>オンチェーンのみで作るマーケットプレイスと比べ、OpenSeaやKyuzan NFT Marketplaceのように「Gas削減のためにオフチェーン要素を組み込んだ多機能なマーケットプレイス」は、どうしても大規模なシステムになってしまいます。ブロックチェーン上でデジタルアセットとしてトークンを発行したいと考えている事業者様やプロダクト開発者様に本システムを自社のシステムに組み込める形で技術提供できればと思います。</p><h3>目次</h3><ol><li><strong>Kyuzan NFT Marketplace とは<br></strong>1.1. Tokenの出品<br>1.2. Tokenの購入<br>1.3. Tokenへのオファー<br>1.4. その他の機能</li><li><strong>システム構成<br></strong>2.1. 構成要素</li><li><strong>開発から得たTips</strong><br>3.1. システム設計<br>3.2. 取引のシーケンス図</li><li><strong>まとめ</strong></li><li><strong>おまけ: Kyuzan Blockchain Studio</strong></li></ol><h3><strong>1. </strong>Kyuzan NFT Marketplaceとは</h3><p>Kyuzan NFT Marketplaceは、OpenSeaのようにユーザー同士がERC721準拠のNFT(Non-Fungible Token)を取引するためのマーケットプレイスです。利用するには、<a href="https://metamask.io/">MetaMask</a>や<a href="https://trustwallet.com/">Trust Wallet</a>のようなブラウザの機能を拡張するEthereumウォレットが必要です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzLZTbHPT2J-s4AkBStp4A.png" /><figcaption>Kyuzan NFT Marketplace</figcaption></figure><h4>1.1. Tokenの出品</h4><p><strong>1.1.1. 固定価格<br></strong>固定価格販売では、売り手はTokenの価格と販売期間を指定して、Tokenを出品します。 期間内に買い手が現れない場合、Tokenの出品はキャンセルされます。</p><p><strong>1.1.2. ダッチオークション<br></strong>ダッチオークションは、時間の経過とともにTokenの価格が下がっていく販売方法です。 これはTokenの適正価格がわかりづらい場合に有効で、NFTの販売時によく利用されています。 ダッチオークションでは、売り手はTokenの初期価格と最終価格、また、価格が最終価格まで推移する期間を指定してToken出品します。</p><p><strong>1.1.3. イングリッシュオークション<br></strong>イングリッシュオークションは、いわゆる「オークション」として一般に認知されている販売方法で、売り手は初期価格とオークション期間を入力してTokenを出品します。 Tokenの価格は買い手の入札によって引き上げられていき、オークション期間が終了した時点で最高額を入札していた人が落札できます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aJ5SdYlz6wXEm3zWZoEzbw.gif" /><figcaption>固定価格でのTokenの出品</figcaption></figure><h4>1.2. Tokenの購入</h4><p>出品されているTokenは、誰でも購入することができます。</p><p>固定価格・ダッチオークションで出品されたTokenは、購入者がETHを入金した瞬間に取引が完了します。</p><p>イングリッシュオークションで出品されたTokenは、オークション期間が終了すると、自動的に取引が完了します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*gldVi_BtH6DV4oWdKFzspQ.gif" /><figcaption>Tokenの購入</figcaption></figure><h4>1.3. Tokenへのオファー</h4><p>自分が欲しい「出品されていない」Tokenに対してオファーを出すことができます。 そのオファーがTokenの持ち主によって承認されれば取引が成立します。</p><p>これは、デジタルアセット(ここではTokenと同義)がブロックチェーンで管理されることによって実現した特徴です。ブロックチェーンを使うことによって、全てのユーザーは出品されたアセットだけではなく「出品されていないアセット」をも見ることができるようになり、それらのアセットにオファーを出せるようになりました。</p><h4>1.4 その他の機能</h4><p><strong>1.4.1. ソート・フィルタ<br></strong>自分の欲しいモンスターを見つけるために、ソートとフィルタの機能を実装しています。</p><p><strong>1.4.2. Like<br></strong>TokenにはLikeをつけることができます。 Likeの数は、Tokenの価値が市場に決められる際の、1つの指標となります。</p><p><strong>1.4.3. Transaction履歴<br></strong>Tokenが取引された記録を見ることができます。</p><p><strong>1.4.4. お知らせ<br></strong>出品したTokenが買われたタイミングなど、決められたタイミングでお知らせする機能があります。</p><h3>2. システム構成</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBeYjlqDYilGEr6V0nYTxg.png" /><figcaption>Kyuzan NFT Marketplace のシステム構成</figcaption></figure><h4>2.1. 構成要素</h4><p><strong>クライアント（Marketplace Client）<br></strong>ユーザーは、Ethereumウォレットが内蔵されたブラウザを使ってマーケットプレイスにアクセスします。</p><p><strong>マーケットプレイス (Marketplace)<br></strong>マーケットプレイスはGoogle Cloud Platform上に構築されており、以下の４つの要素で構成されています。</p><ul><li>フロントエンド (server front-end)<br>クライアントが実際にアクセスする部分です。</li><li>バックエンド サーバー (server back-end)<br>フロントエンドにAPIを提供しています。</li><li>バックエンド ワーカー (worker)<br>ブロックチェーン側の監視をし、データベースの状態を適切に保ちます。GAEのstandard環境はリクエスト時にインスタンスを立ち上げる仕組みのため、workerにはflexible環境を使用する必要があります。</li><li>データベース (db)<br>出品情報やトークンの情報を管理しています。</li></ul><p><strong>マーケットプレイス コントラクト (Marketplace Contract)</strong><br>マーケットプレイスのオンチェーン要素です。<br>Kyuzan NFT Marketplaceは、出品をはじめ多くの処理をオフチェーンで実現しています。一方で、ETHとNFTの交換を不可分に実行したい「取引の確定」時などは、このコントラクトを使ってオンチェーンで処理します。</p><p><strong>キーマネージャー (Key Manager)<br></strong>オフチェーン要素を持ったMarketplaceには、取引の仲介役であるRelayerが存在します。そのRelayerのイーサリアムアカウントを安全にクラウド上で使用するために、キーマネージャーを使って管理しています。<br>この「クラウド上で秘密鍵を安全に扱う」機能はマーケットプレイスに限ったものではないため、マイクロサービスとして切り分けてあります。</p><p><strong>ブロックチェーン エクスプローラー (Blockchain Explorer)<br></strong>ブロックチェーン上のデータを見ることは、速さ・検索しやすさの両面でデータベース上のデータを見るよりも大変です。<br>ブロックチェーンエクスプローラーは、指定したコントラクトを常に監視することで、データベース上にコントラクトのデータをコピーし続けます。こうすることで、他のサービスは直接ブロックチェーンを見る必要がなくなり、オンチェーン情報を簡単かつ迅速に参照することができるようになります。<br>この部分も、マーケットプレイスに限ったものではないため、マイクロサービスとして切り分けてあります。</p><p><strong>ERC721トークン (ERC721 Contracts)</strong><br>イーサリアムのNFT規格であるERC721に準拠したトークンが、マーケットプレイスでの取引対象となります。</p><h3>3. <strong>開発から得た</strong>Tips</h3><h4>3.1. システム設計</h4><p>NFTのマーケットプレイスには様々な種類があります。どのような目的でマーケットプレイスを設計するかによって、システム設計が大きく異なってくることが分かりました。</p><p><strong>3.1.1. NFTマーケットプレイスの分類</strong></p><p>NFTのマーケットプレイスには様々な種類がありますが、それらを分類する上での重要な要素の１つに「gasがどこで発生するか」があります。</p><p>Ethereumというブロックチェーンの特性上、１つの処理を行うたびにgasと呼ばれる手数料を払う必要がありますが、これはコスト的にもUX的にもユーザーにストレスを与えます。たとえば、出品したり取り下げたりするたびに手数料を取られてしまうのでは、積極的なTokenの売買が行われなくなる可能性があります。このように「gasがどこで発生するか」による分類は、ある意味「使いやすさ」による分類とも言えるかもしれません。</p><p>このgasの発生による使いづらさを解決するために、多くのマーケットプレイスはオフチェーン要素を取り入れています。</p><p>例えば、流通量が世界一のマーケットプレイスであるOpenSeaは、初めは全てオンチェーンで実装されていましたが、今では一部の機能がオフチェーンとなり、gasの発生箇所を減らしています。</p><p><a href="https://medium.com/opensea/sell-your-crypto-collectibles-without-paying-gas-77d2a7477612">Sell your crypto collectibles without paying gas!</a></p><p>一方で、オフチェーン要素を増やしてgasを削減することは、開発コストを大幅に引き上げます。まず、ブロックチェーンという堅牢なシステムを放棄することで、自分たちで十分に堅牢なシステムを作り直す必要が出てきます。また、データとロジックがブロックチェーン上とサーバー上の両方に存在することになるため、それらの整合性を保つ仕組みも必要になります。そのため、ブロックチェーン以外にも多くの専門知識が必要になり、開発工数が増えるだけでなく、それらを開発できる人材も限られてきます。</p><p>別の重要な分類要素として、「非中央集権性」があります。多くの仮想通貨取引所では、それぞれのユーザーのwalletを取引所が管理していますが、それに対し、ほとんど全てのNFTマーケットプレイスでは、ユーザー自身が自分の秘密鍵を管理しています。このように「秘密鍵をユーザー自身が管理する」取引所をDEX(Decentralized Exchange)と呼びます。このDEXという言葉には注意が必要で、それは、DEXだからといって、完全に「非中央集権で、中央管理者がいない」わけではない点です。実際にOpenSeaやRareBitsといった有名なNFTマーケットプレイスもDEXではありますが、UX向上のために、その一部を中央管理者がサーバー上で運営しています。</p><p>現状のマーケットプレイスにおいて、UXと非中央集権性はトレードオフであり、その部分をどう設計するかで、それぞれのマーケットプレイスの特色が決まってきます。</p><p><a href="https://blog.coinbase.com/the-playful-paradigm-shift-4bf35d9d1d11">The Playful Paradigm Shift</a></p><p><strong>3.1.2 Kyuzan NFT Marketplaceの設計方針</strong></p><p>Kyuzan NFT Marketplaceは、「1番使いやすいマーケットプレイス」を設計の指針とし、非中央集権性にはある程度目をつむっています。</p><p>そのため、出品や出品の取り下げといった細かい部分にgasがかからないように、適宜オフチェーン要素を取り入れています。</p><p>一方で、イングリッシュオークションはオンチェーンでの実装がメインで、出品や入札にはその都度gasがかかります。これは、「gasがいちいち発生する」問題よりも、「落札されたのにETHが支払われない」問題や「落札してETHを支払ったのにTokenが送られてこない」問題のほうが優先して解決すべき課題だと思ったからです。そのために、イングリッシュオークションでは、売り手は出品時にdepositの入金が必要であり、買い手は入札時に入金が必要です。これらはオンチェーンで行われるため、そこには当然gasも発生します。</p><p>これらの設計は全て「1番使いやすいマーケットプレイス」という設計方針に基づいており、これから追加実装することがあれば、それらの実装も全てこの設計方針にのっとっていく予定です。</p><p>例えば、現状のマーケットプレイスの使いづらさとして、値段ソートが機能していない点があげられると思います。OpenSeaで1番高いCryptoKittiesのTokenを探そうとしても、誰かが出品したTokenが10,000,000,000ETHで表示されたりしてしまいます。これは明らかにソートが機能していない状態であり、「使いやすい」マーケットプレイスにとっては解決すべき課題です。</p><p>解決策としては、Tokenの価格を分析し、「過去に売れた価格の2倍以上の値段はつけられない」などといった制約をつけることが考えられますが、この方法も実現するにはまた工夫が必要そうです。</p><h4>3.2. 取引のシーケンス図</h4><p>以下は、固定価格取引におけるシーケンス図です。このシーケンス図を追いながら、いくつかの開発Tipsを示します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FC_5OnVRagaHEwodF39SQw.png" /><figcaption>固定価格取引のシーケンス図</figcaption></figure><p><strong>3.2.1 出品</strong></p><p>図中のCreateListingが出品の処理です。本システムでは、１つ１つの取引をListingと呼んでいます。<br>ポイントは、対象のERC721トークンにおいて、SellerがRelayer(Serverが持つアカウント)にisApprovedForAllがtrueかを確認している点です。この値はERC721の規格で定められており、これがtrueであれば、RelayerはSellerが持つTokenを自由にTransferすることができます。<br>これを確認した上で、サーバー上に出品情報を記録しています。</p><p><strong>3.2.2 購入</strong></p><p>図中のBuyingListingが購入の処理です。<br>1つ目のポイントは、ServerがBuyerに対してRelayerのsignatureを含んだraw transactionを渡している点です。これによって、最終的にTransactionにSignしBroadcastするのはBuyerであっても、Relayerが指定した(と証明できる)情報をコントラクトまで届けることができます。ここにTokenの価格などを仕込んでおくことで、SellerによってRelayerに伝えられた適切な価格での取引が実現されます。<br>これらの技術的な説明は別の記事でしているので、そちらを参照して見てください。</p><p><a href="https://medium.com/kyuzan/ethereum-%E3%82%A4%E3%83%BC%E3%82%B5%E3%83%AA%E3%82%A2%E3%83%A0%E3%81%AE%E3%83%88%E3%83%A9%E3%83%B3%E3%82%B6%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AB%E7%BD%B2%E5%90%8D%E4%BB%98%E3%81%8D%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%9F%8B%E3%82%81%E8%BE%BC%E3%81%BF-%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%81%A7%E3%81%9D%E3%81%AE%E7%BD%B2%E5%90%8D%E3%82%92%E6%A4%9C%E8%A8%BC%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95-c65465319b7d">Ethereum: イーサリアムのトランザクションに署名付きデータを埋め込み、コントラクトでその署名を検証する方法</a></p><p>2つ目のポイントは、BuyerがExchangeContractから受け取ったtransaction hash(取引IDとして利用)をサーバーに返して処理が終了している点です。Ethereum上の処理には30秒ほどの時間がかかるため、この時点で取引はまだ完了していないのですが、この長い待ち時間で通信が途切れてしまう可能性を考慮して、その後についてはworkerに任せています。</p><p><strong>3.2.3. workerによる取引完了の確認</strong></p><p>3.2.2で示したように、取引完了の確認はworkerによってなされます(図中のProcessBuying)。記録されたtransaction hashを追うことで、pending状態だった取引の完了を検知します。<br>この他にも、workerはTokenのTransferや、isApprovedForAllの状態変化なども監視しています。出品中のTokenに対してこれらの処理がなされると、正常に取引ができなくなるので、これらを監視し、発見され次第出品を取り消すようにしています。</p><p><strong>3.2.4 イングリッシュオークションとオファー</strong></p><p>ダッチオークションもこのシーケンス図とほとんど同じ流れになりますが、イングリッシュオークションとオファーについては、基本的にはオンチェーンでおこなっているため、処理の流れが異なります。<br>本記事での詳しい説明は割愛しますが、以下のポイントだけは、押さえておくといいと思います。</p><p>Metamaskに「signしたtransactionをブロードキャストせずに返す (web3.eth.signTransaction)」機能は実装されていない。</p><blockquote>We don’t and won’t support signing a transaction without submitting it, because it becomes a giant footgun in terms of nonce calculation inside MetaMask.</blockquote><p><a href="https://github.com/MetaMask/metamask-extension/issues/3475">Sign transaction without broadcast · Issue #3475 · MetaMask/metamask-extension</a></p><p>この制約はMetamaskに限らずほとんどのdAppsブラウザに当てはまるため、「オファーする段階で、buyerがsignした購入transactionをサーバーが受け取っておき、サーバー上でオファーが成立したらそのtransactionをbroadcastする」といった設計が不可能になります。</p><p>以上、簡単にですが、開発時のTipsをいくつか共有させてもらいました。</p><h3>4. まとめ</h3><p>本記事では、Kyuzan NFT Marketplaceの概要、システム構成、その開発を通じて得たTipsを紹介しました。この記事が、NFTマーケットプレイスの仕組みを理解する手助けになってくれたら幸いです。</p><p>一方で、この記事の中では紹介しきれなかった内容も多数ありますので、今後もこういった記事という形で共有していけたらいいなと思います。</p><p>このようなNFT向けのマーケットプレイスやオークションシステムにご興味がある方は<a href="/service/mailto:contact@kyuzan.com">こちら</a>まで気軽にご連絡ください。</p><h3>5. おまけ: Kyuzan Blockchain Studio</h3><p>Kyuzanは東京を拠点としたブロックチェーンスタートアップです。</p><p>我々のミッションは「ブロックチェーン技術を実際のビジネスに取り入れる」ことで、日々、実用的なプロダクトの企画・研究・開発をおこなっています。</p><p>これらの取り組みは <strong>Kyuzan Blockchain Studio </strong>という形で、大企業からスタートアップまで全てのみなさまに開かれておりますので、興味のある方はぜひご連絡下さい。</p><p>contact@kyuzan.com</p><p>特に、既存のビジネスで強みを持った方々と、Kyuzanのブロックチェーン技術・デザインを掛け合わせて、まだ世界に事例の無い独創的なプロダクトを作りたいと思っています。よろしくお願いします。</p><p><a href="https://kyuzan.com/">Kyuzan Inc.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b81a3250a07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/kyuzan-nft-marketplace-1b81a3250a07">Kyuzan NFT Marketplace</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum: イーサリアムのトランザクションに署名付きデータを埋め込み、コントラクトでその署名を検証する方法]]></title>
            <link>https://medium.com/kyuzan/ethereum-%E3%82%A4%E3%83%BC%E3%82%B5%E3%83%AA%E3%82%A2%E3%83%A0%E3%81%AE%E3%83%88%E3%83%A9%E3%83%B3%E3%82%B6%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AB%E7%BD%B2%E5%90%8D%E4%BB%98%E3%81%8D%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%9F%8B%E3%82%81%E8%BE%BC%E3%81%BF-%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%81%A7%E3%81%9D%E3%81%AE%E7%BD%B2%E5%90%8D%E3%82%92%E6%A4%9C%E8%A8%BC%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95-c65465319b7d?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65465319b7d</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Tue, 25 Dec 2018 06:41:14 GMT</pubDate>
            <atom:updated>2018-12-25T07:20:19.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ED-yuuugY-I-oF5u" /><figcaption>Photo by <a href="https://unsplash.com/@mjolnir?utm_source=medium&amp;utm_medium=referral">Dominik Rešek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>この記事では、イーサリアム（Ethereum）のトランザクションに署名付きデータを埋め込み、その署名をコントラクトで検証する方法を説明する。</p><p>システム内にこの仕組みを取り入れることで、一部の処理をオフチェーンで実行でき、不要なgasの削減や処理の高速化を実現できる。</p><ol><li>トランザクションの署名</li><li>トランザクション内データの署名</li><li>具体的な署名・検証の実装方法</li><li>まとめ</li></ol><p>参考資料</p><h3>1. トランザクションの署名</h3><p>イーサリアムのトランザクションは、必ず送信者によって署名がされている。こうすることで、誰でも<strong>そのトランザクションの送信者</strong>を検証できる。</p><p>この署名には、ECDSA（Elliptic Curve Digital Signature Algorithm）というアルゴリズムが用いられている。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeMpochoxwxR4f_0blZqbg.png" /></figure><h3>2. トランザクション内データの署名</h3><p>ECDSAは、Solidity側でもWeb3側でも簡単に使える仕組みが提供されている。</p><p>そのため、トランザクションの署名と同じ要領で、トランザクションの中身に署名をすると、<strong>そのトランザクションに書かれている内容の一部が、トランザクション送信者以外の誰かによって書かれた（その人物の許可を得ている）こと</strong>を検証できる。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puctpRD5ktD96ZAZTXCKhw.png" /></figure><h4><a href="https://0x.org/">0x Protocol</a>での利用例</h4><p>0x ProtocolとはDEXの仕組みの１つで、0x Protocolに準拠したDEXは、注文部分をオフチェーンでおこなう。0x Protocolの仕組みは、Off-chain order relay On-chain settlementという言葉で表されている。</p><p>この仕組みを上の図に対応させる。</p><p>まず売り手(0xC)は、以下の内容(一部割愛してある)に署名をして、order(signed data)を作成する。</p><ul><li>売り手のアドレス</li><li>売りたいtokenとその量</li><li>買いたいtokenとその量</li></ul><p>作成されたorderは、order bookと呼ばれるリスト（オフチェーン）に追加される。</p><p>買い手(0xAに対応)は、order bookから好きなorderを選び、そのorderをデータとして含んだtransactionを作ることで、取引を成立させる。（オンチェーン）</p><p>このとき、最終的なtransactionは買い手によって作成されているが、取引内容は売り手が決定できていることに注意する。</p><p>このように0x Protocolでは、注文部分をオフチェーンで処理することによって、不要なgasの発生を防いでいる。（注文の作成・取り消しにかかるはずのgasを削減できている。）</p><h3>3. 具体的な実装方法</h3><p>トランザクション内データに署名することの有用性を理解したので、最後に具体的な実装を見ていく。ここでは、以下の流れを確認することを目的とする。</p><p>3.1. Web3を使ったオフチェーンでの署名<br>3.2. Web3を使ったオフチェーンでの検証 (optional)<br>3.3. Solidityを使ったオンチェーンでの検証</p><p>全体の実装例は、以下のリポジトリに公開している。</p><p><a href="https://github.com/ryokomy/solidity-ecdsa-example/tree/master">ryokomy/solidity-ecdsa-example</a></p><h4>3.1. Web3を使ったオフチェーンでの署名</h4><p>signatureを得るための関数は<a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#sign">web3.eth.accounts.sign</a>を使うといい。</p><p>その際、あらかじめmessageをhashしておくのがよく(bytes32にしておくのがよく)、それには<a href="https://web3js.readthedocs.io/en/1.0/web3-utils.html?highlight=soliditysha3#soliditysha3">web3.utils.soliditySha3</a>が有用である。この関数は、引数をSolidityと同じように扱ってくれるため、後述するSolidity側での検証が可能になる。(例えば、正のnumberはuint256として扱う。)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b80341a07369bebf6a1d6b3c2e7e59/href">https://medium.com/media/37b80341a07369bebf6a1d6b3c2e7e59/href</a></iframe><h4>3.2. Web3を使ったオフチェーンでの署名の検証 (optional)</h4><p>署名の検証には<a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#recover">web3.eth.accounts.recover</a>を使うといい。</p><p>この際デフォルトでは内部的に、署名対象のデータ(messageHash)がhashされる(正確には、prefixをつけてhashされる)ことに注意する。この処理を明示的に書いたのがコメントアウトされた行で、verifiedAddressから始まる２つの行は、どちらの行をコメントアウトしても動作する。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8593448f45276bf7d6232dd996a9f6f/href">https://medium.com/media/f8593448f45276bf7d6232dd996a9f6f/href</a></iframe><p>この例では、signedAddressとverifiedAddressが同じになることが確認できる。</p><h4>3.3. Solidityを使ったオンチェーンでの署名の検証</h4><p>3.2. と同じことをSolidity側で行なっているのが、以下の例である。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/165ba570c9a947fd0614ddb2671323b9/href">https://medium.com/media/165ba570c9a947fd0614ddb2671323b9/href</a></iframe><p>この際、ライブラリとして<a href="https://github.com/OpenZeppelin/openzeppelin-eth/blob/master/contracts/cryptography/ECDSA.sol">OpenZeppelinのECDSA</a>を利用している。Solidity側では、上述の内部的なhashを明示的に記述する必要がある。 (toEthSignedMessageHash)</p><p>ここで得られるverifiedAddressは、3.2で得たverifiedAddressと同じ結果になる。</p><h3>4. まとめ</h3><p>トランザクションの内部データに署名をすることで、<strong>そのトランザクションに書かれている内容（の一部）が誰かの許可を得ていること</strong>を検証できる。</p><p>これらは、不要なgasの削減や処理の高速化に役立ち、Web3・OpenZeppelinのライブラリを使うことで、比較的簡単に実装することができる。</p><h3>5. 参考資料</h3><h4><strong>ECDSA</strong></h4><ul><li><a href="https://ja.wikipedia.org/wiki/%E6%A5%95%E5%86%86%E6%9B%B2%E7%B7%9ADSA">楕円曲線DSA - Wikipedia</a></li><li><a href="https://zoom-blc.com/what-is-ecdsa">ECDSAによる署名生成と検証の仕組みを分かりやすく解説</a></li></ul><h4><strong>0x Protocol</strong></h4><ul><li><a href="https://0x.org/">0x公式</a></li><li><a href="https://medium.com/@tomoyaishida/0x%E3%83%97%E3%83%AD%E3%83%88%E3%82%B3%E3%83%AB%E3%81%AE%E6%A6%82%E8%A6%81%E3%81%A8%E6%B3%A8%E7%9B%AE%E3%81%99%E3%81%B9%E3%81%8D%E7%90%86%E7%94%B1-3d09acae3f67">0xプロトコルの概要と注目すべき理由</a></li></ul><h4><strong>Web3</strong></h4><ul><li><a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#sign">web3.eth.accounts.sign</a></li><li><a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#recover">web3.eth.accounts.recover</a></li><li><a href="https://web3js.readthedocs.io/en/1.0/web3-utils.html#soliditysha3">web3.utils.soliditySha3</a></li><li><a href="https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#hashmessage">web3.eth.accounts.hashMessage</a></li></ul><h4><strong>OpenZeppelin</strong></h4><ul><li><a href="https://github.com/OpenZeppelin/openzeppelin-eth/blob/master/contracts/cryptography/ECDSA.sol">OpenZeppelin/openzeppelin-eth/contracts/cryptography/ECDSA.sol</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65465319b7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/ethereum-%E3%82%A4%E3%83%BC%E3%82%B5%E3%83%AA%E3%82%A2%E3%83%A0%E3%81%AE%E3%83%88%E3%83%A9%E3%83%B3%E3%82%B6%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%81%AB%E7%BD%B2%E5%90%8D%E4%BB%98%E3%81%8D%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%9F%8B%E3%82%81%E8%BE%BC%E3%81%BF-%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%81%A7%E3%81%9D%E3%81%AE%E7%BD%B2%E5%90%8D%E3%82%92%E6%A4%9C%E8%A8%BC%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95-c65465319b7d">Ethereum: イーサリアムのトランザクションに署名付きデータを埋め込み、コントラクトでその署名を検証する方法</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (後半)]]></title>
            <link>https://medium.com/kyuzan/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%BE%8C%E5%8D%8A-284a0c9ff4ae?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/284a0c9ff4ae</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 03:38:55 GMT</pubDate>
            <atom:updated>2019-04-03T09:06:08.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V2Dt9zj7e8hxBn0d" /><figcaption>“snow covered rocky mountain under clear sky at daytime” by <a href="https://unsplash.com/@julian_zett?utm_source=medium&amp;utm_medium=referral">Julian Zett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://goo.gl/fp6nsM">前半</a>では、アップグレード可能なコントラクトの仕組みについて説明した。</p><p><a href="https://medium.com/kyuzan-engineering-blockchain-jp/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%89%8D%E5%8D%8A-8c6c522b31ba">ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (前半)</a></p><p>後半である本記事では、実際にZeppelinOSを使用した実装について説明する。</p><ol><li>ZeppelinOSとは？</li><li>ZeppelinOSを使ってアップグレード可能なコントラクトを実装する<br>2.1. zosアプリケーションのセットアップ<br>2.2. zos-libのインストール<br>2.3. MyContract.solを実装<br>2.4. MyContractをzosアプリケーションに登録<br>2.5. Ganacheにコントラクトをデプロイ<br>2.6. Proxy Contractのデプロイ<br>2.7. コントラクトのアップグレード</li><li>まとめ</li></ol><h3>1. ZeppelinOSとは？</h3><p>ZeppelinOSは、アップグレード可能なコントラクトを実装するためのフレームワークで、そのためのライブラリやCLI (zosコマンド)を提供してくれている。</p><p><a href="https://zeppelinos.org/">ZeppelinOS</a></p><p>ZeppelinOSにおけるProxy Contractの設計パターンは、前半の「2. 参考：アップグレード可能なコントラクトの詳細な理解」で見た「非構造化ストレージパターン」になっている。それらの旨は、以下の記事で紹介されている。</p><p><a href="https://blog.zeppelinos.org/proxy-patterns/">Proxy Patterns - ZeppelinOS Blog</a></p><h3>2. ZeppelinOSを使ってアップグレード可能なコントラクトを実装する</h3><p>実装の仕方は、以下の公式ドキュメントを参考にしている。</p><p><a href="https://docs.zeppelinos.org/docs/start.html">ZeppelinOS · ZeppelinOS</a></p><p>今回は、実際にコントラクトをデプロイし、そのコントラクトをアップグレードするところまでを説明する。ここでの実装は、以下に載せておいた。</p><p><a href="https://github.com/ryokomy/upgradable-test-zeppelinos">ryokomy/upgradable-test-zeppelinos</a></p><h4>2.1. zosアプリケーションのセットアップ</h4><p>以下のコマンドで、zos (ZeppelinOSのCLI)を使ったアプリケーションをセットアップする。</p><pre>$ mkdir my-app &amp;&amp; cd my-app<br>$ npm init<br>$ zos init my-app</pre><p>zos.jsonには、アプリケーションの設定が記述される。</p><h4>2.2. zos-libのインストール</h4><p>アップグレード可能なコントラクトを実現するための仕組みは、zos-libに実装されている。 npmでインストールする。</p><pre>$ npm install zos-lib</pre><h4>2.3. MyContract.solの実装</h4><p>以下のようにcontracts/MyContract.solを実装する。</p><pre>pragma solidity ^0.4.21;<br>import &quot;zos-lib/contracts/migrations/Migratable.sol&quot;;</pre><pre>contract MyContract is Migratable {<br>  uint256 public x;</pre><pre>function initialize(uint256 _x) isInitializer(&quot;MyContract&quot;, &quot;0&quot;) public {<br>    x = _x;<br>  }<br>}</pre><p>zosを使う場合、自前のコントラクトはMigratableというコントラクトを継承させ、 constructorの代わりにinitializeを持たせる。</p><h4>2.4. MyContractをzosアプリケーションに登録</h4><p>実装したコントラクトをネットワーク上にデプロイする前に、zosアプリケーションに認知させる必要がある。そのために、 zos add を使う。</p><pre>$ zos add MyContract</pre><p>これによって、zos.jsonに以下の行が追加され、MyContractがzosアプリケーションに組み込まれたことが分かる。</p><pre>&quot;contracts&quot;: {<br>  &quot;MyContract&quot;: &quot;MyContract&quot;<br>}</pre><h4>2.5. Ganacheにコントラクトをデプロイ</h4><p>今回はテストネットワークとして、Ganacheを使用する。</p><p><a href="https://truffleframework.com/ganache">Ganache | Truffle Suite</a></p><p>zos init でtruffle-config.jsが生成されているので、このポートをganacheが使用している7545に変更する。</p><p>以下のコマンドで、コードをネットワーク上にデプロイする。</p><pre>$ zos push --network local</pre><p>これによって、以下のzos.local.jsonが生成される。localの部分には、指定したネットワーク名が入る。</p><pre>{<br>  &quot;<strong>contracts</strong>&quot;: <strong>{</strong><br>    &quot;<strong>MyContract</strong>&quot;: {<br>      &quot;address&quot;: &quot;0x1bfc7e8a8638c06e5993de2d9844f2f542a2fcba&quot;,<br>      &quot;constructorCode&quot;: &quot;608060405234801561001057600080fd5b50610b0d806100206000396000f300&quot;,<br>      &quot;bodyBytecodeHash&quot;: &quot;c829d0f89f2ee73f114364b2473387ebd483822f0418b301c33c988f531b989e&quot;,<br>      &quot;bytecodeHash&quot;: &quot;83cb3b4e80f79c781380024e9118f0d16d33eab3701d5bec5e4822c4d9826b56&quot;<br>    }<br>  <strong>}</strong>,<br>  &quot;<strong>proxies</strong>&quot;: <strong>{}</strong>,<br>  &quot;app&quot;: {<br>    &quot;address&quot;: &quot;0x94dbc3a51dcb94bf2657fb7439437784d946cd23&quot;<br>  },<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;package&quot;: {<br>    &quot;address&quot;: &quot;0x761930d1cc07ed590ce8563cfdf7dd46962432a7&quot;<br>  },<br>  &quot;provider&quot;: {<br>    &quot;address&quot;: &quot;0x469f85f8c4deeb35faeeaf6ecb0f3f2dbbfaf7d4&quot;<br>  }<br>}</pre><p>このファイルで注目すべきはcontractsプロパティとproxiesプロパティである。 現時点で、contractsプロパティにMyContractが追加されているが、proxiesプロパティには追加されていない。 つまり、今デプロイしたコードは、参照先のコントラクトであり、Proxy Contractはまだデプロイされていない。</p><p>また通常、 truffle migrate コマンドを使ってコントラクトをデプロイすると、build/contracts/MyContract.jsonのaddressプロパティにデプロイしたコントラクトのアドレスが記述されるが、この段階ではまだaddressプロパティがないことにも注意する。これも、Proxy Contractがまだデプロイされていないことに由来する。</p><h4>2.6. Proxy Contractのデプロイ</h4><p>Proxy Contractをデプロイするためには、以下のように、 zos create を使う。</p><pre>$ zos create MyContract --init initialize --args 42 --network local</pre><p>ここで、initオプションは、デプロイ後にinitialize関数を呼ぶことを意味し、argsオプションでその時の引数を指定している。</p><p>このコマンドによって、zos.local.jsonのproxiesプロパティに、MyContractの情報が追加される。 addressプロパティにProxy Contractのアドレスが、implementationプロパティに参照先コントラクトのアドレスが入っていることが確認できる。また、build/contracts/MyContract.jsonにも、addressプロパティが追加されている。ここに追加されたアドレスは、Proxy Contractのアドレスである。</p><p>truffle console を使ってProxy Contractにアクセスしてみると、xの値である42が読み取れることがわかる。</p><pre>$ npx truffle console --network=local<br>$ truffle(local)&gt; myContract = MyContract.at(&#39;&lt;your-proxy-address&gt;&#39;)<br>$ truffle(local)&gt; myContract.x()<br>BigNumber { s: 1, e: 1, c: [ 42 ] }</pre><h4>2.7. コントラクトのアップグレード</h4><p>実際にコントラクトをアップグレードしてみる。<br>MyContractのxを書き換える手段がなかったので、その機能を追加するためにMyContract.solを以下のように書き換えるとする。</p><pre>import &quot;zos-lib/contracts/migrations/Migratable.sol&quot;;</pre><pre>contract MyContract is Migratable {<br>  uint256 public x;</pre><pre>function initialize(uint256 _x) isInitializer(&quot;MyContract&quot;, &quot;0&quot;) public {<br>    x = _x;<br>  }</pre><pre>function increment() public {<br>    x += 1;  <br>  }<br>}</pre><p>これは参照先のコントラクトの変更なので、それをzosアプリケーションに伝えるには、もう一度 zos push を使う。</p><pre>$ zos push --network local</pre><p>これによって、zos.local.jsonのcontractsが変更される。MyContractのアドレスが変わっているのが確認できる。 ただ、これだけでは、デプロイされたProxy Contractには伝わっていない。デプロイされたProxy Contractの参照先を変更するために、 zos update を利用する。</p><pre>$ zos update MyContract --network local</pre><p>これによって、zos.local.jsonのproxiesプロパティにあるMyContractのimplementationプロパティが変更される。</p><p>これで、xを書き換えるために追加した関数が実行できる。</p><pre>$ npx truffle console --network=local<br>$ truffle(local)&gt; myContract = MyContract.at(&#39;&lt;your-proxy-address&gt;&#39;)<br>$ truffle(local)&gt; myContract.x()<br>BigNumber { s: 1, e: 1, c: [ 42 ] }<br>$ truffle(local)&gt; myContract.x()<br>$ truffle(local)&gt; myContract.increment()<br>BigNumber { s: 1, e: 1, c: [ 43 ] }</pre><h3>3. まとめ</h3><p>本投稿では、<a href="https://goo.gl/fp6nsM">前半</a>・後半に分けて、ZeppelinOSを使用してアップグレード可能なコントラクトを実装する、具体的な方法について説明した。<br>後半である本記事では、ZeppelinOSのセットアップから、一度デプロイしたコントラクトに、そのコントラクトのアドレスを変更することなく新しい関数を追加する手順までを説明した。</p><p>ここで、<a href="https://goo.gl/fp6nsM">前半の記事</a>を見るとわかるように、アップグレード可能なコントラクトは、自前で実装することも可能である。場合によっては、その方が融通がきいて、最適なコードを書くことができるかもしれない。</p><p>では、ZeppelinOSを利用する価値はどこにあるのだろうか。</p><p>それはやはり、<a href="https://github.com/OpenZeppelin/openzeppelin-solidity">OpenZeppelin</a>の開発で有名な<a href="https://zeppelin.solutions/">Zeppelin</a>の、信頼性の高いツールを簡単に使える、という点にあると思う。</p><p>特にSolidityによるコードは、金銭的な取引を含むコードが多いため、些細な実装ミスが深刻なトラブルを起こし兼ねない。そのような可能性を少しでも減らすために、信頼性のあるコードを利用することには、非常に大きな意味がある。</p><p>また、ZeppelinOSは<a href="https://github.com/OpenZeppelin/openzeppelin-zos">オープンソース</a>であるため、本当に必要な機能だけを、ZeppelinOSの上に自分で追加実装していくことが可能である。<br>これは例えば、ERC721準拠のTokenを開発するときに「<a href="https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC721">OpenZeppelinのERC721</a>を元にして、そこに自前の機能を追加していく」という開発方法とよく似ていて、合理的に思える。</p><p>こういった理由から、アップグレード可能なコントラクトを実装して見たい場合は、ZeppelinOSから始めてみるのがいいのではないかと思う。</p><p>そのための第一歩として、本記事が役に立てれば幸いである。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284a0c9ff4ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%BE%8C%E5%8D%8A-284a0c9ff4ae">ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (後半)</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (前半)]]></title>
            <link>https://medium.com/kyuzan/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%89%8D%E5%8D%8A-8c6c522b31ba?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c6c522b31ba</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 03:35:47 GMT</pubDate>
            <atom:updated>2018-09-18T23:32:46.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ofWg1okPhYPeN88P" /><figcaption>“photo of mountain during cloudy day” by <a href="https://unsplash.com/@wolfi?utm_source=medium&amp;utm_medium=referral">Wolfgang Lutz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ethereumにデプロイされたコントラクトのコードは、基本的に書き直すことができない。</p><p>コントラクトに機能を追加したい場合は新しいコントラクトを再度デプロイする必要があり、その際コントラクトのアドレスが変わってしまう。これでは、元のコントラクトをアップグレードしたとは言い難い。</p><p>しかし、実際にサービスを運営したい場合、コントラクトがアップグレード可能であることは重要な要素である。そうでなければ、リリース前に全てのバグをなくさなくてはならなくなる。この点には実際に我々も不自由さを感じたことがあり、以前<a href="https://goo.gl/b3xTvG">Ethoccer</a>というDappsを開発した際、リリース前に通常のWebサービスでは考えられないほどの緊張感があった。</p><p>ZeppelinOSは、アップグレード可能なコントラクトを記述するためのフレームワークであり、この問題を解決する手助けをしてくれる。</p><p><a href="https://zeppelinos.org/">ZeppelinOS</a></p><p>前半である本記事では、ZeppelinOSを使ってアップグレード可能なコントラクトを実装する上で、押さえておくべきポイントを説明する。実際にZeppelinOSを使用する部分については、<a href="https://goo.gl/3eskXM">後半の記事</a>にまとめる。</p><ol><li>アップグレード可能なコントラクトとは？<br>1.1. 通常のスマートコントラクト<br>1.2. アップグレード可能なスマートコントラクト</li><li>参考：アップグレード可能なコントラクトの詳細な理解</li></ol><h3>1. アップグレード可能なコントラクトとは？</h3><p>コントラクトの「アップグレード」には、以下の３つが含まれる。</p><ul><li>既存の関数の実装変更</li><li>新しい関数の追加</li><li>新しい変数の追加</li></ul><p>ここで注意しなくてはならないのが、「変数の削除」「変数の順番の変更」ができないことである。</p><p>アップグレード可能なスマートコントラクトの仕組みを理解することでそのような制約の原因もわかるのだが、それらを細部まで理解することは、意外と難しい。</p><p>なのでここでは、アップグレード可能なコントラクトの仕組みを感覚的に理解し、ZeppelinOSを使った開発ができるようになることを目的として説明しようと思う。</p><h4>1.1. 通常のスマートコントラクト</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fEU-Cvm5v5fygalJOV2UlA.png" /></figure><p>ContractAの関数fを使いたいとき、ユーザーはContractAのアドレス0xAにアクセスする。 関数fを変更したい場合、上述のようにコントラクトをデプロイし直さなくてはならないが、そのとき0xAというアドレスが変わってしまう。これをユーザーは知るすべがないため、運用中のコントラクトの関数を変更することは難しい。</p><p>また、コントラクトは独自のストレージを持ち、ストレージ変数を(特別な指定なしで)定義すると、このストレージの先頭から順番に領域が割り当てられていく。そのため、新しいコントラクトをデプロイし直してしまうと、0xAにあるContractAのストレージ変数に保存された値は、次のコントラクトに引き継がれない。</p><h4>1.2. アップグレード可能なスマートコントラクト</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_kEspNy_7JYyT1Ux4CSxw.png" /></figure><p><strong>1.2.1. 関数を変更・追加する仕組み</strong></p><p>通常のコントラクトと同様に、ユーザーはContractAの関数fを使うために、0xAにアクセスする。 このとき、ユーザーからすると、ContractAに関数fがあるように見えるのだが、実際にはfの実装はContractBに記述されている。 ContractAは、fが呼ばれたとき、ContractBのfを<strong>delegatecall*</strong>で参照するようになっている。(上図左)</p><p>* delegatecallとは「参照先のロジック」だけを使わせてもらうcallのことで、その関数実行でのストレージの操作は「呼び出し元のストレージ」に適用される。</p><p>このように設計することで、ContractAが参照するコントラクトのアドレスを変更すると、fの実装を変更することができるようになる(上図右)。参照を変更した後のコントラクト(ContractC)に新しい関数があれば、ContractAのアドレス0xAに対して、その関数を使用することも可能である。</p><p><strong>1.2.2. ストレージ変数を追加する仕組み</strong></p><p>ストレージ変数も、参照先のコントラクトに定義されている。</p><p>ここで注意しなくてはならないのが、「ContractAにはストレージ変数は定義されていないが、delegatecallで関数fを参照することによって、ContractAのストレージは、参照先のストレージ変数があるかのように値が書き込まれていく」ことである。図では、ストレージの色を対応させることで表現した。</p><p>このように設計することで、コントラクトをアップグレードしても(参照先のコントラクトがContractBからContractCに変わっても)、これまでストレージに保存していた値は影響を受けない。(常にContractAが保持している。)<br>また、ContractCで新しいストレージ変数zを追加しても、ContractAのストレージは、ストレージ変数zがあるかのように振る舞う。</p><p>ここまで見ると、「変数の追加」はできるが、「変数の削除」「変数の順番の変更」ができない理由も感覚的に理解できると思う。</p><p>これが、アップグレードの大まかな仕組みである。<br>ユーザーは常にContractAにアクセスすればよく、裏側を気にする必要はない。 開発者は、新しいContractCを作り、ContractAの参照先をContractCに変更することで、コントラクトをアップグレードすることができる。</p><p>この場合のContractAを、<strong>Proxy Contract</strong>と呼ぶ。</p><p>ZeppelinOSを使ってコントラクトをアップグレードするときに注意しなくてはならないことは、新しいコントラクトで</p><ul><li>ストレージ変数の削除</li><li>ストレージ変数の順番の変更</li></ul><p>をしないことである。</p><p>ここまでの理解で、ZeppelinOSを使った開発をしていくことはできるはずなので、まずは後半に進むといいかもしれない。</p><p>以下の章では、アップグレード可能なコントラクトに関するより詳細な理解をするために、必要な知識や参考になるサイトを紹介する。</p><h3>2. 参考：アップグレード可能なコントラクトの詳細な理解</h3><p>アップグレード可能なコントラクトのより詳細な理解には、以下の記事が役に立つ。ここでは、前章で「ZeppelinOSが使えるようになることに焦点を当て、抽象化して説明した」部分を、より具体的に説明してくれている。</p><p><a href="https://zoom-blc.com/how-to-develop-upgradable-contracts">アップグレード可能なスマートコントラクトを実現する具体的なアプローチ</a></p><p>この内容を理解するには、基本的なEthereumの知識・Solidityのプログラミングスキルに加えて、Proxyコントラクトを理解する必要がある。</p><p>そのための予備知識として、storage slot, delegatecallの説明が記事内でされているが、この他に、以下のassemblyを理解しておく必要がある。</p><p><a href="https://solidity.readthedocs.io/en/v0.4.24/assembly.html">Solidity Assembly - Solidity 0.4.24 documentation</a></p><p>記事内で説明されているproxy contractの仕組みを実際に実装したので、そのコードも載せておく。</p><p><a href="https://github.com/ryokomy/upgradable-test">ryokomy/upgradable-test</a></p><p><a href="https://goo.gl/3eskXM">後半</a>では、実際にZeppelinOSを利用した実装について話していく。</p><p><a href="https://medium.com/kyuzan-engineering-blockchain-jp/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%BE%8C%E5%8D%8A-284a0c9ff4ae">ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (後半)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c6c522b31ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/zeppelinos-%E3%82%A2%E3%83%83%E3%83%97%E3%82%B0%E3%83%AC%E3%83%BC%E3%83%89%E5%8F%AF%E8%83%BD%E3%81%AA%E3%82%B3%E3%83%B3%E3%83%88%E3%83%A9%E3%82%AF%E3%83%88%E3%82%92%E8%A8%98%E8%BF%B0%E3%81%99%E3%82%8B%E3%81%9F%E3%82%81%E3%81%AE%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF-%E5%89%8D%E5%8D%8A-8c6c522b31ba">ZeppelinOS: アップグレード可能なコントラクトを記述するためのフレームワーク (前半)</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Ethoccer : How to build a World Cup Predictions Game on Ethereum]]></title>
            <link>https://medium.com/kyuzan/inside-ethoccer-how-to-build-a-world-cup-predictions-game-on-ethereum-9d9644c429cf?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9644c429cf</guid>
            <category><![CDATA[english]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Wed, 04 Jul 2018 07:13:40 GMT</pubDate>
            <atom:updated>2019-04-03T09:16:57.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ethoccer is a FIFA World Cup 2018 match result prediction game that runs on the blockchain. Anyone can play it for free as Ethoccer is deployed on Ropsten Test Network*. In addition, users who have the highest scores at the end of the World Cup will be given ETH of Main Network*.</p><ul><li>play for free</li><li>get prizes</li></ul><p>For details, please see the following page.</p><p><a href="https://ethoccer.com/">Ethoccer : 1 ETH Prize DApps Game for FIFA World Cup Prediction</a></p><p>※ The Main Network is a network where “real” Ethereum is running, the Test Network refers to the network where “Ethereum” for “developer” is running. ETH on Test Network can be obtained for free, and developers can check the operation free of charge by first deploying smart contract on this network</p><p>This article will explain Ethoccer’s internals. This is mainly targeted towards DApps developers, especially developers who are about to develop a Dapp.<br>Also, in this article we will mainly introduce the Solidity code, and we will consider showing the front-end code as well if anyone is interested.</p><h3>System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phed53yvU7yzUnPAXofNLQ.png" /></figure><h4>Reference</h4><ul><li><a href="http://solidity.readthedocs.io/en/v0.4.20/">Solidity</a><br>The programming language to write smart contracts running on Ethereum.</li><li><a href="https://truffleframework.com/">Truffle</a><br>A framework for testing and deploying smart contract written in Solidity.</li><li><a href="https://metamask.io/">Metamask</a><br>Ethereum wallet implemented as a google chrome addon.</li><li><a href="https://trustwalletapp.com/">Trust</a><br>Ethereum wallet and browser on mobile devices.</li><li><a href="https://web3js.readthedocs.io/en/1.0/">Web3.js<br></a>API for accessing smart contract from Javascript.</li><li><a href="https://truffleframework.com/ganache">Ganache</a> (not in above figure)<br>A test network that runs in the local environment, which helps us to increase development efficiency.</li></ul><h3>All Solidity Code</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FuEAa7GjJf1&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FuEAa7GjJf1&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/3213d59fdaf3efba04914b7dcb08fd9f/href">https://medium.com/media/3213d59fdaf3efba04914b7dcb08fd9f/href</a></iframe><h3>Solidity Code Explanation</h3><h4>Contract inheritance relationship</h4><pre>contract StringHelper</pre><pre>contract MultiOwnable<br>contract Pausable is MultiOwnable</pre><pre>contract EthoccerType<br>contract EthoccerWeb3Interface is EthoccerType</pre><pre>contract Ethoccer is EthoccerWeb3Interface, Pausable, StringHelper</pre><h4>StringHelper</h4><p>This contract defines functions that are helpful for using string type. String in Solidity doesn’t have much functions for now. For example, you can not compare two string variables.</p><h4>MultiOwnable</h4><p>Ethoccer contracts have functions that only owner can execute, such as createGame and updateScores. The setting for that is described in MultiOwnable.<br>This contract is an improvement of <a href="https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol">Ownable of OpenZeppelin</a> to have multiple owner.</p><h4>Pausable</h4><p>If a bug is found in the contract, it’ll be necessary to temporarily stop the contract to deal with it. Pausable is the contract in which the setting is written.<br>We refer to <a href="https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol">Pausable of OpenZeppelin</a>, again.</p><h4>EthoccerType</h4><p>It defines structs and enums used in Ethoccer.</p><h4>EthoccerWeb3Interface</h4><p>Functions and events that can be accessed through Web3.js are summarized in this contract.<br>The main purpose is to make it easier for front-end engineers to find available functions just by looking at this contract.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FjANPAnjgdX&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FjANPAnjgdX&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/54eef0c4ab7bf2b69df604604fb29f79/href">https://medium.com/media/54eef0c4ab7bf2b69df604604fb29f79/href</a></iframe><h4>Ethoccer</h4><p>This is the main contract of Ethoccer which inherits all the contracts introduced so far.<br>Ethoccer contract has states “games” and “users” inside, and it works by changing these two states using functions defined in EthoccerWeb3Interface.</p><pre>// @dev Game<br>mapping(string =&gt; Game) internal games;<br>string[] internal gameList; // list of game IDs</pre><pre>// @dev User<br>mapping(address =&gt; User) internal users;<br>address[] internal userList; // list of user addresses</pre><p>Game and User are defined in EthoccerType like the followings.</p><pre>struct Game {<br>  string id;<br>  string country1;<br>  string country2;<br>  uint8 numberGoalCountry1;<br>  uint8 numberGoalCountry2;<br>  string time;<br>  string group;<br>  bool isOpen;<br>  bool hasResult;<br>  uint256[3] pointsPlaced;<br>  uint256 betsLength;<br>  mapping(uint256 =&gt; Bet) bets;<br>  bool initiated;<br>}</pre><pre>struct User {<br>  uint256 point;<br>  uint256 userElemsLength;<br>  mapping (uint256 =&gt; UserElem) userElems;<br>  bool initiated;<br>}</pre><pre>struct UserElem {<br>  string gameId;<br>  uint256 betId;<br>}</pre><ul><li>games<br>All game information is stored in games. An element is added by owner calling createGame.<br>While a game is open, users can bet (vote) on the game. Betted points are saved in pointsPlaced, and each bet is stored in bets mapping.<br>When the owner calls updateScores and gives the result to the game, appropriate amount of points are awarded to users based on these data.</li><li>users<br>users stores all user information. An element, User struct, is added when the user first uses Ethoccer. In this case, createUser is called internally.<br>The initial value of the points is 100. It decreases each time the user bets, and increases when user obtain the dividend points. User holds all the information of his/her bets in userElems.</li></ul><h3>Conclusion</h3><p>In this article, we introduced Ethoccer’s system.<br>Ethoccer is an experimental project, and there is still room for improvement in our contract.<br>For example, it seems unnecessary to have the information of bet stored in the User struct. Originally, we implemented it so that all bet information can be returned from the user’s address, but “information only for getter (information not necessary to refer inside smart contract)” should be implemented as Event to save gas costs. By using Web3.js, all past Events can be easily referred to as follows.</p><pre>getPlaceBetEvents() { <br>  return new Promise((resolve, reject) =&gt; {<br>    const events = this.instance.PlaceBetEvent({}, {fromBlock: 0, toBlock: &#39;latest&#39;})<br>    events.get((err, logs) =&gt; {<br>      if (err) return reject(err)<br>      return resolve(logs)<br>    })<br>  })<br>}</pre><p>While there is still room for improvement as such, we learned a lot through developing Ethoccer, and we also gained a lot of know-how in DApps development. We think that there is some things that can only be learned by actually developing and getting user feedback. For example,</p><ul><li>How to save gas cost</li><li>Implementation considering pending and rejection</li><li>Implementation considering migration and update of data</li><li>Tutorial for non DApps Users</li></ul><p>We would like to contribute to the DApps developer community with feedback obtained from users and knowledge obtained by analyzing user activities through our future services.</p><p>We hope that not only DApps users, but also the number of DApps developers will increase. We would be glad if this article helps new DApps developers to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9644c429cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/inside-ethoccer-how-to-build-a-world-cup-predictions-game-on-ethereum-9d9644c429cf">Inside Ethoccer : How to build a World Cup Predictions Game on Ethereum</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethoccer : Ethereum上で動く、ワールドカップ試合結果予測ゲームをSolidityとWeb3.jsで作る方法]]></title>
            <link>https://medium.com/kyuzan/ethoccer%E3%81%AE%E5%AE%9F%E8%A3%85-ethereum%E4%B8%8A%E3%81%A7%E5%8B%95%E3%81%8F-%E3%83%AF%E3%83%BC%E3%83%AB%E3%83%89%E3%82%AB%E3%83%83%E3%83%97%E8%A9%A6%E5%90%88%E7%B5%90%E6%9E%9C%E4%BA%88%E6%B8%AC%E3%82%B2%E3%83%BC%E3%83%A0%E3%81%AE%E4%BD%9C%E3%82%8A%E6%96%B9-3e5b814b13b0?source=rss-79baae68da79------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5b814b13b0</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[dapps]]></category>
            <dc:creator><![CDATA[こみー / Ryo Komiyama]]></dc:creator>
            <pubDate>Wed, 04 Jul 2018 07:13:40 GMT</pubDate>
            <atom:updated>2019-04-16T03:11:09.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P2JHlq8Qcxmqp3U4" /><figcaption>“green grass field in the mountain” by <a href="https://unsplash.com/@steponas?utm_source=medium&amp;utm_medium=referral">Etienne Delorieux</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>はじめに</h3><p>Ethoccerは、ブロックチェーン上で動くFIFA World Cup 2018 試合結果予測ゲームです。 EthoccerはRopsten Test Network<em>上にデプロイされているため、ユーザーは無料で遊ぶことができます。 さらに、W杯終了時に成績が上位だったユーザーは、Main Network</em>のETHを得ることができます。</p><ul><li>無料で遊べる</li><li>賞金がもらえる</li></ul><p>詳しくは、以下のページをご覧ください。</p><p><a href="https://ethoccer.com/">Ethoccer : 1 ETH Prize DApps Game for FIFA World Cup Prediction</a></p><p>※ Main Networkとは”本物の”Ethereumが動作しているネットワークで、Test Networkは”開発者用の”Ethereumが動作しているネットワークを指します。Test Network上のETHは無料で手に入れることができ、開発者はこのネットワーク上にsmart contractをデプロイすることで、まずは無料で動作を確認してみることができます。</p><p>本記事はEthoccerのシステムを解説するもので、主にDApps開発者、特にこれから何かを作ってみようとしている開発者を対象としています。<br>また、本記事で紹介するのは主にSolidityのコードで、フロント部分については、この記事の反応も見つつ次回以降に紹介していければと考えています。</p><h3>システム概要</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*phed53yvU7yzUnPAXofNLQ.png" /></figure><ul><li><a href="http://solidity.readthedocs.io/en/v0.4.20/">Solidity</a><br>Ethereum上で動くsmart contractを記述する言語。</li><li><a href="https://truffleframework.com/">Truffle</a><br>solidityで書かれたsmart contractをテスト・デプロイするためのframework。</li><li><a href="https://metamask.io/">Metamask</a><br>Ethereumのwalletで、chromeのアドオンとして実装されている。</li><li><a href="https://trustwalletapp.com/">Trust</a><br>Ethereumのwalletとブラウザがセットになったもので、スマートフォンアプリとして実装されている。</li><li><a href="https://web3js.readthedocs.io/en/1.0/">Web3.js<br></a>Javascriptからsmart contractにアクセスするためのLibrary。</li><li><a href="https://truffleframework.com/ganache">Ganache</a> (not in above figure)<br>ローカル環境で動くテストネットワークとwalletがセットになったもので、開発効率を上げてくれる。</li></ul><h3>Solidityコード全文</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FuEAa7GjJf1&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FuEAa7GjJf1&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/3213d59fdaf3efba04914b7dcb08fd9f/href">https://medium.com/media/3213d59fdaf3efba04914b7dcb08fd9f/href</a></iframe><h3>コード解説</h3><h4>Contractの継承関係</h4><pre>contract StringHelper</pre><pre>contract MultiOwnable<br>contract Pausable is MultiOwnable</pre><pre>contract EthoccerType<br>contract EthoccerWeb3Interface is EthoccerType</pre><pre>contract Ethoccer is EthoccerWeb3Interface, Pausable, StringHelper</pre><h4>StringHelper</h4><p>Solidityはstringの比較ができないため、このコントラクトで、stringを使用する際に役立つ関数を定義しています。</p><h4>MultiOwnable</h4><p>Ethoccerコントラクトには、createGameやupdateScoresなど、ownerだけが実行できる関数があります。MultiOwnableには、そのための設定が記述されています。<br>このコントラクトは、<a href="https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol">OpenZeppelinのOwnable</a>を、複数のownerを持てるように改良したものです。</p><h4>Pausable</h4><p>万一コントラクトにバグが発覚した場合、その対処のため、一時的にコントラクトを停止させる必要があると考えました。Pausableにはそのための設定が記述されています。<br>こちらも、<a href="https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol">OpenZeppelinのPausable</a>を参考にしています。</p><h4>EthoccerType</h4><p>Ethoccerで使用するstructやenumを定義しています。</p><h4>EthoccerWeb3Interface</h4><p>このコントラクトには、Web3.jsを通じてアクセスできる関数・イベントがまとめてあります。<br>主な目的は、ブロックチェーンエンジニア以外がSolidityの実装を見ないでよくするためで、フロントエンジニアはここを見るだけで使用可能な関数を見つけることができます。</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fethfiddle.com%2FjANPAnjgdX&amp;src=https%3A%2F%2Fethfiddle.com%2Fservices%2Fiframesnippet%2FjANPAnjgdX&amp;type=text%2Fhtml&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;schema=ethfiddle" width="300" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/54eef0c4ab7bf2b69df604604fb29f79/href">https://medium.com/media/54eef0c4ab7bf2b69df604604fb29f79/href</a></iframe><h4>Ethoccer</h4><p>ここまでに紹介した全てのコントラクトを継承している、Ethoccerのメインとなるコントラクトです。<br>Ethoccerコントラクトは内部にgamesとusersを持っていて、この２つのstateの値をEthoccerWeb3Interfaceで定義した関数で変化させることで動作しています。</p><pre>// @dev Game<br>mapping(string =&gt; Game) internal games;<br>string[] internal gameList; // list of game IDs</pre><pre>// @dev User<br>mapping(address =&gt; User) internal users;<br>address[] internal userList; // list of user addresses</pre><p>GameとUserはEthoccerTypeで以下のように定義されています。</p><pre>struct Game {<br>  string id;<br>  string country1;<br>  string country2;<br>  uint8 numberGoalCountry1;<br>  uint8 numberGoalCountry2;<br>  string time;<br>  string group;<br>  bool isOpen;<br>  bool hasResult;<br>  uint256[3] pointsPlaced;<br>  uint256 betsLength;<br>  mapping(uint256 =&gt; Bet) bets;<br>  bool initiated;<br>}</pre><pre>struct User {<br>  uint256 point;<br>  uint256 userElemsLength;<br>  mapping (uint256 =&gt; UserElem) userElems;<br>  bool initiated;<br>}</pre><pre>struct UserElem {<br>  string gameId;<br>  uint256 betId;<br>}</pre><ul><li>games<br>gamesには全ての試合情報が格納されています。要素であるGame structは、ownerがcreateGameを呼ぶことで追加されます。<br>gameがopenの状態では、ユーザーはgameに対してbet (vote) することができます。betされたポイントはpointsPlaced内に保存され、１つ１つのbetはbetsというmapping内に保存されます。<br>ownerがupdateScoresを呼びgameに試合結果を与えると、これらのデータを元に、ユーザーに配当ポイントが配布されます。</li><li>users<br>usersには全てのユーザー情報が格納されています。要素であるUser structは、ユーザーが初めてEthoccerを使用したときに追加されます。このとき内部ではcreateUserが呼ばれています。<br>Userのpointの初期値は100で、betするたびにマイナスされ、配当ポイントを得たときにプラスされます。また、Userは自分がbetした全ての情報をuserElemsという形で保持しています。</li></ul><h3>まとめ</h3><p>本記事では、Ethoccerのシステムについて紹介しました。<br>Ethoccerは実験的なプロジェクトであり、コードにはまだまだ改善の余地があります。<br>例えば、User structにbetの情報は持たせる必要はなさそうです。これは元々、ユーザーのaddressから全てのbet情報を返せるように実装したのですが、このように「getterのためだけの情報 (smart contract内部で参照する必要がない情報)」は、Eventとして実装したほうがgasの節約になります。過去の全てのEventは、web3.jsを用いると以下のように簡単に参照することができます。</p><pre>getPlaceBetEvents() { <br>  return new Promise((resolve, reject) =&gt; {<br>  const events = this.instance.PlaceBetEvent({}, {fromBlock: 0, toBlock: &#39;latest&#39;})<br>  events.get((err, logs) =&gt; {<br>    if (err) return reject(err)<br>      return resolve(logs)<br>    })<br>  })<br>}</pre><p>このように、まだまだ改善の余地がある一方で、我々はEthoccerの開発によって、DApps開発における多くのノウハウを獲得できたと実感しています。例えば以下のようなことは、実際に開発をしてユーザーのフィードバックを得ることで初めて感覚が掴めることだと思います。</p><ul><li>gasの減らし方</li><li>pendingやRejectを考慮した実装</li><li>データ移行やUpdateを考慮した実装</li><li>非DApssユーザーに向けたチュートリアル</li></ul><p>今回、ユーザーからいただいたフィードバックや、ユーザーの動向を解析することで得られた知見は、これからの実証実験やサービスでDApps開発者コミュニティに還元していけたらと思います。</p><p>我々はDappsユーザーが増えることと同時に、DApps開発者が増えることも望んでいます。 この記事が少しでもみなさんの助けになれば幸いです。</p><p><em>Originally published at </em><a href="https://medium.com/kyuzan-engineering/inside-ethoccer-how-to-build-a-world-cup-predictions-game-on-ethereum-9d9644c429cf"><em>medium.com</em></a><em> on July 4, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5b814b13b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kyuzan/ethoccer%E3%81%AE%E5%AE%9F%E8%A3%85-ethereum%E4%B8%8A%E3%81%A7%E5%8B%95%E3%81%8F-%E3%83%AF%E3%83%BC%E3%83%AB%E3%83%89%E3%82%AB%E3%83%83%E3%83%97%E8%A9%A6%E5%90%88%E7%B5%90%E6%9E%9C%E4%BA%88%E6%B8%AC%E3%82%B2%E3%83%BC%E3%83%A0%E3%81%AE%E4%BD%9C%E3%82%8A%E6%96%B9-3e5b814b13b0">Ethoccer : Ethereum上で動く、ワールドカップ試合結果予測ゲームをSolidityとWeb3.jsで作る方法</a> was originally published in <a href="https://medium.com/kyuzan">KYUZAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>