使用React Native建立以太坊錢包,實現轉帳等功能

以前想用React Native開發一版以太坊錢包app,但在生成帳戶那塊碰見了問題,沒有crypto等nodejs包,react native是運行在JavaScriptCore環境裏面,是沒有buffer, crypto 跟 stream這些庫的,因此爲了解決,就跟同事開發了基於golang的web3go,而後使用gomoble工具編譯成ios須要的framework以及android須要的jar aar,完美解決問題javascript

  • 演示

dapp-demo-1.png

dapp-demo-2.png

  • 安裝web3go
git clone https://github.com/bcl-chain/web3.go.git
複製代碼
  • 使用gomobile編譯成framework,jar,aar
// generate framework
gomobile bind -target=ios ./github.com/bcl-chain/web3.go/mobile

// generate arr jar
gomobile bind -target=android ./github.com/bcl-chain/web3.go/mobile
複製代碼
  • 把生成的包link到原生app裏面

link-web3go.png
andoir-getbalence.png

  • 下載ETH本地測試工具ganache-cli

gan-cli.png

  • 安裝依賴
yarn
react-native run-android
react-native run-ios
複製代碼
  • getBalance代碼分析
// IOS
RCT_EXPORT_METHOD(getBalance:
                  (NSString*) address:
                  (RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject){
  // ip地址
  Web3goEthereumClient* client = Web3goNewEthereumClient(nodeIP, nil);
  Web3goContext* ctx = Web3goNewContext();
  // 帳戶地址
  Web3goAddress* address1 = Web3goNewAddressFromHex(address, nil);
  @try {
    Web3goBigInt* a = [client getBalanceAt:ctx account:address1 number:-1 error:nil];
    NSString* ammount = [a getString:10];
    NSLog(@"%@", ammount);
    resolve(ammount);
  } @catch (NSError *exception) {
    NSLog(@"NSError: %@", exception);
    reject(@"NSError: %@", @"There were no events", exception);
  } @finally {
    NSLog(@"finally");
  }
  
}

// android
@ReactMethod
public void getBalance(String address, Promise promise) {
    try {
      web3go.EthereumClient client = Web3go.newEthereumClient(nodeIP);
      web3go.Context ctx = Web3go.newContext();
      web3go.Address address1 = Web3go.newAddressFromHex(address);
      web3go.BigInt a = client.getBalanceAt(ctx, address1, -1);
      String ammout = a.getString(10);
      promise.resolve(ammout);
    } catch (Exception e) {
      promise.reject(e.getMessage());
    }
}

// react-native
async getBalance() {
    try {
      var ammount = await NativeModules.Web3go.getBalance(this.state.defGaAddress);
      this.setState({
        gaAmmount: ammount
      })
    } catch (e) {
      console.error(e);
    }
}
 
複製代碼

若是有用,給個start

web3gojava

React-Native-Dappnode

相關文章
相關標籤/搜索