Skip to content

Ditch.EOS

Korzun Alexander edited this page Aug 16, 2018 · 1 revision

Goal

Easy interaction with EOS API.

.Net Standard allow to use Ditch.EOS in .NET Core, Mono, Xamarin(iOS/Mac/Android), Windows etc.

Installation

PM> Install-Package Ditch.EOS

How to use

Initialisation

public class MyApp
{
    protected RepeatHttpClient HttpClient; // Extended HttpClient (repeat request and async supported)
    protected static OperationManager Api; // Main class to interaction with Ditch.EOS

    public MyApp()
    {
        HttpClient = new RepeatHttpClient();
        Api = new OperationManager(HttpClient)
        {
            ChainUrl = ConfigurationManager.AppSettings["ChainUrl"], // path to EOS node
            WalletUrl = ConfigurationManager.AppSettings["WalletUrl"] // path to EOS Wallet (if needed)
        };
    }
    ...
}

Go to http://jungle.cryptolions.io/#account to create new test account or http://eosnetworkmonitor.io main net.

Go to http://jungle.cryptolions.io/#p2p to get url to node for "ChainUrl", for example http://dev.cryptolions.io:18888

Ditch.EOS is not a wallet! So you may:

  • Use Ditch.EOS to signing transaction, but you need to pass WIF to library
  • Use external Wallet for sighing transactions

Let`s adds login and WIF:

public string Login = "ditchtest";
public byte[] PrivateActiveWif = Base58.DecodePrivateWif("5HpybixN6DFwm13yovdsS26H6VbeTs3EXkynkPoV5zZ9vNpQiFZ");

Call to Apis

Ditch.EOS support API:

  • chain
  • history
  • wallet

see all current EOS API.

Let`s call get_info endpoint:

var infoResp = await Api.GetInfo(CancellationToken.None);

Where infoResp is: Task<OperationResult>

OperationResult is wrapper. It`s contain:

  • Result - responsed data (null if some exception was)
  • Exception - some exception (null if all going well)
  • RawRequest - Yours request for debug (if needed)
  • RawResponse - responce for debug (may be empty)

Let`s call get_block endpoint:

Some endpoints needs arguments...

var args = new GetBlockParams
{
    BlockNumOrId = infoResp.Result.LastIrreversibleBlockId
};

var blockResp = await Api.GetBlock(args, CancellationToken.None);

Let`s get some stored data from contract (call get_table_rows endpoint)

For example, get your tokens

var args = new GetTableRowsParams
{
    Code = "eosio.token", // contract name (eosio.token is one of the main contracts, it`s probably already deployed on node)
    Scope = "ditchtest", // scope... (Login) 
    Table = "accounts", // table name in the contract
    Json = true, //if true - return data in json format, otherwise return binary (abi) data.
    //LowerBound = "0",
    //UpperBound = "-1",
    //Limit = 10
};

var resp = await Api.GetTableRows(args, CancellationToken.None);

Let`s store some data to our contract (call push_transaction endpoint).

Actually, there are several steps needed to prepare and send transaction, but we will use facade function. For example let`s buy some ram:

var op = new BuyramAction
{
    Account = User.Login,       
    Args = new Buyram
    {
        Payer = User.Login,      // = WIF owner name
        Receiver = User.Login,
        Quant = new Asset("0.001 EOS")
    },
    Authorization = new[]
    {
        new PermissionLevel
        {
            Actor = User.Login,   // WIF owner name
            Permission = "active" // type of WIF needed/used for signing
        }
    }
};

* note ContractName = "eosio" and ActionName="buyram" already setted in BuyramAction constructor by default.

var resp = await Api.BroadcastActions(new[] { op }, new List<byte[]> { PrivateActiveKey }, CancellationToken.None);

If you have Wallet (EOS Wallet or Scatter) you may use another way to call function:

var resp = await Api.BroadcastActions(new[] { op }, new[] { new PublicKey(User.PublicActiveWif) }, SigningWithEosWallet,  CancellationToken.None);

private async Task<OperationResult<SignedTransaction>> SigningWithEosWallet(SignedTransaction trx, PublicKey[] keys, string chainId, CancellationToken token)
{
    await Api.WalletOpen(User.Login, token);
    await Api.WalletUnlock(User.Login, User.Password, token);
    var result = await Api.WalletSignTransaction(trx, keys, chainId, token);
    await Api.WalletLock(User.Login, CancellationToken);
    return result;
}

Connect to custom contract

Ditch.EOS not support all existing contracts (it's just impossible) from the box. But there are a class ApiContractToModelGenerator which can generate all needed models.

Let's generate code for some contract, for example for eosio account ( = eosio contract)

var contractName = "eosio";
var @namespace = "MyProjectName";
var outDir = "//MyProjectName//Contracts//";
HashSet<string> actionFilter = new[] {"newaccount"}; // if null - then generate all actions
var generator = new ContractCodeGenerator();
await generator.Generate(Api, contractName, @namespace, outDir, actionFilter, CancellationToken.None);

In outDir will be added Eosio directory (= contract name). Include it in the project and rebuild. Then let`s call new action:

var op = new NewaccountAction
{
    Account = User.Login,
    Args = new Newaccount
    {
... fill fields                  
    },
    Authorization = new[]
    {
        new PermissionLevel
        {
            Actor = User.Login,
            Permission = "active"
        }
    }
}

var resp = await Api.BroadcastActions(new[] { op }, new List<byte[]> { PrivateActiveKey }, CancellationToken.None);

Enjoy :)