Flutter Algorand区块链交互插件algorand_dart的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter Algorand区块链交互插件algorand_dart的使用

Algorand是一个公共区块链和协议,旨在为所有参与者提供去中心化、规模和安全性。其PURE PROOF OF STAKE™共识机制确保了完全参与、保护和速度在一个真正去中心化的网络中。借助algorand_dart插件,您可以轻松地在Flutter应用中与Algorand区块链进行交互。

安装

首先,您需要在pubspec.yaml文件中添加algorand_dart依赖:

dependencies:
  algorand_dart: ^latest-version

注意:algorand-dart要求Dart >=2.12.0和null safety,请查看pub.dev获取最新版本。

初始化客户端

创建一个AlgodClientIndexerClient并传递给Algorand构造函数。我们为本地托管节点和第三方服务(如PureStake)提供了额外的支持。

import 'package:algorand_dart/algorand_dart.dart';

final algodClient = AlgodClient(
    apiUrl: PureStake.TESTNET_ALGOD_API_URL,
    apiKey: 'your_api_key',
    tokenKey: PureStake.API_TOKEN_HEADER,
);

final indexerClient = IndexerClient(
    apiUrl: PureStake.TESTNET_INDEXER_API_URL,
    apiKey: 'your_api_key',
    tokenKey: PureStake.API_TOKEN_HEADER,
);

final algorand = Algorand(
    algodClient: algodClient,
    indexerClient: indexerClient,
);

发送支付

一旦安装完成,您可以简单地连接您的应用程序到区块链并开始发送支付:

final account = await algorand.createAccount();
final newAccount = await algorand.createAccount();

await algorand.sendPayment(
    account: account,
    recipient: newAccount.address,
    amount: Algo.toMicroAlgos(5),
    note: 'Hi from Flutter!',
);

如果您希望等待交易确认,可以使用waitForConfirmation参数:

final transactionId = await algorand.sendPayment(
    account: account,
    recipient: newAccount.address,
    amount: Algo.toMicroAlgos(5),
    note: 'Hi from Flutter!',
    waitForConfirmation: true,
    timeout: 3,
);

创建资产

创建一个新的资产同样简单:

final transactionId = await algorand.assetManager.createAsset(
    account: account,
    assetName: 'FlutterCoin',
    unitName: 'Flutter',
    totalAssets: 10000,
    decimals: 2,
);

或者使用TransactionBuilder来创建更具体的原始交易:

final params = await algorand.getSuggestedTransactionParams();

final transaction = await (AssetConfigTransactionBuilder()
      ..assetName = 'FlutterCoin'
      ..unitName = 'Flutter'
      ..totalAssetsToCreate = 10000
      ..decimals = 2
      ..defaultFrozen = false
      ..managerAddress = account.address
      ..reserveAddress = account.address
      ..freezeAddress = account.address
      ..clawbackAddress = account.address
      ..sender = account.address
      ..suggestedParams = params)
    .build();

final signedTransaction = await transaction.sign(account);

final txId = await algorand.sendTransaction(signedTransaction);

原子转移

原子转移意味着转移中的交易要么全部成功,要么全部失败。以下是创建原子转移的示例:

final params = await algorand.getSuggestedTransactionParams();

final transactionA = await (PaymentTransactionBuilder()
    ..sender = accountA.address
    ..note = 'Atomic transfer from account A to account B'
    ..amount = Algo.toMicroAlgos(1.2)
    ..receiver = accountB.address
    ..suggestedParams = params)
  .build();

final transactionB = await (PaymentTransactionBuilder()
    ..sender = accountB.address
    ..note = 'Atomic transfer from account B to account A'
    ..amount = Algo.toMicroAlgos(2)
    ..receiver = accountA.address
    ..suggestedParams = params)
  .build();

AtomicTransfer.group([transactionA, transactionB]);

final signedTxA = await transactionA.sign(accountA);
final signedTxB = await transactionB.sign(accountB);

final txId = await algorand.sendTransactions([signedTxA, signedTxB]);

账户管理

创建新账户

final account = await algorand.createAccount();

或者使用Account类:

final account = await Account.random();

提取公钥地址、签名密钥和助记词/种子短语:

final publicAddress = account.publicAddress;
final words = await account.seedPhrase;

加载现有账户

final account = await algorand.loadAccountFromSeed(seed);

恢复账户

final restoredAccount = await algorand.restoreAccount(['25-word-mnemonic']);

状态智能合约

合约账户

final arguments = <Uint8List>[];
arguments.add(Uint8List.fromList([123]));

final result =
    await algorand.applicationManager.compileTEAL(sampleArgsTeal);
final logicSig = LogicSignature.fromProgram(
  program: result.program,
  arguments: arguments,
);

final receiver =
    'KTFZ5SQU3AQ6UFYI2QOWF5X5XJTAFRHACWHXAZV6CPLNKS2KSGQWPT4ACE';
final params = await algorand.getSuggestedTransactionParams();
final transaction = await (PaymentTransactionBuilder()
      ..sender = logicSig.toAddress()
      ..note = 'Logic Signature'
      ..amount = 100000
      ..receiver = Address.fromAlgorandAddress(address: receiver)
      ..suggestedParams = params)
    .build();

final signedTx = await logicSig.signTransaction(transaction: transaction);

final txId = await algorand.sendTransaction(
  signedTx,
  waitForConfirmation: true,
);

账户委托

final arguments = <Uint8List>[];
arguments.add(Uint8List.fromList([123]));

final result =
    await algorand.applicationManager.compileTEAL(sampleArgsTeal);
final logicSig = await LogicSignature.fromProgram(
  program: result.program,
  arguments: arguments,
).sign(account: account);

