Best of Crypto

Best of Crypto

1655004660

BUSD Stablecoin Smart Contract Elrond Written in Rust

Elrond BUSD stablecoin

BUSD stablecoin smart contract Elrond implementation and tests

How to build

First, install erdpy

In short:

pip3 install --user --upgrade --no-cache-dir erdpy

More details here: https://github.com/ElrondNetwork/erdpy/blob/master/README.md

Build command

erdpy build .

Run tests

All tests:

erdpy --verbose test --directory="tests"

To debug individual tests (example):

erdpy --verbose test --directory="tests/init/create.scen.json"

Deploy

erdpy --verbose deploy . --pem="./alice.pem" --proxy="https://wallet-api.elrond.com"
erdpy --verbose query erd1qqqqqqqqqqqqqpgq9sp6f9m9zzhepfl0e02cy9m9tnztry2kx2fsf96449 --function="name" --proxy="https://wallet-api.elrond.com"

Learn More

Current implementation directly translated from https://github.com/paxosglobal/busd-contract from Solidity to elrond-wasm Rust.

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/sc-busd-rs
License: GPL-3.0 license

#elrond  #blockchain  #smartcontract #rust 

BUSD Stablecoin Smart Contract Elrond Written in Rust
Best of Crypto

Best of Crypto

1654997280

Erdwalletjs Http: Generate Accounts & Sign Transactions for Elrond

erdwalletjs-http

Lighweight HTTP utility to generate accounts and sign transactions for the Elrond Network.

This utility relies on elrond-core-js to generate accounts and sign transactions.

This HTTP utility should only be used in secure, off-line, environments. Do not host or use this on a web server.

Setup and start

Please make sure you have a recent version of NodeJS installed.

git clone https://github.com/ElrondNetwork/erdwalletjs-http.git
cd erdwalletjs-http
npm install
node ./index.js

Currently, the API will listen to http://localhost:8080 (port not yet configurable).

API

For API examples, please see client.http as well.

Generate an account

One can generate an Elrond account - address, mnemonic, private key and key-file wallet - using the account/new route.

The password field is optional, and it will be used to generate the symmetrically encrypted JSON key-file wallet.

Request:

POST {{baseUrl}}/account/new
Content-Type: application/json

{
    "password": "foobar"
}

Response:

The response contains the mnemonic phrase, plus data derived from it: the private key, the address (in bech32 format). Additionally, a key-file object (the content of the Elrond JSON key-file wallet) is returned.


{
  "code": "success",
  "data": {
    "mnemonic": "home stamp ...",
    "privateKey": "4aa6...",
    "address": "erd1...",
    "keyFilePassword": "foobar",
    "keyFileObject": {
      ...
    }
  }
}

Sign a transaction

Request:

Note that the data (memo) field should be in plain UTF-8. The signing process will encode it in base-64.

The sender field must not be set. It will be filled-in by the signing process.

{
    "transaction": {
        "nonce": 42,
        "receiver": "erd1...",
        "value": "100000000000000000",
        "gasPrice": 1000000000,
        "gasLimit": 70000,
        "data": "food for cats",
        "chainID": "1",
        "version": 1
    }, 
    "privateKey": "f3062..."
}

Response:

The response is a ready-to-broadcast Elrond transaction.

Note how the data field is encoded in the response.

{
  "code": "success",
  "data": {
    "nonce": 42,
    "value": "100000000000000000",
    "receiver": "erd1...",
    "sender": "erd1...",
    "gasPrice": 1000000000,
    "gasLimit": 70000,
    "data": "Zm9vZCBmb3IgY2F0cw==",
    "chainID": "1",
    "version": 1,
    "signature": "7f2e..."
  }
}

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/erdwalletjs-http
License:

#elrond  #blockchain  #smartcontract #javascript 

Erdwalletjs Http: Generate Accounts & Sign Transactions for Elrond
Best of Crypto

Best of Crypto

1654989900

Rust Smart Contract Used to Distribute ESDT Tokens

sc-distribution-rs

Smart contract used for distribution of ESDT tokens, in particular for MEX.

The big picture

Works in combination with snapshots scripts. Those are supposed to set the rewards for each user and each user is supposed to claim its rewards. The SC expects its distributed token to have been issued and have already been set LocalMint and LocalBurn roles for it.

How it works

Setting up community rewards

For setting up community rewards, the owner of the contract calls setCommunityReward with the total_amount and unlock_epoch. This operation is a GlobalOperation so startGlobalOperation needs to be called.

Setting up user rewards

For setting up user rewards, the owner of the contract calls setPerUserRewards with: unlock_epoch a vector (user_address, amount). This operation is a GlobalOperation so startGlobalOperation needs to be called. This operation can run out of gas when called with a large vector. So it should be called multiple times with smaller chunks. The contract does certain verifications, like the community total amount should be greater or equal with the sum of all users rewards set. Also it checks for duplicates in the arrays. In case of human error, undo functions can be called in order to revert last community reward (undoLastCommunityReward) and user rewards (undoUserRewardsBetweenEpochs) between certain epochs. These functions are also Global Operations.

