Skip to content

Credits API in C#

angelesmanzo edited this page May 29, 2019 · 4 revisions

Creation and execution of transactions with Credits API (in C#)


Which transaction fields must be filled:

//Create a transaction (transfer from a wallet to another wallet)

var transaction = new Transaction();

//Internal transaction number (id)

transaction.Id = client.WalletTransactionsCountGet(sourceKeys.PublicKeyBytes).LastTransactionInnerId + 1;

//Initial wallet byte array

transaction.Source = sourceKeys.PublicKeyBytes;

//Target wallet byte array

transaction.Target = targetKeys.PublicKeyBytes;

//Quantity of transferable coins

transaction.Amount = new Amount(1, 0);

//Commission

transaction.Fee = new AmountCommission(Fee(0.9));
transaction.Currency = 1;

Field Completion for transaction signature

It is necessary to create a byte array with a size of 85 bytes.

Table completion

table2

Last element of the array is filled out with zero (0).

Example of completion:

var bytes = new byte[86];
Array.Copy(BitConverter.GetBytes(transaction.Id), 0, bytes, 0, 6);
Array.Copy(transaction.Source, 0, bytes, 6, 32);
Array.Copy(transaction.Target, 0, bytes, 38, 32);
Array.Copy(BitConverter.GetBytes(transaction.Amount.Integral), 0, bytes, 70, 4);
Array.Copy(BitConverter.GetBytes(transaction.Amount.Fraction), 0, bytes, 74, 8);
Array.Copy(BitConverter.GetBytes(transaction.Fee.Commission), 0, bytes, 82, 2);
bytes[84] = 1;
bytes[85] = 0;

Concern

It is necessary to convert commission value from double to short. For example:

// Commission

transaction.Fee = new AmountCommission(Fee(0.9));

private short Fee(Double value)
{
    byte sign = (byte)(value < 0.0 ? 1 : 0); // sign
    int exp;   // exponent
    long frac; // mantissa
    value = Math.Abs(value);
    double expf = value == 0.0 ? 0.0 : Math.Log10(value);
    int expi = Convert.ToInt32(expf >= 0 ? expf + 0.5 : expf - 0.5);
    value /= Math.Pow(10, expi);
    if (value >= 1.0)
    {
        value *= 0.1;
        ++expi;
    }
    exp = expi + 18;
    if (exp < 0 || exp > 28)
    {
        throw new Exception($"exponent value {exp} out of range [0, 28]");
    }
    frac = (long)Math.Round(value * 1024);
    return (short)(sign * 32768 + exp * 1024 + frac);
}

Transaction Execution

public TransactionFlowResult ExecuteTransaction()
{
    return client.TransactionFlow(CreateTransaction());
}

Here, clearly is showed that the transaction which creates method: CreateTransaction(), is transfered to method: TransactionFlow() for execution. TransactionFlow() is a Credits API method.