1655004660
BUSD stablecoin smart contract Elrond implementation and tests
In short:
pip3 install --user --upgrade --no-cache-dir erdpy
More details here: https://github.com/ElrondNetwork/erdpy/blob/master/README.md
erdpy build .
All tests:
erdpy --verbose test --directory="tests"
To debug individual tests (example):
erdpy --verbose test --directory="tests/init/create.scen.json"
erdpy --verbose deploy . --pem="./alice.pem" --proxy="https://wallet-api.elrond.com"
erdpy --verbose query erd1qqqqqqqqqqqqqpgq9sp6f9m9zzhepfl0e02cy9m9tnztry2kx2fsf96449 --function="name" --proxy="https://wallet-api.elrond.com"
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
1654997280
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.
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).
For API examples, please see client.http as well.
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": {
...
}
}
}
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:
1654989900
Smart contract used for distribution of ESDT tokens, in particular for MEX.
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.
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.
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.
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
1654982580
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).
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):
loan_amount
of loan_token_id
function
at given address
with given gas_limit
and arguments
acceptPayback
endpoint. The contract will only accept funds while a flash loan is ongoing and will only accept loan_token_id
tokens.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
].
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
.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
1654975200
REST API facade facilitating the interactions with the Elrond blockchain.
npm install
in the project directoryconfig.js
.env
file in project root and specify the config informationCONFIG=mainnet/testnet/devnet
PrivateElastic=true/false
PrivateElasticUsername="username"
PrivateElasticPassword="password"
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
1654967880
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.
Before installing/running be sure to add a valid owner.pem
to the script PEM folder.
PEM
inside the scripts folderowner.pem
file inside the previously created folder[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;
POST /write
endpointSends 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
}
POST /price-job
endpointStarts 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
}
POST /ethgas/denominate
endpointFetched 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:
1654960500
Elrond C++ Command Line Tools and SDK for interacting with the Elrond Network (in general) and Smart Contracts (in particular).
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
Elrond C++ SDK CLI uses:
cmake .
cmake --build .
After building with cmake, you can use the SDK by:
#include "erdsdk.h"
cd cli
./erdcpp -h
Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-sdk-erdcpp
License: MIT license
1654953180
Nest framework TypeScript starter repository.
$ npm install
# development
$ npm run start:devnet
# watch mode
$ npm run start:devnet:watch
# production mode
$ npm run start:mainnet
# development
$ npm run start:microservice:devnet
# watch mode
$ npm run start:microservice:devnet:watch
# production mode
$ npm run start:microservice:mainnet
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
Download Details:
Author: ElrondNetwork
Source Code:
License:
1654945800
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
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).
API
Usecase | Endpoint |
---|---|
GetAccountUsecase | GET address/:bech32Address |
GetAddressBalanceUsecase | GET address/:bech32Address/balance |
GetAddressNonceUsecase | GET address/:bech32Address/nonce |
GetAddressTransactionsUsecase | GET address/:bech32Address/transactions |
GetTransactionInfoUsecase | GET transaction/:txHash |
GetTransactionStatusUsecase | GET transaction/:txHash/status |
SendTransactionUsecase | POST transaction/send |
EstimateCostOfTransactionUsecase | POST transaction/cost |
GetNetworkConfigUsecase | GET network/config |
QueryContractUsecase | POST vm-values/query |
QueryContractHexUsecase | POST vm-values/hex |
QueryContractStringUsecase | POST vm-values/string |
QueryContractIntUsecase | POST vm-values/int |
Usecase | Description |
---|---|
CallContractUsecase | Interact with a Smart Contract (execute function): equivalent to erdpy contract call |
DNS
Usecase | Description |
---|---|
RegisterDnsUsecase | Send a register transaction to the appropriate DNS contract from given user and with given name: equivalent to erdpy dns register |
GetDnsRegistrationCostUsecase | Gets the registration cost from a DNS smart contract: equivalent to erdpy dns registration-cost |
CheckUsernameUsecase | Can be useful for validating a text field before calling RegisterDnsUsecase |
// default value is ProviderUrl.DevNet
ErdSdk.setNetwork(ProviderUrl.MainNet)
// configure the OkHttpClient
ErdSdk.elrondHttpClientBuilder.apply {
addInterceptor(HttpLoggingInterceptor())
}
The SDK is not yet uploaded to a maven repository
You can build the jar from the sources by running mvn package
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
1654938420
The go implementation for the Elrond deploy
Building the repository requires Go (version 1.12 or later)
Run in %project_folder%/cmd/filegen folder the following command to build a filegen (which generates .pem and .json files used by the node):
$ 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
$ 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.
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.
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.
$ 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
$ go test ./...
Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/elrond-deploy-go
License:
1654931100
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.
git clone https://github.com/ElrondNetwork/elrond-polychain-relayer.git
cd elrond-polychain-relayer
go build -o elrond-polychain-relayer main.go
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:
1654923840
This is the official Elrond wallet app for the Ledger Nano S.
Before proceeding with the installation, please make sure your device is up-to-date with the latest firmware.
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.
ledgerblue
pip3 install --user --upgrade --no-cache-dir ledgerblue
Note that python3
and pip3
are required in order to install ledgerblue
.
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
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.
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.
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
1654916520
Elrond C# SDK for interacting with the Elrond Network (in general) and Smart Contracts (in particular).
This SDK depends on :
Elronford SDK for .NET Core is delivered via nuget package, therefore it can be installed as follows:
Install-Package elrond-sdk-erdcsharp
Main Features
The documentation and guides can be found at Read the docs.
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
1654912680
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
The library can be installed via npm or yarn.
npm install @elrondnetwork/dapp-core-components
or
yarn add @elrondnetwork/dapp-core-components
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";
There are a couple of requirements that need to be met for the application to work properly.
React
This library was built for applications that use React, it might not be suitable for usage with other libraries or frameworks.
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 { DappProvider } from "@elrondnetwork/dapp-core-components";
<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.
{
id: string;
egldLabel: string;
name: string;
walletAddress: string;
apiAddress: string;
gatewayAddress: string;
explorerAddress: string;
}
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>
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
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:
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
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:
All hooks have the same respose signature:
return type is as follows:
const [triggerFunction, genericLoginReturnType, customLoginReturnType] = useLoginHook({
callbackRoute,
logoutRoute
});
{
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
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).
useGetLoginInfo, useGetAccountInfo, useGetNetworkConfig
;getAccount, getAccountBalance, getAccountShard, getAddress, getIsLoggedIn;
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
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
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
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.
See the open issues for a list of proposed features (and known issues).
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.
git checkout -b feature/AmazingFeature
)git commit -m 'Add some AmazingFeature'
)git push origin feature/AmazingFeature
)Download Details:
Author: ElrondNetwork
Source Code: https://github.com/ElrondNetwork/dapp-core-components
License:
1654905360
This module contains a collection of react components and helper functions commonly used when developing DApps.
Installation:
npm i @elrondnetwork/dapp-utils
Denominate Displays a denominated value along with its label
Usage:
import { UI } from "@elrondnetwork/dapp-utils";
const yourComponent = () => {
return (
<>
...
<UI.Denominate ...params />
</>
)
}
Params:
Name | type | required | default | Description |
---|---|---|---|---|
value | string | yes | - | Value that needs to be denominated |
showLastNonZeroDecimal | boolean | no | false | Shows the last non zero decimal |
showLabel | boolean | no | true | Shows the default label |
erdLabel | string | no | EGLD | Overrides the default label |
token | string | no | - | Overrides the erdLabel, used for ESDT Tokens |
decimals | number | no | 4 | Specifies how many decimals should be displayed |
denomination | number | no | 18 | Specifies how much to denominate by |
stringIsFloat Checks if a string is float.
Usage:
import { validation } from "@elrondnetwork/dapp-utils";
validation.stringIsFloat("100.3423");
Params:
Name | type | required | default | Description |
---|---|---|---|---|
amount | string | yes | - | 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:
Name | type | required | default | Description |
---|---|---|---|---|
amount | string | yes | - | Amount that needs to be checked |
Returns boolean
nominate(input, customDenomination) Nominates a provided value
Usage:
import { operations } from "@elrondnetwork/dapp-utils";
operations.nominate("10");
Params:
Name | type | required | default | Description |
---|---|---|---|---|
input | string | yes | - | Value that needs to be nominated |
customDenomination | number | no | 18 | Custom 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:
Name | type | required | default | Description |
---|---|---|---|---|
input | string | yes | - | Value that needs to be denominated |
denomination | number | yes | - | Denomination value |
decimals | number | yes | - | Specifies how many decimals should be displayed |
showLastNonZeroDecimals | boolean | no | false | Shows the last non zero decimal |
addCommas | boolean | no | true | Formats 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:
Name | type | required | default | Description |
---|---|---|---|---|
data | string | yes | - | 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: