Skip to content
Oleg edited this page Nov 14, 2022 · 2 revisions

Welcome to the binance_chain_dart wiki!

Binance Chain Dart SDK Usage Examples

Create Wallet

  • From mnemonic phrase (random or manually)
  import 'package:bip39/bip39.dart' as bip39;
  import 'package:binance_chain/binance_chain.dart';
  ....
  var mnemonic = bip39.generateMnemonic();
  var wallet = Wallet.fromMnemonicPhrase(mnemonic, bip39.Language.english, env);
  print(wallet.address);
  print(wallet.privateKey);
  print(wallet.publicKey);
  • From private key:
  import 'package:binance_chain/binance_chain.dart';
  ....
  var privateKey = '<private key in HEX>';
  var wallet = Wallet(privateKey, env);
  print(wallet.address);
  print(wallet.privateKey);
  print(wallet.publicKey);
  • Coming soon: creating a wallet from WIF and .keystore(keystore JSON)

HTTP Client (async)

Basics

All HTPP Client methods returns instance of APIResponse class. This class is a convenient query wrapper with useful properties and data models for responses. For example let's get account info:

  var env = BinanceEnvironment.getTestnetEnv();
  var http = HttpApiClient(env: env);
  var response = await http.getAccount('tbnb1.........');

getAccount method returns Future<APIResponse<Account>> object, where Account - type of data model with corresponding properties. If we're "await" this method, in response will be APIResponse<Account> object; So, there is getters of APIResponse:

  • response.statusCode - returns integer HTTP status code (e.g. 200=Success);
  • response.ok - returns true if request was successful or false if no. Based on HTTP status code: 200 -> ok=true, other -> ok=false
  • response.load - returns instance of corresponding data model. In this example type of load will be Account and will have corresponding properties.
  • response.error - returns instance of Error class if request was wrong. In case of an request error response.load will return empty data model(all properties will be null). Error class have two properties: code - HTTP satus code and message - message about error (from Binance API).

To access data from response load use getters of corresponding data model:

  response.load.address; // address of account 
  response.load.balances; // List<Balance>, balances of account 
  response.load.sequence; // account sequence

All data models description available in code docs with links to Binance Api Docs.

Getting data from Binance Chain API

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

  var testnetEnv = BinanceEnvironment.getTestnetEnv();
  var httpClient = HttpApiClient(env: testnetEnv);
  
  // create wallet from mnemonic phrase
  var wallet = Wallet.fromMnemonicPhrase('mnemonic phrase 12-24 words', bip39.Language.english, testnetEnv)
  // or from private key
  var wallet = Wallet('private key in hexadecimal', testnetEnv)
  
  // get account info
  var account = await httpClient.getAccount('tbnb1v8603f3ene9zd2y44s6czhhjw7sd8gs9v4est4');
  
  // get open orders of account
  var openOrders = await httpClient.getOpenOrders('tbnb1v8603f3ene9zd2y44s6czhhjw7sd8gs9v4est4');
  
  // get order from order id
  var order = await httpClient.getOrder('9D0537108883C68B8F43811B780327CE97D8E01D-2');

  // get order from order id (for mini tokens BEP8)
  var order_mini = await http.getOrderMini('9D0537108883C68B8F43811B780327CE97D8E01D-2');

  // get transactions
  var transactions = await httpClient.getTransacions('tbnb1v8603f3ene9zd2y44s6czhhjw7sd8gs9v4est4');
  
  // get node info
  var nodeInfo = await http.getNodeInfo();
  
  // get order book (market depth)
  var depth = await http.getOrderBook('BNB_BUSD-BD1');

  // get candlestics (k-lines) for BEP2 token
  var candlestics = await http.getCandlestickBars(symbol: 'BNB_BUSD-BD1');

  // get candlestics (k-lines) for mini BEP8 token
  var candlestics_mini = await http.getCandlestickBarsMini(symbol: 'BHC-3E8M_BUSD-BD1');
  
  // get tickers 24h for all BEP2 tokens
  var tickers_mini = await http.getTickerStats24hr();

  // get tickers 24h for some BEP2 token
  var tickerBCH = await http.getTickerStats24hr(symbol:'BNB_BUSD-BD1');

  // get tickers 24h for all mini BEP8 tokens
  var tickers_mini = await http.getMiniTickerStats24hr();

  // get tickers 24h for some mini BEP8 token
  var tickerBCH = await http.getMiniTickerStats24hr(symbol:'BHC-3E8M_BUSD-BD1');

Creating and broadcasting messages

To creating and sending messages you need:

var env = BinanceEnvironment.getTestnetEnv();
var wallet = Wallet(privateKey, env); // or other way: mnemonic / WIF / keystore
var httpClient = HttpApiClient(env: env);

All prices and amounts in messages require Decimal object represenstation of real numbers to keep accurate.

There are two ways to broadcast messages: synchronous and asyncronous.

In the case of the synchronous broadcast, you will receive a response only after the transaction is confirmed by the Binance Chain. This is convenient if you immediately need to make sure that the transaction has been confirmed.

In the case of the asynchronous broadcast, you will receive a response with txHash immediately, but you won't know if the transaction is confirmed by the blockchain. The success of the transaction can be checked by receiving the transaction using the httpClient.getTransaction('') method. If information about the transaction is returned, transaction was successful. If an error is returned, then the transaction was not formed correctly or it is not yet in the Transaction API.

A fee will be charged for all transactions by the blockchain. You can get the current trading fees settings using httpClient.getFees() method or visit Binance Chain docs Fees info

Now let's send some messages.

  • New Order Message
  var newOrder = NewOrderMsg(
    symbol: 'BNB_BUSD-BD1',                         //market pair
    order_type: OrderType.LIMIT(),                  //order type. now only Limit order allowed
    side: OrderSide.BUY(),                          //order side: buy or sell
    time_in_force: TimeInForce.GOOD_TILL_EXPIRE(),  //time in force
    quantity: Decimal.parse('2.2734'),             
    price: Decimal.parse('0.73'),
    wallet: wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(newOrder, sync:true); // returns `APIResponse<List<Transaction>>`
  print(broadcastResponse.ok);
  print(broadcastResponse.load.first.hash); // prints transaction hash if success or null if error
  • Cancel Order Message
  var cancelOrder = CancelOrderMsg(
    symbol:'BNB_BUSD-BD1',
    order_id: '<order ID>',           
    wallet: wallet 
  );
  var broadcastResponse = await httpClient.broadcastMsg(cancelOrder, sync:true);
  print(broadcastResponse.ok);
  • Transfer Message
  var transfer = TransferMsg(
    amount: Decimal.parse('2.622'), 
    symbol: 'BNB',
    to_address: '<target address>', 
    memo: 'Description (memo)', 
    wallet: wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(transfer, sync:true);
  print(broadcastResponse.ok);
  • Multisend (Multitransfer) To send different tokens and different amounts to different addresses:
  var multiTransfer = MultiTransferMsg(
    transfers: [
      //           address                                   symbol         price 
      Transfer('bnb1h5ch0utdjfgq700qgummmhyjrdf3dwgfvx76zq', 'BNB', Decimal.parse('0.01')),
      Transfer('bnb1h5ch0utdjfgq700qgummmhyjrdf3dwgfvx76zq', 'TBC-3A7', Decimal.parse('0.02')),
      Transfer('bnb1s76hyee7xvxksxlkc4whsmc3gxuqhrqvd3y0zm', 'TBC-3A7', Decimal.parse('0.03')),
    ],
    memo: 'Description (memo)',
    wallet: wallet,
  );
  var broadcastResponse = await httpClient.broadcastMsg(miltiTransfer, sync:true);
  print(broadcastResponse.ok);

If you need to send one token with same amounts to different addresses, you may use simplified named constructor:

  var multiTransfer = MultiTransferMsg.oneTokenSameAmount(
    symbol: 'BNB',
    amount: Decimal.parse('0.1'),
    to_addresses: [
      'bnb1h5ch0utdjfgq700qgummmhyjrdf3dwgfvx76zq',
      'bnb1s76hyee7xvxksxlkc4whsmc3gxuqhrqvd3y0zm'
    ],
    memo: 'Description (memo)',
    wallet: wallet,
  );
  var broadcastResponse = await httpClient.broadcastMsg(miltiTransfer, sync:true);
  print(broadcastResponse.ok);
  • Freeze Message
  var freeze = FreezeMsg(
    symbol: 'BNB',
    amount: Decimal.parse('1.561'),
    wallet: wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(freeze, sync:true);
  print(broadcastResponse.ok);
  • UnFreeze Message
  var freeze = UnFreezeMsg(
    symbol: 'BNB',
    amount: Decimal.parse('1.561'),
    wallet: wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(freeze, sync:true);
  print(broadcastResponse.ok);
  • UnFreeze Message
  var unfreeze = UnFreezeMsg(
    symbol: 'BNB',
    amount: Decimal.parse('1.561'),
    wallet: wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(freeze, sync:true);
  print(broadcastResponse.ok);
  • Vote Message
  var vote = VoteMsg(
    627,
    VoteOption.YES(),
    wallet
  );
  var broadcastResponse = await httpClient.broadcastMsg(vote, sync:true);
  print(broadcastResponse.ok);