Claiming rewards

The user can claim its rewards by calling claimRewards. The rewards will be calculated for the last maximum of 4 reward distributions. Anything above that will become unclaimable. The owner of the contract can call clearUnclaimableRewards in order to clear the rewards accumulated and that are unclaimable. This function should never run out of gas and should be called until it returns the value 0, which is the amount of user rewards cleared in that specific transaction. This function wil fail if a GlobalOperation is ongoing.

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/sc-distribution-rs
License: GPL-3.0 license

#elrond  #blockchain  #smartcontract #rust 

Rust Smart Contract Used to Distribute ESDT Tokens
Best of Crypto

Best of Crypto

1654982580

Smart Contract Offering Flash Loans Written in Rust

Flash Mint Smart Contract

This Smart Contract is a general purpose Flash Loan Provider with the particularity that it does not need any funds to be added by providers, instead it Mints the requested tokens and lets the user use them as he wishes by the time the transaction ends.

It can be used for any number of tokens, the owner being the one that can configure the per token Loan Service Settings (including for example the fee percent).

Endpoints

flashLoan

This is the endpoint that a user can use to loan tokens and configure an action to be executed with the tokens. The arguments are:

    loan_token_id: TokenIdentifier,
    loan_amount: Self::BigUint,
    address: Address,
    function: BoxedBytes,
    gas_limit: u64,
    #[var_args] arguments: MultiArgVec<BoxedBytes>,

By calling this endpoint, the following flow of actions with happen (assuming input values are correct):

  • The contract will mint loan_amount of loan_token_id
  • The contract will transfer the minted tokens and will execute function at given address with given gas_limit and arguments
  • The contract will expect the payback to be received via acceptPayback endpoint. The contract will only accept funds while a flash loan is ongoing and will only accept loan_token_id tokens.
  • The contract will check if the loan was paid back (the initial amount + a configured fee). The whole transaction will be reverted if this check fails. For example, if a user requests a loan of 100 tokenA and the fee percent for tokenA is 10%, the contract will verify it's balance and will expect to have at least 110 tokenA.
  • The contract will send the fees to a configured address.

This function is not re-entrant, meaning that one cannot call it multiple times in a nested way.

configureTokenLoanServiceSettings

This endpoint can be used only by the owner in order to configure the Loan Service Settings for a speficic Token. The arguments are:

    token_id: TokenIdentifier,
    minimum_loan_amount: Self::BigUint,
    maximum_loan_amount: Self::BigUint,
    fee_percent: u64,
    fee_transfer_gas_limit: u64,
    fee_destination_addr: Address,
    fee_destination_func: BoxedBytes,

Any Flash Mint Loans with the token_id will respect the boundry configured [minimum_loan_amount, maximum_loan_amount].

  • Any Successful Flash Mint Loans with the token_id will produce a fee of the configured fee_percent and will transfer the fee tokens them and execute fee_destination_func at fee_destination_addr with fee_transfer_gas_limit.
  • After calling this function, the owner must make sure the contract has EsdtLocalMint and EsdtLocalBurn roles for the configured token_id.

removeTokenLoanService

This endpoint can be used only by the owner in order to delete the settings for a specific token, hence will not allow Flash Mint Loans for it.

getTokenLoanServiceSettingsList and getLoanServiceSettings

This view function can be used by anyone. Their purpose is to allow the user check the tokens that are available for Flash Mint Lending and what are the Loan Service Settings (most important what is the fee_percent).

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/sc-flash-mint-rs
License: GPL-3.0 license

#elrond  #blockchain  #smartcontract 

Smart Contract Offering Flash Loans Written in Rust
Best of Crypto

Best of Crypto

1654975200

Express API: REST API to interact with The Elrond Blockchain

REST API facade facilitating the interactions with the Elrond blockchain.

Quick start

  1. Run npm install in the project directory
  2. Optionally make edits to config.js
  3. Make sure you create a .env file in project root and specify the config information

.env Example content

CONFIG=mainnet/testnet/devnet
PrivateElastic=true/false
PrivateElasticUsername="username"
PrivateElasticPassword="password"

Available Scripts

​ In the project directory, you can run: ​

npm run start

​ Runs the app in the production mode. Make requests to http://localhost:3000.

npm run start-dev

​ Runs the app in the development mode. Make requests to http://localhost:3000. The app will reload if you make edits. You will also see any lint errors in the console. ​

npm run test

​ Launches the test runner in the interactive watch mode.

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/express-api
License:

#elrond  #blockchain  #smartcontract #express #api #javascript 

Express API: REST API to interact with The Elrond Blockchain
Best of Crypto

Best of Crypto

1654967880

The Chainlink Node and Elrond Adapter

INTRODUCTION

Scripts will install and run a Chainlink Node complete with Postgresql DB and the Elrond Chainlink Connector. The Chainlink Node and Elrond Adapter will run as system services that can be turned on/off independently.

REQUIREMENTS

  • Running Ubuntu 20.04 & up
  • Running the script requires a user (not root) with sudo priviledges (without password).

