Skip to content

Latest commit

 

History

History
172 lines (158 loc) · 8.64 KB

advanced.md

File metadata and controls

172 lines (158 loc) · 8.64 KB

Advanced usage

The following examples depend on:

These examples are using a wallet signer that should not be used in production, only in private!


1. Token Transfer

In the following example we will create a Token Transaction Request, sign it and send it to the network

Get the ApiProvider instance

IApiProvider provider = new ApiProvider(new ApiNetworkConfiguration(Network.DevNet));

Get a valid NetworkConfig instance

var networkConfig = await NetworkConfig.GetFromNetwork(provider);

Create a Signer instance by providing the key file and the associated password

var filePath = "PATH/TO/KEYFILE.json";
var password = "PASSWORD";
var signer = WalletSigner.FromKeyFile(filePath, password);

Set up my Account and Receiver Address

var account = Account.From(await provider.GetAccount(signer.GetAddress().Bech32));
var receiverAddress = Address.FromBech32("RECEIVER_ADDRESS");

Get a token from network

var token = Token.From(await provider.GetToken("BUSD-632f7d"));

Create the Transaction Request

var transactionRequest = TokenTransactionRequest.TokenTransfer(
    networkConfig,
    account,
    receiverAddress,
    token.Identifier,
    ESDTAmount.ESDT("100", token.GetESDT()));

Use the Wallet Methods to sign the transaction

var signature = signer.SignTransaction(transactionRequest.SerializeForSigning());
var signedTransaction = transactionRequest.ApplySignature(signature);

POST the transaction to MultiversX API

try
{
    var response = await provider.SendTransaction(signedTransaction);
    //other instructions
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Get the Transaction from response and await for execution to finalize

var transaction = Transaction.From(response.TxHash);
await transaction.AwaitExecuted(provider);
Console.WriteLine($"Transaction executed with status {transaction.Status}");

2. Smart Contract interaction

The example is created for the adder contract.

Create a EGLD Transaction Request to a Smart Contract, sign it and send it to the network

try
{
    var transactionRequest = EGLDTransactionRequest.EGLDTransferToSmartContract(
        networkConfig,
        account,
        smartContractAddress,
        ESDTAmount.Zero(),
        "add",
        NumericValue.BigUintValue(10));
    var signature = signer.SignTransaction(transactionRequest.SerializeForSigning());
    var signedTransaction = transactionRequest.ApplySignature(signature);
    var response = await provider.SendTransaction(signedTransaction);
    var transaction = Transaction.From(response.TxHash);
    await transaction.AwaitExecuted(provider);
    Console.WriteLine($"Transaction executed with status {transaction.Status}");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Query smart contract (no ABI available)

var smartContractAddress = Address.FromBech32("CONTRACT_BECH32_ADDRESS");
var outputTypes = new TypeValue[] { TypeValue.BigUintTypeValue };
var queryResult = await SmartContract.QuerySmartContract<NumericValue>(provider,
                                                                       smartContractAddress,
                                                                       outputTypes,
                                                                       "getSum");
Console.WriteLine(queryResult.Number);

// query array from Smart Contract
var queryArrayResult = await SmartContract.QuerySmartContract<VariadicValue>(provider,
                                                                             smartContractAddress,
                                                                             new TypeValue[] { TypeValue.VariadicValue(TypeValue.AddressValue) },
                                                                             "getUsers");
foreach (var user in queryArrayResult)
    Console.WriteLine(user.Bech32);

// more complex reading from Smart Contract storage
uint day = 1;
var dayRewards = await SmartContract.QuerySmartContract<VariadicValue>(provider,
                                                                       smartContractAddress,
                                                                       new TypeValue[] { TypeValue.VariadicValue(TypeValue.StructValue("EsdtTokenPayment", new FieldDefinition[3]
                                                                       {
                                                                           new FieldDefinition("token_identifier", "", TypeValue.TokenIdentifierValue),
                                                                           new FieldDefinition("token_nonce", "", TypeValue.U64TypeValue),
                                                                           new FieldDefinition("amount", "", TypeValue.BigUintTypeValue)
                                                                       }))},
                                                                       "getDayRewards",
                                                                       null,
                                                                       NumericValue.U32Value(day));
foreach(var esdt in dayRewards)
    Console.WriteLine($"{esdt.Fields[0].Value} {esdt.Fields[1].Value} {esdt.Fields[2].Value}");
// You can map the StructValue from response to you custom class object for easier usage, if you need
// e.g. var tokens = dayRewards.ToObject<List<Token>>(); //Token is a class with 3 properties [string Identifier, ulong Nonce, BigInteger Amount]

//Enum example
var enumResult = await SmartContract.QuerySmartContract<EnumValue>(provider,
                                                                   smartContractAddress,
                                                                   new TypeValue[] {TypeValue.EnumValue("enum", new VariantDefinition[]
                                                                   {
                                                                       new("InvalidPool", "", 0, null),
                                                                       new("SimplePool", "", 1, null),
                                                                       new("ComplexPool", "", 2, null)
                                                                   })},
                                                                   "getPoolType");

Query smart contract (ABI available)

More examples ca be found in the Testing Project here
var abi = AbiDefinition.FromFilePath("abi.json");

//Variadic example
var addresses = await SmartContract.QuerySmartContractWithAbiDefinition<VariadicValue>(
                provider,
                smartContractAddress,
                abi,
                "getVariadicManagedAddress");

var addressesList = addresses.ToObject<List<Address>>();

//Enum example
enum PoolType
{
    InvalidPool,
    SimplePool,
    ComplexPool
}
var enumResult = await SmartContract.QuerySmartContractWithAbiDefinition<EnumValue>(provider,
                                                                                    smartContractAddress,
                                                                                    abi,
                                                                                    "getPoolType");
var poolType = enumResult.ToEnum<PoolType>();