final receiver =
    'KTFZ5SQU3AQ6UFYI2QOWF5X5XJTAFRHACWHXAZV6CPLNKS2KSGQWPT4ACE';
final params = await algorand.getSuggestedTransactionParams();
final transaction = await (PaymentTransactionBuilder()
      ..sender = account.address
      ..note = 'Account delegation'
      ..amount = 100000
      ..receiver = Address.fromAlgorandAddress(address: receiver)
      ..suggestedParams = params)
    .build();

final signedTx = await logicSig.signTransaction(transaction: transaction);

final txId = await algorand.sendTransaction(
  signedTx,
  waitForConfirmation: true,
);

多重签名

创建多重签名地址

final one = Address.fromAlgorandAddress(
  address: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU',
);
final two = Address.fromAlgorandAddress(
  address: 'HTNOX33OCQI2JCOLZ2IRM3BC2WZ6JUILSLEORBPFI6W7GU5Q4ZW6LINHLA',
);

final three = Address.fromAlgorandAddress(
  address: 'E6JSNTY4PVCY3IRZ6XEDHEO6VIHCQ5KGXCIQKFQCMB2N6HXRY4IB43VSHI',
);

final publicKeys = [one, two, three]
    .map((address) => Ed25519PublicKey(bytes: address.publicKey))
    .toList();

final multiSigAddr =
    MultiSigAddress(version: 1, threshold: 2, publicKeys: publicKeys);

使用多重签名账户签署交易

final account1 = await Account.fromSeed(seed1);
final account2 = await Account.fromSeed(seed2);
final account3 = await Account.fromSeed(seed3);

final publicKeys = [account1, account2, account3]
    .map((account) => Ed25519PublicKey(bytes: account.address.publicKey))
    .toList();

final msa =
    MultiSigAddress(version: 1, threshold: 2, publicKeys: publicKeys);

final params = await algorand.getSuggestedTransactionParams();
final transaction = await (PaymentTransactionBuilder()
      ..sender = msa.toAddress()
      ..note = 'MSA '
      ..amount = 1000000
      ..receiver = account3.address
      ..suggestedParams = params)
    .build();

final signedTx = await msa.sign(
  account: account1,
  transaction: transaction,
);

final completeTx = await msa.append(
  account: account2,
  transaction: signedTx,
);

final txId = await algorand.sendTransaction(
  completeTx,
  waitForConfirmation: true,
);

更多关于Flutter Algorand区块链交互插件algorand_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Algorand区块链交互插件algorand_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用algorand_dart插件与Algorand区块链进行交互的示例代码。这个示例将展示如何连接到Algorand节点,生成钱包地址,以及发送交易。

首先,确保你已经在pubspec.yaml文件中添加了algorand_dart依赖:

dependencies:
  flutter:
    sdk: flutter
  algorand_dart: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

接下来是示例代码:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  AlgodClient? _algodClient;
  KmdClient? _kmdClient;
  String? _walletAddress;
  String? _transactionId;

  @override
  void initState() {
    super.initState();
    // 初始化AlgodClient和KmdClient
    _initializeClients();
  }

  void _initializeClients() async {
    // 替换为你的Algod和KMD服务器地址和端口
    String algodAddress = 'http://localhost:4001';
    String kmdAddress = 'http://localhost:4002';
    String token = 'your_api_token';  // 如果需要API令牌的话

    _algodClient = AlgodClient(algodAddress, token: token);
    _kmdClient = KmdClient(kmdAddress, token: token);

    // 生成钱包地址(示例中仅生成,实际应用中应妥善管理钱包)
    final walletHandle = await _kmdClient!.generateKey();
    final walletInfo = await _kmdClient!.walletInfo(walletHandle);
    setState(() {
      _walletAddress = walletInfo.addresses[0];
    });
  }

  void _sendTransaction() async {
    if (_algodClient == null || _walletAddress == null) return;

    // 获取建议的交易参数
    final params = await _algodClient!.getTransactionParams();

    // 构建交易(这里以转账为例)
    final senderAddress = _walletAddress!;
    final receiverAddress = 'receiver_address';  // 替换为接收方地址
    final amount = 1000;  // 转账金额(微阿尔戈)
    final note = Uint8List.fromList('Hello, Algorand!'.codeUnits);

    final tx = Transaction(
      sender: senderAddress,
      fee: params.fee,
      firstRound: params.lastRound + 1,
      lastRound: params.lastRound + 1000,
      genesisHash: params.genesisHash,
      group: null,
      lease: null,
      note: note,
      type: TransactionType.pay,
      recv: receiverAddress,
      amt: amount,
    );

    // 签署交易
    final signedTxn = await _kmdClient!.signTransaction(
      _walletAddress!,
      tx.toByteData(),
    );

    // 发送交易
    final sendResponse = await _algodClient!.sendRawTransaction(signedTxn);
    setState(() {
      _transactionId = sendResponse.txId;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Algorand Flutter Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Wallet Address: $_walletAddress'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _sendTransaction,
                child: Text('Send Transaction'),
              ),
              SizedBox(height: 20),
              Text('Transaction ID: $_transactionId'),
            ],
          ),
        ),
      ),
    );
  }
}

注意事项:

  1. API令牌:如果你的Algod和KMD服务器需要API令牌,请确保在初始化客户端时提供。
  2. 安全性:在实际应用中,请确保私钥和钱包信息的安全存储和管理。
  3. 网络配置:根据你的网络配置(测试网、主网等)调整服务器地址和端口。
  4. 错误处理:示例代码省略了错误处理逻辑,实际开发中应添加适当的错误处理。

这个示例展示了如何使用algorand_dart插件在Flutter应用中生成钱包地址和发送交易。根据你的具体需求,你可能需要进一步扩展和调整代码。

回到顶部