SCRIPT SETTINGS - MUST BE MODIFIED BEFORE FIRST RUN

  • config/variables.cfg - used to define username, home path, database options and chainlink node options.

KEY MANAGEMENT

Before installing/running be sure to add a valid owner.pem to the script PEM folder.

  • create a folder named PEM inside the scripts folder
  • add the owner.pem file inside the previously created folder

RUNNING THE SCRIPT

[FIRST RUN]

./script.sh install - installs the everything needed to run the elrond-adapter;

[START]

./script.sh start_chainlink - starts the Chainlink Node; ./script.sh start_adapter - starts the Elrond Adapter;

[STOP]

./script.sh stop_chainlink - stops the Chainlink Node; ./script.sh stop_adapter - stops the Elrond Adapter;

[CLEANUP]

./script.sh clean - #Removes installed packages;

API Examples (elrond-adapter)

HTTP POST /write endpoint

Sends transaction and writes the request data to the Elrond network

Input:

{
  "id": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {
    "value": "15051",
    "data": {},
    "sc_address": "erd1...",
    "function": "submit_endpoint",
    "round_id": "145"
  }
}

Output:

{
  "jobRunID": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {
    "result": "19feccf4b8590bcc9554ad632ff23f8344d0318fbac643bdba5fa7a605373bf4"
  },
  "result": "19feccf4b8590bcc9554ad632ff23f8344d0318fbac643bdba5fa7a605373bf4",
  "statusCode": 200
}

HTTP POST /price-job endpoint

Starts a price feed job which aggregates feeds from multiple sources and pushes data in the aggregator smart contract

Data body can be left empty, it reads input values from config.toml

Input:

{
  "id": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {}
}

Output:

{
  "jobRunID": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {
    "result": {
      "txHashes": [
        "25d1731151692cd75aa605dcad376c6acf0cd22d6fe0a1ea50a8e2cd25c16f27",
        "f95060ff47bc676f63a72cc5a51ead7ebbb1a21131d60e2273d5148a2fea3d95",
        "3a3092ba6bf49ad54afbdb2b08efa91b6b024e25753797dee675091c9b8f1891",
        "102ff3ef391cb4c53de2b9c672a98a4dca0c93da53be7255c827c60c8da029d3",
        "9c0c4c1ab8372efc21c4bbcadfc79162564e9895c91f73d942cb96be53ddd27e"
      ]
    }
  },
  "result": {
    "txHashes": [
      "25d1731151692cd75aa605dcad376c6acf0cd22d6fe0a1ea50a8e2cd25c16f27",
      "f95060ff47bc676f63a72cc5a51ead7ebbb1a21131d60e2273d5148a2fea3d95",
      "3a3092ba6bf49ad54afbdb2b08efa91b6b024e25753797dee675091c9b8f1891",
      "102ff3ef391cb4c53de2b9c672a98a4dca0c93da53be7255c827c60c8da029d3",
      "9c0c4c1ab8372efc21c4bbcadfc79162564e9895c91f73d942cb96be53ddd27e"
    ]
  },
  "statusCode": 200
}

HTTP POST /ethgas/denominate endpoint

Fetched latest eth gas prices, in gwei and denominates the value in a specified asset. e.g GWEI/EGLD

Data body can be left empty, it reads input values from config.toml

Input:

{
  "id": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {}
}

Output:

{
  "jobRunID": "bbfd3e3a8aed4d46abb0a89764951bf9",
  "data": {
    "result": "19feccf4b8590bcc9554ad632ff23f8344d0318fbac643bdba5fa7a605373bf4"
  },
  "result": "19feccf4b8590bcc9554ad632ff23f8344d0318fbac643bdba5fa7a605373bf4",
  "statusCode": 200
}

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-chainlink-scripts
License:

#elrond #chainlink #shell  #blockchain  #smartcontract 

The Chainlink Node and Elrond Adapter
Best of Crypto

Best of Crypto

1654960500

Elrond C++ SDK for Interacting with Elrond Network & Smart Contracts

elrond-sdk-erdcpp

Elrond C++ Command Line Tools and SDK for interacting with the Elrond Network (in general) and Smart Contracts (in particular).

1. Instalation. How to use it

1.1 Update submodules

Elrond C++ SDK CLI uses google test which is configured as submodule. After cloning the repository, make sure to initialize and update the submodule:

git submodule update --init --recursive

1.2 Dependencies

Elrond C++ SDK CLI uses:

  • Libsodium shared library. Make sure to install the latest version.

1.3 Compile and build with CMake

cmake .
cmake --build .

1.4 Usage

1.4.1 SDK

After building with cmake, you can use the SDK by:

  • Adding the include folder to your project. Then you only need to include one header to your project:
#include "erdsdk.h"
  • Add the library generated in src file

1.4.2 CLI SDK

cd cli
./erdcpp -h

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-sdk-erdcpp
License: MIT license

#elrond  #blockchain  #smartcontract #cpluplus 

Elrond C++ SDK for Interacting with Elrond Network & Smart Contracts
Best of Crypto

Best of Crypto

1654953180

NestJS Framework TypeScript Starter Repository for Elrond

Description

Nest framework TypeScript starter repository.

Installation

$ npm install

Running the app

# development
$ npm run start:devnet

# watch mode
$ npm run start:devnet:watch

# production mode
$ npm run start:mainnet

Running second microservice

# development
$ npm run start:microservice:devnet

# watch mode
$ npm run start:microservice:devnet:watch

# production mode
$ npm run start:microservice:mainnet

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Download Details:
Author: ElrondNetwork
Source Code: 
License:

#elrond #typescript  #blockchain  #smartcontract 

NestJS Framework TypeScript Starter Repository for Elrond
Best of Crypto

Best of Crypto

1654945800

Elrond Kotlin SDK for interacting with Elrond Network & Smart Contract

Elrond Kotlin SDK

This is the kotlin implementation of Elrond SDK

This project was primarily designed for Android but is also compatible with any Kotlin-friendly app since it doesn't use the Android SDK

Usage

This SDK is built with the clean architecture principles.
Interaction are done through usecases

Here is an example for sending a transaction.

// Create a wallet from mnemonics
val wallet = Wallet.createFromMnemonic(..., 0)

// Get information related to this address (ie: balance and nonce)
val account = ErdSdk.getAccountUsecase().execute(Address.fromHex(wallet.publicKeyHex))

// Get the network informations
val networkConfig = ErdSdk.getNetworkConfigUsecase().execute()

// Create the transaction object
val transaction = Transaction(
    sender = account.address,
    receiver = Address.fromHex(...),
    value = 1000000000000000000.toBigInteger(), // 1 xEGLD
    data = "Elrond rocks !",
    chainID = networkConfig.chainID,
    gasPrice = networkConfig.minGasPrice,
    gasLimit = networkConfig.minGasLimit,
    nonce = account.nonce
)

// Send transaction.
// Signature is handled internally
val sentTransaction = ErdSdk.sendTransactionUsecase().execute(transaction, wallet)
Log.d("Transaction", "tx:${sentTransaction.txHash}")

In a real world example, the usescases would be injected
The sample application showcase how to do it on Android with Hilt framework (see the Sample App).

Usecases list

API

UsecaseEndpoint
GetAccountUsecaseGET address/:bech32Address
GetAddressBalanceUsecaseGET address/:bech32Address/balance
GetAddressNonceUsecaseGET address/:bech32Address/nonce
GetAddressTransactionsUsecaseGET address/:bech32Address/transactions
GetTransactionInfoUsecaseGET transaction/:txHash
GetTransactionStatusUsecaseGET transaction/:txHash/status
SendTransactionUsecasePOST transaction/send
EstimateCostOfTransactionUsecasePOST transaction/cost
GetNetworkConfigUsecaseGET network/config
QueryContractUsecasePOST vm-values/query
QueryContractHexUsecasePOST vm-values/hex
QueryContractStringUsecasePOST vm-values/string
QueryContractIntUsecasePOST vm-values/int

Contract

UsecaseDescription
CallContractUsecaseInteract with a Smart Contract (execute function): equivalent to erdpy contract call

DNS

UsecaseDescription
RegisterDnsUsecaseSend a register transaction to the appropriate DNS contract from given user and with given name: equivalent to erdpy dns register
GetDnsRegistrationCostUsecaseGets the registration cost from a DNS smart contract: equivalent to erdpy dns registration-cost
CheckUsernameUsecaseCan be useful for validating a text field before calling RegisterDnsUsecase

Configuration

// default value is ProviderUrl.DevNet
ErdSdk.setNetwork(ProviderUrl.MainNet)

// configure the OkHttpClient
ErdSdk.elrondHttpClientBuilder.apply {
    addInterceptor(HttpLoggingInterceptor())
}

Build

The SDK is not yet uploaded to a maven repository
You can build the jar from the sources by running mvn package

Sample App

For a complete example you can checkout this sample application

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-sdk-erdkotlin
License: GPL-3.0 license

#elrond #kotlin  #blockchain  #smartcontract 

Elrond Kotlin SDK for interacting with Elrond Network & Smart Contract
Best of Crypto

Best of Crypto

1654938420

Deployment Tools for Elrond network Written in Go

Elrond deploy go

The go implementation for the Elrond deploy

Getting started

Prerequisites

Building the repository requires Go (version 1.12 or later)

Installation and running

Run in %project_folder%/cmd/filegen folder the following command to build a filegen (which generates .pem and .json files used by the node):

To run in "direct" staking mode, please run this:

$ go build
$ ./filegen -stake-type direct -node-price 2500000000000000000000 -total-supply 20000000000000000000000000 -num-of-shards 3 -num-of-nodes-in-each-shard 7 -consensus-group-size 5 -num-of-observers-in-each-shard 1 -num-of-metachain-nodes 7 -metachain-consensus-group-size 7 -num-of-observers-in-metachain 1 -hysteresis 0.2

To run in "delegated" staking mode, please run this:

$ go build
$ ./filegen -stake-type delegated -node-price 2500000000000000000000 -total-supply 20000000000000000000000000 -num-of-shards 3 -num-of-nodes-in-each-shard 7 -consensus-group-size 5 -num-of-observers-in-each-shard 1 -num-of-metachain-nodes 7 -metachain-consensus-group-size 7 -num-of-observers-in-metachain 1 -hysteresis 0.2 -num-delegators 1293

In the "delegated" mode the initial staking will be done through the delegation SC. When set to "delegated" mode, there are 2 optional flags delegation-init for setting a custom init string and delegation-version for setting the correspondent delegation SC version.

Important:

If the hysteresis value is greater than 0, the binary will add more nodes as validators in order to compensate for the nodes in the waiting list.

Notes:

The optional flag called -richest-account can be used in order to increase the first wallet key to almost all available balance left after the staking process occurred. This is helpful when dealing with automated staking scenarios.

Running with docker

$ docker pull elrondnetwork/elrond-go-filegen:tagname
$ docker run -v /tmp/:/data/ elrondnetwork/elrond-go-filegen:latest -stake-type direct -node-price 2500000000000000000000 -total-supply 20000000000000000000000000 -num-of-shards 3 ...

This will create the files on the host machine running Docker at the path location /tmp/. Detailed information about the build is located under https://hub.docker.com/r/elrondnetwork/elrond-go-filegen

Running the tests

$ go test ./...

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-deploy-go
License:

#elrond  #blockchain  #smartcontract #go 

Deployment Tools for Elrond network Written in Go
Best of Crypto

Best of Crypto

1654931100

Polychain Relayer for Elrond Network Written in Go

Elrond-Relayer

This program is still under developing!

Elrond Relayer is an important character of Poly cross-chain interactive protocol which is responsible for relaying cross-chain transaction from and to Elrond.

Build From Source

Prerequisites

Build

git clone https://github.com/ElrondNetwork/elrond-polychain-relayer.git
cd elrond-polychain-relayer
go build -o elrond-polychain-relayer main.go

Run Relayer

Before you can run the relayer you will need to create a wallet file of PolyNetwork. After creation, you need to register it as a Relayer to Poly net and get consensus nodes approving your registeration. And then you can send transaction to Poly net and start relaying.

After that, make sure you already have a Elrond wallet with EGLD.

Before running, you need feed the configuration file config.json.

{
  "ElrondConfig": {
    "ElrondChainID": "",
    "ElrondTxVersion": 1,
    "ElrondBlockMonitorIntervalInSeconds": 6,
    "BlocksPerBatch": 15,
    "ElrondForceHeight": 0,
    "RestURL": "https://gateway.elrond.com",
    "SideChainID": 100,
    "CrossChainManagerContract": "",
    "BlockHeaderSyncContract": "",
    "KeyStorePath": "",
    "KeyStorePwdSet": {
      "": "",
    }
  },
  "PolyConfig": {
    "ChainID": 2,
    "RestURL": "http://beta1.poly.network:20336",
    "EntranceContractAddress": "0300000000000000000000000000000000000000",
    "OntUsefulBlocksNum": 1,
    "WalletFile": "./wallet.dat",
    "WalletPwd": "",
    "PolyStartHeight": 0,
    "PolyMonitorIntervalSeconds": 10
  },
  "BoltDbPath": "./db",
  "RoutineNum": 10,
  "TargetContracts": [
    {
      "0xD8aE73e06552E...bcAbf9277a1aac99": {
        "inbound": [6],
        "outbound": [6]
      }
    }
  ]
}

Now, you can start relayer as follow:

./elrond-polychain-relayer --cliconfig=./config.json 

It will generate logs under ./Log and check relayer status by view log file.

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-polychain-relayer
License:

#elrond  #blockchain  #smartcontract #go 

Polychain Relayer for Elrond Network Written in Go
Best of Crypto

Best of Crypto

1654923840

Elrond App for the Ledger Nano S

Introduction

This is the official Elrond wallet app for the Ledger Nano S.

Prerequisites

Latest firmware

Before proceeding with the installation, please make sure your device is up-to-date with the latest firmware.

Connectivity

Furthermore, you need to configure your OS to enable the connectivity with the Nano S device. For example, on Linux, you have to issue the following command:

wget https://raw.githubusercontent.com/LedgerHQ/udev-rules/master/add_udev_rules.sh | sudo bash

For other platforms, please have a look on this article from ledger.com.

Python package ledgerblue

pip3 install --user --upgrade --no-cache-dir ledgerblue

Note that python3 and pip3 are required in order to install ledgerblue.

Installation

Download the latest *.hex file from our releases page. If wget is available on your machine, then:

export APP_VERSION=1.0.16

wget https://github.com/ElrondNetwork/ledger-elrond/releases/download/v${APP_VERSION}/elrond-ledger-app-v${APP_VERSION}.hex

Now that you've downloaded the app and ledgerblue package is available, let's load the app on the device:

export APP_VERSION=1.0.16

python3 -m ledgerblue.loadApp --curve ed25519 --path "44'/508'" --appFlags 0x240 --tlv --targetId 0x31100004 --targetVersion=1.6.0 --delete --appName Elrond --appVersion ${APP_VERSION} --fileName elrond-ledger-app-v${APP_VERSION}.hex --dataSize 64 --icon "010000000000ffffffffffffffffff37ecdffbeff7f7eff7eff7eff7efeff7dffb37ecffffffffffff"

To remove the app from the device, issue the following command:

python3 -m ledgerblue.deleteApp --targetId 0x31100004 --appName Elrond

ESDT tokens support

In order to perform whitelisted tokens operation, first an ESDT data providing is needed.

A concatenation between the following fields has to be sent by using INS 0x08: ticker len, ticker, id_len, id, decimals, chain_id_len, chain_id, signature

The signature is generated by signing the sha256 hash of ticker len, ticker, id_len, id, decimals, chain_id_len, chain_id with a private key managed by Elrond team.

Testing

The testApp folder contains a sample Go application to prepare Elrond transactions, which you can sign using the Ledger device. The signed transactions are then dispatched to the Elrond Proxy, in order to be processed and saved on the blockchain.

Download the latest ElrondTestApp* file from our releases page. Linux, MacOS and Windows are supported. Then execute the file while the device is connected to your computer. You will be requested to enter transaction details and then continue with the signing step.

Before running the application, you need to mark it as executable on Linux / MacOS:

chmod +x ./ElrondTestApp*

Also please note that on Windows you might receive the Unknown publisher warning from the UAC facility when you first run the testApp.

Development environment: building and installing

To build locally, you must first clone this repository, then set up the development environment:

$ source prepare-devenv s

This could take a while. Then, load the app as follows:

$ make load

To remove the app from the device, run:

$ make delete

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/ledger-elrond
License: Apache-2.0 license

#elrond  #blockchain  #smartcontract 

Elrond App for the Ledger Nano S
Best of Crypto

Best of Crypto

1654916520

Elrond C# SDK for interacting with Elrond Network & Smart Contracts

elrond-sdk-erdcsharp

Elrond C# SDK for interacting with the Elrond Network (in general) and Smart Contracts (in particular).

This SDK depends on :

How to install ?

Elronford SDK for .NET Core is delivered via nuget package, therefore it can be installed as follows:

Install-Package elrond-sdk-erdcsharp

Main Features

  • Transaction construction, signing, broadcasting and querying.
  • Smart Contracts deployment and interaction (execution and querying).
  • Wallet creation, derive wallet from mnemonic
  • Query values stored within Smart Contracts.

Documentation

The documentation and guides can be found at Read the docs.

Change Log

All notable changes will be documented in this file.

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-sdk-erdcsharp
License: GPL-3.0 license

#elrond  #blockchain  #smartcontract #csharp 

Elrond C# SDK for interacting with Elrond Network & Smart Contracts
Best of Crypto

Best of Crypto

1654912680

Dapp Core Component on The Elrond Network

dapp-core-components

A library that holds the core logic of a dapp on the Elrond Network with an example to get started easily

If you need only the dapp-core basic logic, without the additional UI, consider using the stripped down version at @elrondnetwork/dapp-core

Installation

The library can be installed via npm or yarn.

npm install @elrondnetwork/dapp-core-components

or

yarn add @elrondnetwork/dapp-core-components

Usage

dapp-core-components aims to abstract and simplify the process of interacting with users' wallets and with the Elrond Network, allowing developers to easily get started with a new application or integrate dapp-core-components into an existing application.

This library covers two main areas: User Identity and Transactions. The API for interacting with library's logic is exposed via hooks and methods that can be called for logging in the user, getting the status of the user or sending transactions.

However, to simplify usage even further, the library also comes with a default UI that already uses these hooks and methods under the hood. These UI elements can be easily customized with custom css classes.

The default UI is exposed via the DappUI object.

import { DappUI } from "@elrondnetwork/dapp-core-components";

More on this below.

Prerequisites

There are a couple of requirements that need to be met for the application to work properly.

React

React

This library was built for applications that use React, it might not be suitable for usage with other libraries or frameworks.

DappProvider

DappProvider

You need to wrap your application with the DappProvider component, which is exported by the library, as we need to create a global Context to be able to manipulate the data.

  • import the Provider:

import { DappProvider } from "@elrondnetwork/dapp-core-components";

  • Wrap your application with this Provider.

<DappProvider networkConfig={{ network, walletConnectBridge, walletConnectDeepLink }}>

As you might have noticed, the DappProvider accepts a networkConfig object with a couple of keys. This allows using different APIs and different connection providers.

  • walletConnectBridge (optional) is a string that is used to establish the connection to walletConnect library.
  • walletConnectDeepLink (optional) is a string that will create a deeplink for an application that is used on a mobile phone, instead of generating the login QR code.
  • network is a required configuration file that contains the following information about the environment of the application:
{
  id: string;
  egldLabel: string;
  name: string;
  walletAddress: string;
  apiAddress: string;
  gatewayAddress: string;
  explorerAddress: string;
}

UI Wrappers

UI Wrappers

The library exposes a couple of Components that are connected to the redux store and are used to display various elements when something happens inside the app:

TransactionsToastList will display new transactions in nice toasts at the bottom of the screen. This component is fully customizable. ``` import {DappUI} from "@elrondnetwork/dapp-core-components";




- `SignTransactionsModals` will show a modal when a new transaction is submitted, prompting the user to verify and sign it.

import {DappUI} from "@elrondnetwork/dapp-core-components";

``` `NotificationModal` Will show a modal to the user with various warnings and errors.

  import {DappUI} from "@elrondnetwork/dapp-core-components";

<App>
  <DappUI.NotificationModal />
  <Content/>
</App>
  • DappCoreUIWrapper is a wrapper that needs to be wrapped around the whole tree to namespace the styles inside dapp-core-components Components.
  import {DappCoreUIWrapper} from "@elrondnetwork/dapp-core-components";

<App>
  <DappCoreUIWrapper>
  <Content/>
  </DappCoreUIWrapper>
</App>

User Identity

dapp-core-components makes logging in and persisting user's session easy and hassle-free. The library exposes two ways in which a user can be logged in:

Login UI

Login UI

There are a couple of very handy React components that can be used to login the user and protect certain routes if the user is not logged in.

Under the DappUI object mentioned above, you can find 4 buttons (one for each provider) which abstract away all the logic of loggin in the user and render the default UI. These buttons can be easily customized with a custom css class. The exported buttons are:

  • DappUI.ExtensionLoginButton
  • DappUI.WalletConnectLoginButton
  • DappUI.LedgerLoginButton
  • DappUI.WebWalletLoginButton

example:

<DappUI.ExtensionLoginButton callbackRoute="/dashboard" buttonClassName="extension-login" loginButtonText="Extension login" />

They can also be used with children

<DappUI.ExtensionLoginButton callbackRoute="/dashboard" buttonClassName="extension-login" loginButtonText="Extension login">
  <>
    <icon/>
    <p>Login text</p>
  <>
</DappUI.ExtensionLoginButton

Also, for a quicker setup, the DappUI object exports an DappUI.UnlockPage component, which contains all 4 buttons.

Another handly component is DappUI.AuthenticatedRoutesWrapper, which can be used to protect certain routes and redirect the user to login page if the user is not authenticated.

Import from dapp-core-components:

import { AuthenticatedRoutesWrapper} from "@elrondnetwork/dapp-core-components";

Use with routes:

<AuthenticatedRoutesWrapper
          routes={routes}
          unlockRoute={routeNames.unlock}
        >
          {appContent}
        </AuthenticatedRoutesWrapper>

routes should be an array with objects with a signature similar to this:

{
    path: "/dashboard",
    title: "Dashboard",
    component: Dashboard,
    authenticatedRoute: true,
  }

The important parts that makes this component work are the flag authenticatedRoute: true and the key path, which means that this route should be accessible only to authenticated users.

Login hooks

Login hooks

If needed, the Login UI can be bypassed using a custom UI, and opt in for the login hooks, which expose a trigger function and the login data, ready to be rendered.

These hooks are exposed by the loginServices object, which can be imported from dapp-core-components:

import {loginServices} from @elrondnetwork/dapp-core-components

There are 4 available hooks:

  • useExtensionLogin
  • useWalletConnectLogin
  • useLedgerLogin
  • useWebWalletLogin

All hooks have the same respose signature:

return type is as follows:

const [triggerFunction, genericLoginReturnType, customLoginReturnType] = useLoginHook({
    callbackRoute,
    logoutRoute
  });
  • initiateLogin is a function that needs to be called for the login flow to be initiated;
  • genericLoginReturnType is an object that is exactly the same for all hooks:
{
  error: string,
  isFailed: boolean,
  isLoading: boolean,
  isLoggedIn: boolean
}

customLoginReturnType is an object that is custom for each hook and returns specific data for that login:

null for useExtensionLogin;

null for useWebWalletConnect;

{ uriDeepLink: string, qrCodeSvg: svgElement } for useWalletConnectLogin;

  •  
{
  accounts: string[];
  showAddressList: boolean;
  startIndex: number;
  selectedAddress: SelectedAddress | null;
  onGoToPrevPage: () => void;
  onGoToNextPage: () => void;
  onSelectAddress: (address: SelectedAddress | null) => void;
  onConfirmSelectedAddress: () => void;
}

for useLedgerLogin;

Reading User State

Reading User State

Once logged in, the user's session is persisted and can be read and deleted via a couple of handy functions.

For logging out, the library exposes a simple function called logout, which can be called to clear the user data.

There are 2 ways of reading the user current state: hooks (to be used inside components and for reacting to changes in the data) and simple functions (for reading data outside of React components or inside handlers).

  • hooks: useGetLoginInfo, useGetAccountInfo, useGetNetworkConfig;
  • functions: getAccount, getAccountBalance, getAccountShard, getAddress, getIsLoggedIn;

Transactions

The dapp-core-components library exposes a straight-forward way of sending transactions and tracking their status, with a couple of handy UI components;

Sending Transactions

Sending Transactions

The API for sending transactions is a function called sendTransactions:

import { sendTransactions } from "@elrondnetwork/dapp-core-components";

It can be used to send a transaction with minimum information:

const { sessionId, error } = await sendTransactions({
    transactions: [
        {
          value: '1000000000000000000',
          data: 'ping',
          receiver: contractAddress
        },
      ],
    });

It returns a Promise that will be fulfilled with {error?: string; sessionId: string | null;}

sessionId is the transaction's batch id which can be used to track a transaction's status and react to it.

Tracking a transaction

Tracking a transaction

The library exposes a hook called useTrackTransactionStatus under the object transactionServices.

import {transactionServices} from @elrondnetwork/dapp-core-components;

const transactionStatus = transactionServices.useTrackTransactionStatus({
  transactionId: sessionId,
  onSuccess,
  onFailed,
  onCancelled
});

transactionStatus has the following information about the transaction:

{
  isPending,
  isSuccessful,
  isFailed,
  isCancelled,
  errorMessage,
  status,
  transactions
}

It's safe to pass in null as a sessionId, so if the transaction wasn't yet sent, the hook will just return an empty object.

Also, one can use the hook useGetPendingTransactions to get a list of all pending transactions.

Transaction Toasts UI

Transaction Toasts UI

dapp-core-components also exposes a toast component for tracking transactions that uses the above mentioned hooks and displays toasts with transactions statuses.

The toasts list is exposed via DappUI.TransactionsToastList component and can be used just by rendering it inside the application.

<App>
  <Router/>
  <DappUI.TransactionsToastList />
</App>

Important: This has to be inside the <DappProvider/> children.

Roadmap

See the open issues for a list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.

One can contribute by creating pull requests, or by opening issues for discovered bugs or desired features.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/dapp-core-components
License:

#elrond  #blockchain  #smartcontract #dapp #typescript 

Dapp Core Component on The Elrond Network
Best of Crypto

Best of Crypto

1654905360

Dapp Utils React Package for Elrond Network

dapp-utils react package

This module contains a collection of react components and helper functions commonly used when developing DApps.

Installation:

npm i @elrondnetwork/dapp-utils

Components

Denominate Displays a denominated value along with its label

Usage:

import { UI } from  "@elrondnetwork/dapp-utils";
const yourComponent = () => {
	
	return (
	<>
		...
		<UI.Denominate ...params />
	</>
	)
}

Params:

NametyperequireddefaultDescription
valuestringyes-Value that needs to be denominated
showLastNonZeroDecimalbooleannofalseShows the last non zero decimal
showLabelbooleannotrueShows the default label
erdLabelstringnoEGLDOverrides the default label
tokenstringno-Overrides the erdLabel, used for ESDT Tokens
decimalsnumberno4Specifies how many decimals should be displayed
denominationnumberno18Specifies how much to denominate by

Validations

stringIsFloat Checks if a string is float.

Usage:

import { validation } from  "@elrondnetwork/dapp-utils";

validation.stringIsFloat("100.3423");

Params:

NametyperequireddefaultDescription
amountstringyes-Amount that needs to be checked

Returns boolean

stringIsInteger Checks if a string is integer

Usage:

import { validation } from  "@elrondnetwork/dapp-utils";

validation.stringIsInteger("100");

Params:

NametyperequireddefaultDescription
amountstringyes-Amount that needs to be checked

Returns boolean

Operations

nominate(input, customDenomination) Nominates a provided value

Usage:

import { operations } from  "@elrondnetwork/dapp-utils";

operations.nominate("10");

Params:

NametyperequireddefaultDescription
inputstringyes-Value that needs to be nominated
customDenominationnumberno18Custom denomination value

Returns string

denominate(input, denomination, decimals, showLastNonZeroDecimals) Denominates a provided value

Usage:

import { operations } from  "@elrondnetwork/dapp-utils";

operations.denominate({input: "10000000000000000000000", decimals: 4});

Params:

NametyperequireddefaultDescription
inputstringyes-Value that needs to be denominated
denominationnumberyes-Denomination value
decimalsnumberyes-Specifies how many decimals should be displayed
showLastNonZeroDecimalsbooleannofalseShows the last non zero decimal
addCommasbooleannotrueFormats the number with commas

Returns string

getTokenFromData(data) Nominates a provided value

Usage:

import { operations } from  "@elrondnetwork/dapp-utils";

operations.getTokenFromData("ESDTTransfer@425553442d663361616361@0de0b6b3a7640000");

Params:

NametyperequireddefaultDescription
datastringyes-string representing operation and Hex ecoded values of token and amount

Returns data { tokenId: string; nominatedTokenAmount: string }

Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/dapp-utils
License:

#elrond  #blockchain  #smartcontract 

Dapp Utils React Package for Elrond Network