React Nativeでトランザクションを送信する方法
🏏

React Nativeでトランザクションを送信する方法

タグ
React NativeSymbol
公開日
March 21, 2023

cryptoをインストール

npm i crypto-browserify readable-stream

metro.config.jsを編集

/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */

module.exports = {
// ここのresolverを追加する
  resolver: {
    extraNodeModules: {
      crypto: require.resolve('crypto-browserify'),
      stream: require.resolve('readable-stream'),
    },
  },
// ここはデフォであります。
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
};

rm-nodifyインストール

npm install rn-nodeify -g

インストール

rn-nodeify --install 'buffer,events,http,https,os,process,stream,tty,url,util,vm,zlib' --hack

index.jsの先頭にshim.jsを追加

/**
 * @format
 */
// ここに追加
import './shim.js';
// 以下はデフォルト
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

symbol-sdkとrxjsを追加

npm install symbol-sdk rxjs

App.ts

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React from 'react';
import {
  Alert,
  Button,
  SafeAreaView,
  ScrollView,
  StatusBar,
  useColorScheme,
} from 'react-native';

import {Colors, Header} from 'react-native/Libraries/NewAppScreen';

import {
  RepositoryFactoryHttp,
  Account,
  Address,
  TransferTransaction,
  Deadline,
  PlainMessage,
  UInt64,
} from 'symbol-sdk';

// ここの秘密鍵とアドレスは各自調整が必須
const AlicePrivateKey =
  'B82E003F3DAF29C1E55C39553327B8E178D820396C8A6144AA71329EF391D0EB';
const bobAddress = 'TBH3OVV3AFONJZSYOMUILGERPNYY77AISF54C4Q';

const example = async (): Promise<void> => {
  // Network information
// ネットワークも動いていないものを使うとネットワークエラーになるので使えるやつを使いましょう。
  const nodeUrl = 'https://vmi834332.contaboserver.net:3001';
  const repositoryFactory = new RepositoryFactoryHttp(nodeUrl);
  const epochAdjustment = await repositoryFactory
    .getEpochAdjustment()
    .toPromise();
  const networkType = await repositoryFactory.getNetworkType().toPromise();
  const networkGenerationHash = await repositoryFactory
    .getGenerationHash()
    .toPromise();
  const recipientAddress = Address.createFromRawAddress(bobAddress);
  const transferTransaction = TransferTransaction.create(
    Deadline.create(epochAdjustment!), // 有効期限
    recipientAddress, // 受取人のアドレス
    [], // 送信するモザイクとその数量
    PlainMessage.create('This is a test message'), // メッセージ
    networkType!, // ネットワークタイプ
    UInt64.fromUint(2000000), // 手数料
  );

  const account = Account.createFromPrivateKey(AlicePrivateKey, networkType!);
  const signedTransaction = account.sign(
    transferTransaction,
    networkGenerationHash!,
  );
  console.log(signedTransaction.hash, 'hash');
  console.log('--------------------------------');
  console.log(signedTransaction.payload, 'payload');
  const transactionRepository = repositoryFactory.createTransactionRepository();
  const response = await transactionRepository
    .announce(signedTransaction)
    .toPromise();
  console.log(response);
};

function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
        <Button
          title="Press me"
          onPress={() => Alert.alert('Simple Button pressed')}
        />
        <Button
          title="押してみそ"
          onPress={() =>
            example()
              .then()
              .catch(err => console.log(err))
          }
        />
      </ScrollView>
    </SafeAreaView>
  );
}

export default App;

image

この押してみそをクリックするとトランザクションが送信されます。

image