テクノロジー

Vol.173 FlutLab記録 - Metamask連携はできるのか?

gryption's icon'
  • gryption
  • 2022/08/28 10:06

今回は、FlutLab開発日記的なものを書いていきたいと思います。FlatLabはこの前に記事化して紹介しましたが、いわゆる「mBaaS」的なものととらえて大丈夫かと負います。Zennというメディアがエンジニアとして利用するにあたり先進的だと考えているため、一部その情報をここで共有します。

Content image

Media間の情報共有は重要だと考えており、前述した通りここのALISで発言したものはほかのブログプラットフォームでも一部配信しています。

一応は下記の記事などを参照しましたが、現在でもFlatLabでメタマスクを実装するに至っていません。

上記のflutter_web3_sampleが開発しているものですが、これらのサンプルコードはgithub上からとってきました。

こちらkboyという方が編集してくれたもので、何もわからなかった身としてはありがたくもありました。私としてはあまりFlutterには詳しい方ではないので、このようなサンプルはありがたいです。しかし、動きませんでした。

Content image

チャットもしてみましたがわかりませんでした。

main.dart

// ignore_for_file: nullable_type_in_catch_clause

import 'package:flutter/material.dart';
import 'package:flutter_web3/flutter_web3.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);


  @override
  State<MyHomePage> createState() => _MyHomePageState();
}


const kboyAddress = '0x68035DC06E6282AD280c136139D65d00d7B99ec0';


class _MyHomePageState extends State<MyHomePage> {
  String account = '';
  double balanceString = 0;


  get ethereum => null;


  get provider => null;


  void _fetchBalance() async {
    print(ethereum);
    // `Ethereum.isSupported` is the same as `ethereum != null`
    if (ethereum != null) {
      try {
        // Prompt user to connect to the provider, i.e. confirm the connection modal
        final accounts = await ethereum!.requestAccount();
        final firstAccount = accounts.first;


        final BigInt balance = await provider!.getBalance(kboyAddress);
        final ethBalance =
            balance.toDouble() * 1 / 1000000000000000000; // WEI to ETH


        setState(() {
          account = firstAccount;
          balanceString = ethBalance;
        });
      } on EthereumUserRejected {
        print('User rejected the modal');
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutt'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Address: $account',
            ),
            Text(
              '$balanceString ETH',
              style: Theme.of(context).textTheme.headline4,
            ),
            TextButton(
                onPressed: () async {
                  // Send 1000000000 wei to `0xcorge`
                  final tx = await provider!.getSigner().sendTransaction(
                        TransactionRequest(
                          to: kboyAddress,
                          value: BigInt.from(1000000000000),
                        ),
                      );
                  final receipt = await tx.wait();
                  print(receipt);
                },
                child: const Text('send')),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fetchBalance,
        child: const Icon(Icons.account_balance_wallet),
      ),
    );
  }

  TransactionRequest({required String to, required BigInt value}) {}
}

上記がmain.dartで、

Content image

index.htmlが、

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.


    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.


    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base


    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="$FLUTTER_BASE_HREF">


  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">


  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="flutter_web3_sample">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">


  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>


  <title>flutter_web3_sample</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    var serviceWorkerVersion = null;
    var scriptLoaded = false;
    function loadMainDartJs() {
      if (scriptLoaded) {
        return;
      }
      scriptLoaded = true;
      var scriptTag = document.createElement('script');
      scriptTag.src = 'main.dart.js';
      scriptTag.type = 'application/javascript';
      document.body.append(scriptTag);
    }


    if ('serviceWorker' in navigator) {
      // Service workers are supported. Use them.
      window.addEventListener('load', function () {
        // Wait for registration to finish before dropping the <script> tag.
        // Otherwise, the browser will load the script multiple times,
        // potentially different versions.
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => {
            function waitForActivation(serviceWorker) {
              serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                }
              });
            }
            if (!reg.active && (reg.installing || reg.waiting)) {
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing || reg.waiting);
            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
            } else {
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            }
          });


        // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plaint <script> tag.
        setTimeout(() => {
          if (!scriptLoaded) {
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          }
        }, 4000);
      });
    } else {
      // Service workers not supported. Just drop the <script> tag.
      loadMainDartJs();
    }
  </script>


  <!--Ethers-->
  <script src="https://cdn.ethers.io/lib/ethers-5.4.umd.min.js" type="application/javascript"></script>
  <!--Wallet Connect-->
  <script src="https://cdn.jsdelivr.net/npm/@walletconnect/web3-provider@1.6.5/dist/umd/index.min.js" type="application/javascript"></script>
</body>
</html>

となります。ALISにはコード化する場合Flutterという選択がなかったので、追加してほしい所存です。

で、今のところMetamask連携はできていないので、なぜGithubでできたのかをいろいろ試したいと思っています。もしかしたら、AndroidStudioでやるかもしれません。
 

Supporter profile icon
Article tip 1人がサポートしています
獲得ALIS: Article like 3.89 ALIS Article tip 4.10 ALIS
gryption's icon'
  • gryption
  • @biyori
金融系・テック関連のニッチな最新情報をわかりやすくアウトプット&解説

投稿者の人気記事
コメントする
コメントする
こちらもおすすめ!
Eye catch
クリプト

スーパーコンピュータ「京」でマイニングしたら

Like token Tip token
1.06k ALIS
Eye catch
他カテゴリ

ALISのシステム概観

Like token Tip token
5.00 ALIS
Eye catch
クリプト

17万円のPCでTwitterやってるのはもったいないのでETHマイニングを始めた話

Like token Tip token
46.60 ALIS
Eye catch
テクノロジー

彼女でも分かるように解説:ディープフェイク

Like token Tip token
32.10 ALIS
Eye catch
テクノロジー

なぜ、素人エンジニアの私が60日間でブロックチェーンゲームを制作できたのか、について語ってみた

Like token Tip token
270.93 ALIS
Eye catch
クリプト

Bitcoinの価値の源泉は、PoWによる電気代ではなくて"競争原理"だった。

Like token Tip token
159.32 ALIS
Eye catch
クリプト

約2年間ブロックチェ-ンゲームをして

Like token Tip token
61.20 ALIS
Eye catch
クリプト

Bitcoin史 〜0.00076ドルから6万ドルへの歩み〜

Like token Tip token
947.13 ALIS
Eye catch
クリプト

ブロックチェーンの51%攻撃ってなに

Like token Tip token
0.00 ALIS
Eye catch
クリプト

「ハッシュ」とは何なのか、必ず理解させます

Like token Tip token
0.10 ALIS
Eye catch
クリプト

NFT解体新書・デジタルデータをNFTで販売するときのすべて【実証実験・共有レポート】

Like token Tip token
120.79 ALIS
Eye catch
テクノロジー

オープンソースプロジェクトに参加して自己肯定感を高める

Like token Tip token
85.05 ALIS