用flutter创建cosmos钱包

import 'package:bip39/bip39.dart' as bip39;

import 'package:shared_preferences/shared_preferences.dart';

import 'package:sacco/sacco.dart';

1.调用bip39库生成助记词,先暂时用shared_preferences存储着

List mnemonic;

连接节点

final networkInfo = NetworkInfo(name: "", bech32Hrp: "cosmos", lcdUrl: "http://172.168.0.78:1317");

void getMnemonic() async{

String randomMnemonic = await bip39.generateMnemonic();

mnemonic = randomMnemonic.split(" ");//将助记词转换成List类型

prefs.setStringList("mnemonic", mnemonic);

}

2.调用sacco库用之前存储的助记词创建钱包对象

wallet() async{

SharedPreferences prefs = await SharedPreferences.getInstance();

var mnemonicString = prefs.getStringList("mnemonic");

Wallet wallet = Wallet.derive(mnemonicString, networkInfo);

return wallet;

  }

获取钱包地址:

Wallet wa = await wallet();

print("地址"+wa.bech32Address);

3.发送一个交易

final message = StdMsg(

  type: "cosmos-sdk/MsgSend",

value: {

    "from_address": "cosmos1huydeevpz37sd9snkgul6070mstupukw00xkw9",

    "to_address": "cosmos18rwfv9yj7u4zmahv4y299ft086j704cxal9mtf",

    "amount": [

      {"denom": "zcoin", "amount": "1"}

    ]

  },

);

//签名交易

final stdTx = TxBuilder.buildStdTx(stdMsgs: [message]);

//发送交易

final signedStdTx = await TxSigner.signStdTx(

                            wallet: wa, stdTx: stdTx);

                        final result = await TxSender.broadcastStdTx(

                          wallet: wallet,

                          stdTx: signedStdTx,

                      );

                        if (result.success) {

                          print("Tx send successfully. Hash: ${result.hash}");

                      } else {

                          print("Tx send error: ${result.error.errorMessage}");                   

                      }

你可能感兴趣的:(用flutter创建cosmos钱包)