Buy and sell any erc20 token on oceanone through go

Time:2019-11-5

Buy and sell any erc20 token on oceanone through go

In the last lesson, we introduced how to trade bitcoin in oceanone. Oceanone supports the transaction of any token on the mixin network, including all erc20 and EOS tokens, without any formalities and fees, and can directly register the order. Here’s how to put an erc20 token on the oceanone transaction! After mastering erc20 token, you can buy and sell any token on ocean.

Here we use an erc20 token called Benz as an example. This token has been recharged into mixin network. You can see the total number and transaction of this token in mixin network in the blockchain browser

Preparatory knowledge:

First deposit the Ben into your wallet, and then useReadAssetsAPI reads its UUID

Get UUID of the currency

callReadAssetsThe API will return JSON data, such as:

  • asset_idUUID. of coins
  • public_keyThe address of the current wallet for the currency
  • symbolThe name of the coin
if cmd == "aw" {
  priKey, _, sID, userID, _ := GetWalletInfo()
  assets, err := mixin.ReadAssets(userID,sID,priKey)
  if err != nil {
      log.Fatal(err)
  }
  var AssetsInfo map[string]interface{}
  err = json.Unmarshal(assets, &AssetsInfo)
  if err != nil {
      log.Fatal(err)
  }
  // fmt.Println("Data is: ",AssetsInfo["data"].(map[string]interface{})["public_key"])
  for _, v := range (AssetsInfo["data"].([]interface{})) {
    if v.(map[string]interface{})["symbol"] == "EOS" {
      fmt.Println(v.(map[string]interface{})["symbol"]," ",
                  v.(map[string]interface{})["asset_id"]," ",
                  v.(map[string]interface{})["account_name"]," ",
                  v.(map[string]interface{})["account_tag"]," ",
                  v.(map[string]interface{})["balance"])
    } else {
      fmt.Println(v.(map[string]interface{})["symbol"]," ",
                  v.(map[string]interface{})["asset_id"]," ",
                  v.(map[string]interface{})["public_key"]," ",
                  v.(map[string]interface{})["balance"])
    }
  }
}

callReadAssetsThe complete output of the API is as follows:

Make your choose:aw
Benz   0x330860Ec473fF366F5Bc4339a69f5bffB52d18Cb   88.9
EOS   eoswithmixin   79dd76cedf8f6af49a8d98216bbde890   0
USDT   16wWhKAjmACvZzkfxkyrVutqfrJ1JQ83aj   1
CNB   0x330860Ec473fF366F5Bc4339a69f5bffB52d18Cb   0.10999989
BTC   16wWhKAjmACvZzkfxkyrVutqfrJ1JQ83aj   0
XIN   0x330860Ec473fF366F5Bc4339a69f5bffB52d18Cb   0.01

limit entry

  • Pay with limit priceA single below or equal to the market price
  • Sell with limited priceA single above or equal to the market price

Oceanone supports three basic types of prices: usdt, Xin, BTC, i.e. Benz / usdt, Benz / Xin, Benz / BTC, which is demonstrated here

Limit the price and put up a sales order

After registering the new currency, you need to wait about a minute, wait for oceanone to initialize the data related to the new currency

if cmd == "s2" {
  fmt.Print("Please input the price of ERC20/USDT: ")
  var pcmd string
  var acmd string
  scanner.Scan()
  pcmd = scanner.Text()
  fmt.Println(pcmd)
  fmt.Print("Please input the amount of ERC20: ")
  scanner.Scan()
  acmd = scanner.Text()
  fmt.Println(acmd)
  omemo := generateOceanOrderMemo(mixin.GetAssetId("USDT"),"A",pcmd)
  priKey, pToken, sID, userID, uPIN := GetWalletInfo()
  balance := ReadAssetBalanceByUUID(ERC20_BENZ,userID,sID,priKey)
  fmt.Println(balance)
  fbalance, _ := strconv.ParseFloat(balance,64)
  abalance, _ := strconv.ParseFloat(acmd,64)
  if fbalance > 0 && fbalance >= abalance {
    fmt.Println(omemo)
    transInfo, _ := mixin.Transfer(OCEANONE_BOT,
                                   acmd,
                                   ERC20_BENZ,
                                   omemo,
                                   messenger.UuidNewV4().String(),
                                   uPIN,pToken,userID,sID,priKey)
    fmt.Println(string(transInfo))
    var jsTransInfo map[string]interface{}
    err := json.Unmarshal([]byte(transInfo), &jsTransInfo)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("The Order id is " + jsTransInfo["data"].(map[string]interface{})["trace_id"].(string) +
               " it is needed to cancel the order!")
  } else { fmt.Println("Not enough BenZ!") }
}

Limit the price and pay for it

After registering the new currency, you need to wait about a minute, wait for oceanone to initialize the data related to the new currency

if cmd == "b2" {
  fmt.Print("Please input the price of ERC20/USDT: ")
  var pcmd string
  var acmd string
  scanner.Scan()
  pcmd = scanner.Text()
  fmt.Println(pcmd)
  fmt.Print("Please input the amount of USDT: ")
  scanner.Scan()
  acmd = scanner.Text()
  fmt.Println(acmd)
  omemo := generateOceanOrderMemo(ERC20_BENZ,"B",pcmd)
  priKey, pToken, sID, userID, uPIN := GetWalletInfo()
  balance := ReadAssetBalance("USDT",userID,sID,priKey)
  fmt.Println(balance)
  fbalance, _ := strconv.ParseFloat(balance,64)
  abalance, _ := strconv.ParseFloat(acmd,64)
  if fbalance > 0 && fbalance >= abalance {
    fmt.Println(omemo)
    transInfo, _ := mixin.Transfer(OCEANONE_BOT,
                                   acmd,
                                   mixin.GetAssetId("USDT"),
                                   omemo,
                                   messenger.UuidNewV4().String(),
                                   uPIN,pToken,userID,sID,priKey)
    fmt.Println(string(transInfo))
    var jsTransInfo map[string]interface{}
    err := json.Unmarshal([]byte(transInfo), &jsTransInfo)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("The Order id is " + jsTransInfo["data"].(map[string]interface{})["trace_id"].(string) +
               " it is needed to cancel the order!")
  } else { fmt.Println("Not enough USDT!") }
}//end of b2

Read price list of currency

Read the price list of currency to confirm whether the registration is successful!

if cmd == "3" {
   FormatOceanOneMarketPrice(mixin.GetAssetId("BTC"),mixin.GetAssetId("USDT"))
 }
func FormatOceanOneMarketPrice(asset_id string, base_asset string) {
 priceInfo, err := GetOceanOneMarketPrice(asset_id, base_asset)
 if err != nil {
   log.Fatal(err)
 }

 var marketInfo map[string]interface{}
 err = json.Unmarshal([]byte(priceInfo), &marketInfo)
  fmt.Println("Price | Amount | Funds | Side")
 for _, v := range (marketInfo["data"].
                   (map[string]interface{})["data"].
                   (map[string]interface{})["asks"].
                   ([]interface{})) {
   fmt.Println(v.(map[string]interface{})["price"],
               v.(map[string]interface{})["amount"],
               v.(map[string]interface{})["funds"],
               v.(map[string]interface{})["side"],
              )
 }
 for _, v := range (marketInfo["data"].
                   (map[string]interface{})["data"].
                   (map[string]interface{})["bids"].
                   ([]interface{})) {
   fmt.Println(v.(map[string]interface{})["price"],
               v.(map[string]interface{})["amount"],
               v.(map[string]interface{})["funds"],
               v.(map[string]interface{})["side"],
              )
 }
}
func GetOceanOneMarketPrice(asset_id string, base_asset string) ([]byte, error)  {
    var body []byte
    req, err := http.NewRequest("GET", "https://events.ocean.one/markets/" + asset_id + "-" + base_asset + "/book",
                             bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", "application/json")

    resp, err := httpClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
 // fmt.Println(resp.Body)
    bt, err := ioutil.ReadAll(resp.Body)
    if resp.StatusCode != http.StatusOK {
        var resp struct {
            Error Error `json:"error"`
        }
        err = json.Unmarshal(bt, &resp)
        if err == nil {
            err = resp.Error
        }
    }
    return bt, err
}

Erc20 related operation instructions

Commands list of this source code:

  • trb:Transfer ERC20 from Bot to Wallet
  • trm:Transfer ERC20 from Wallet to Master
  • o: Ocean.One Exchange

Make your choose(eg: q for Exit!):

  • 3: Orders-Book of ERC20/USDT
  • b3: Buy ERC20 pay USDT
  • s3: Sell ERC20 get USDT
  • c: Cancel the order
  • q: Exit

Complete code

Recommended Today

Details of multi-path and large capacity hard disk mount under CentOS

I. application environment and requirementsBlade servers connect HP storage through fiber switches, forming a 2×2 link The storage capacity of the operating system for CentOS 6.4 64 bit mount is 2.5t Based on this application environment, two problems need to be solved: In order to ensure the stability and transmission performance of the link, multi-path […]