Welcome to DeFiChain Developer Documentation

V1: Metachain Framework

Developer Documentation

Learn how to build secure dApps, launch tokens or interact with the thriving ecosystem inside MetaChain Layer - an EVM-compatible layer that brings the world building of smart contracts to the UTXO environment of DeFiChain to unlock new possibilities of cross-chain interoperability.

MetaChain Layer, initiated through DFIP 2111-B, offers DeFiChain an opportunity to stretch the boundaries of what is currently possible in the world of web3 and the original DeFiChain project via it's unique 'xVM' architecture. Supporting the creation of smart contracts in a Turing complete environment for faster paced innovation.

Basic Function Overview

The transferdomain function in DeFiChain allows for the transfer of balances between DFI addresses in the DVM (DeFiChain Virtual Machine) and EVM (Ethereum Virtual Machine) domains. This function creates and submits a transaction to the local node and network.

Use Case Example

Let’s say you want to transfer DFI Tokens to the EVM module to use them with your Smart Contracts or to transfer them to any EVM address. Below is what your command would look like:

Using DeFi CLI:

defi-cli transferdomain '[
{
    "src:{
    "address":dzc6q5tPtQip27LbG9iHtXahqCzxmm6jmf",
    "amount":"1.0@DFI",
    "domain":1,
    },
    "dst":{
    "address":"0x32Be343B94f860124dC4fEe278FDCB38C102D88",
    "amount":"1.0@DFI",
    "domain":2, 
    }              

}
]'

Using CurL

curl --user rpcuser:rpcpassword --data-binary '{
        "jsonrpc":"1.0",
        "id":"curltest",
        "method":"transferdomain",
        "params":[
        [
          {
          "src:{
               "address":dzc6q5tPtQip27LbG9iHtXahqCzxmm6jmf",
               "amount":"1.0@DFI",
                "domain":1,
                },
          "dst":{
                  "address":"0x32Be343B94f860124dC4fEe278FDCB38C102D88",
                   "amount":"1.0@DFI",
                    "domain":2, 
    }              

}
        
        ]
        ]
        }' -H 'content-type: text/plain;' http:127.0.0.1:8332/

Parameters Terminology

  • src and dst objects are of the same type.

  • src stands for source (the sender of the transfer)

  • dst stands for destination (the receiver of the transfer)

Each of these objects contains the following fields:

  • address: This is either a DVM address or an EVM address, depending on the domain field.

  • amount: The amount to be transferred, in the format number@symbol. For example, 1.0@DFI means 1 DFI token.

  • domain: This field specifies the domain of the address. It can be either:

  • 1 for DVM (DeFiChain Virtual Machine)

  • 2 for EVM (Ethereum Virtual Machine)

For example, if you want to send from DVM to EVM, the src object would contain domain: 1 and the dst object would have domain: 2.

Summary

The transferdomain function is a powerful feature in DeFiChain that enables seamless transfers between the DVM and EVM domains, allowing users to interact with both DeFiChain and Ethereum ecosystems using DFI tokens.

Running a Full-Node

Running a Full Node on Metachain's Floppynet: A Comprehensive Guide

Note: Please review then code blocks can be added

Introduction

Floppynet is an ALPHA stage test network for Metachain, which means it is subject to changes, execution failures, data persistence issues, and periodic rollbacks. Despite being in its early stages, it provides a valuable environment for developers to test and experiment with Metachain features.

Step 1: Get the Source Code

1. Clone the branch of the official DeFiChain node repository:

git clone - https://github.com/defich/ain

Step 2: Compile the Node

Note: This build process is currently operational on Linux. MacOS and Windows processes are under development.

1. Ensure Docker is installed and running on your machine. Follow the official guide to install, configure, and run Docker.

2. Use the make.sh script for efficient compilation of the node:

./make.sh docker_release

This command compiles the node dependencies and the node itself inside a Docker container. The first run may take some time as it downloads necessary source code and Docker images.

Step 3: Running the Node

1. After a successful build, find the binaries in ./build/defichain-latest/bin/.

2. Run the node and connect it to Floppynet with the following command

./build/defichain-latest/bin/defid -devnet -connect=35.187.53.161 --daemon

The -connect=35.187.53.161 flag connects your local node to a public node maintained by the core developers, initiating synchronization with other nodes in Floppynet.

Step 4: Monitor Synchronization Progress

1. To see the progress of the syncing, run:

./build/defichain-latest/bin/defi-cli -devnet stop 

2. Then start the node with RUST_LOG=debug:

RUST_LOG=debug ./build/defichain-latest/bin/defid -devnet --daemon

Step 5: Connect Metamask to Floppynet

For detailed steps on how to connect Metamask to Floppynet, refer to this [guide] ( https://defich.github.io/handbook/guides/guide_floppynet_short.html ).

Conclusion

Running a full node on Metachain's Floppynet is an excellent way for developers to familiarize themselves with the Metachain environment. This guide provides a step-by-step approach to setting up a node, from source code retrieval to node synchronization and log checking.

Please Note: Floppynet is in its ALPHA stage and is subject to changes and potential data persistence issues.

For more detailed guides and information, visit the [DeFiChain Handbook](https://defich.github.io/handbook/ ).

Smart Contracts

This guide aims to help developers deploy smart contracts on MetaChain Layer. Smart contracts on MetaChain Layer function similarly to those on Ethereum and are written in Solidity. This guide will cover the requirements, methods, and tools you can use for deployment.

Deploy a smart contract

Smart contracts are written in Solidity and they function on Metachain Layer as they do on Ethereum.

To deploy a smart contract, you will need to send a Metachain Layer transaction containing your bytecode without specifying any recipients. DFI will be consumed to pay for gas fees when deploying smart contracts.

After the contract is deployed, it will be available to all users of the network. Smart contracts will also have a Metachain Layer address just like other accounts.

Requirements

  • Bytecode (compiled code) of your smart contract

  • DFI for gas costs

  • Deployment script/plugin

  • Access to a Metachain Layer node, either by running your own node or API access to a node. We currently have a temporary node operated for the community.

Example of smart contract deployment

If you are going to deploy a smart contract for the first time, you may take a look at the example given in the following link:

https://github.com/exampleMetaChain/example-deployment

The repository contains the materials to deploy a smart contract using HardHat and Truffle tools. Instructions to work with the mainnet and testnet are included

Deployment using Remix

If you want to deploy a smart contract using Remix to the Metachain Layer Changi Testnet, you just need to connect the Metamask to Changi Testnet and choose Injected Provider - Metamask in the Environment option. You can see that the network id is set to 1133 which is Metachain EVM Testnet's network id. When you deploy the smart contract, it will be deployed to the Changi Testnet.

Deploy using your favorite Ethereum Tools

  • Solidity: Solidity is an object-oriented, high-level language for implementing smart contracts.

  • Remix: IDE that’s used to write, compile, debug & deploy Solidity code in your browser.

  • Hardhat: Development environment for editing, compiling, debugging and deploying your smart contracts using the EVM.

  • Truffle: Development environment, testing framework and asset pipeline for blockchains using the EVM.

  • OpenZeppelin: OpenZeppelin Contracts helps you minimize risk by using battle-tested libraries of smart contracts for Ethereum and other blockchains.

  • thirdweb: Complete Web3 development framework that provides everything you need to connect your applications and games to decentralized networks

Quick Guide: Deploying a Smart Contract on Metachain Layer (or any EVM-compatible blockchain)

This guide is aimed at developers looking for a quick and straightforward way to deploy smart contracts. We'll use Truffle for this example, but you can adapt the steps for Hardhat or other tools.

Prerequisites

  • Node.js and npm installed

  • Truffle installed (npm install -g truffle)

  • MetaMask or another wallet set up

  • Some test ETH or FTM for gas fees

Step 1: Initialize Your Project

Create a new directory for your project and navigate into it.

mkdir MySmartContract
cd MySmartContract

Initialize a new Truffle project.

Step 2: Environment Setup

Create a .env file in your project directory.

touch .en

Add your private key to the .env file.

PRIVATE_KEY= your private key here

Step 3: Install Dependencies

Install the HDWalletProvider package.

npm install @truffle/hdwallet-provider

Step 4: Write Your Smart Contract

Create a new Solidity file under the contracts directory.

touch contracts/MyContract.sol

Write your smart contract code. For example:

Step 5: Migration Script

Create a new migration file under the migrations directory.

touch migrations/2_deploy_contract.js

Add the following code to handle the deployment.

const MyContract = artifacts.require(“HelloWorld”);
module.exports = function(deployer) {
    deployer.deploy(MyContract, “MyContract”);
    
};

Javascript

Step 6: Network Configuration

Open truffle-config.js and add your network configurations.

var HDWalletProvider = require("truffle-hdwallet-provider");
const MNEMONIC = 'YOUR WALLET KEY';

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    },
    ropsten: {
      provider: function() {
        return new HDWalletProvider(MNEMONIC, "https://ropsten.infura.io/YOUR_API_KEY")
      },
      network_id: 3,
      gas: 4000000      //make sure this gas allocation isn't over 4M, which is the max
    }
  }
};

Step 7: Compile and Deploy

Compile your smart contracts.

truffle compile

Deploy your smart contract to the testnet.

Step 8: Verify Deployment

Check the logs for the contract address and other details to confirm that the deployment was successful.

That's it! You've successfully deployed a smart contract. Always remember to test thoroughly on testnets before deploying to the mainnet.

You can find the mainnet explorer in this link:

https://meta.defiscan.live/

Unit Testing Smart Contracts

It is essential to write unit tests for your smart contracts. It is a good practice to perform unit testing before deploying your smart contracts.

Smart contract unit tests are written in Javascript.

In this tutorial, we provide two examples of unit testing using Hardhat and Truffle.

Truffle

All test files should be located in the ./test directory. Truffle will only run test files with the following file extensions: .js, .ts, .es, .es6, and .jsx, and .sol. All other files are ignored.

To run all tests, simply run:

$ truffle test

Alternatively, you can specify a path to a specific file you want to run, e.g.,

$ truffle test ./path/to/test/file.js

Note: When the truffle test process exits, its exit code is equal to the number of failing tests. If there are more than 255 failing tests, it will exit with code 255.

https://trufflesuite.com/docs/truffle/how-to/debug-test/test-your-contracts/

Create a Fixed-Cap Asset

Fixed-cap assets are fungible tokens for which the supply is determined at the time of asset creation. No additional quantities can be generated afterwards.

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Capped.sol

functions

constructor(cap)
cap()
_beforeTokenTransfer(from, to, amount)me code

General

name()
symbol()
decimals()
totalSupply()
balanceOf(account)
transfer(recipient, amount)
allowance(owner, spender)
approve(spender, amount)
transferFrom(sender, recipient, amount)
increaseAllowance(spender, addedValue)
decreaseAllowance(spender, subtractedValue)
_transfer(sender, recipient, amount)
_mint(account, amount)
_burn(account, amount)
_approve(owner, spender, amount)
_setupDecimals(decimals_)

2. Compile your code into bytecode

3. Deploy your Fixed-cap Asset by sending your code in a transaction to the Metachain network

4. Navigate to the explorer to check that your token has been created

Create a Variable-Cap Asset

functions

symbol()
decimals()
totalSupply()
balanceOf(account)
transfer(recipient, amount)
allowance(owner, spender)
approve(spender, amount)
transferFrom(sender, recipient, amount)
increaseAllowance(spender, addedValue)
decreaseAllowance(spender, subtractedValue)
_transfer(sender, recipient, amount)
_mint(account, amount)
_burn(account, amount)
_approve(owner, spender, amount)
_setupDecimals(decimals_)

Hence, ERC20 Presets (such as ERC20PresetMinterPauser) are designed using opinionated patterns to provide developers with ready to use, deployable contracts.

You could also refer to a preset

https://docs.openzeppelin.com/contracts/3.x/api/presets#ERC20PresetMinterPauser

2. Compile your code into bytecode

3. Deploy your Variable-cap Asset by sending your code in a transaction to the Fantom network

4. Navigate to the explorer to check that your token has been created

5. You can use the _mint function to create additional units of the token

Contract Verification

Smart contract verification provides transparency for users interacting with smart contracts by publishing the source code, allowing everyone to attest that it really does what it claims to do and can help reduce the possibility of malicious contracts. You can verify your smart contracts using the Metascan Explorer. The procedure is simple:

  • Navigate to the Contract tab on the explorer

  • On the contract tab select verify contract

  • Navigate to the Contract tab on the explorer

  • Copy and paste the flattened source code and enter all the build parameters exactly as they are on the published contract

  • Click submit

If successful, the code tab will now have a green checkmark, and your users will be able to verify the contents of your contract. This is a strong positive signal that your users can trust your contracts, and it is strongly recommended for all production contracts.

See for a detailed tutorial with Truffle.

Launch Your Ethereum Dapp on Metachain Layer

The purpose of this document is to help you with launching your existing Dapp on Metachain Layer. It contains a series of resources designed to help you get the basics of Metachain Layer and how it works, show how to connect to the network, how to use your existing tools and environments in developing and deploying on Metachain Layer, as well as some common pitfalls you need to consider when running your Dapp on Metachain Layer.

How to use oracles in Metachain Layer

PUBLIC PREVIEW DOCUMENT

This document is currently in public preview and may change significantly as feedback is captured from readers like you. Click the Request an update button at the top of this document or join the Community Discord to share your feedback.

Contract Security Checks

Due to the nature of distributed apps, it is very hard to fix bugs once the application is deployed. Hence, there is a need to ensure your app is running correctly and securely before deployment. Contract security reviews are done by specialized companies and services; however, they can be very expensive, which might be out of reach for single developers and startups. But, there are also automated services and programs that are free to use.

For example; https://github.com/crytic/slither by Trails of Bit as a static analyzer.

For more information about Slither; https://blog.trailofbits.com/2018/10/19/slither-a-solidity-static-analysis-framework/

A more comprehensive look into secure development practices can be found;

https://github.com/crytic/building-secure-contracts/blob/master/development-guidelines/workflow.md

DST-20 Tokens

DST-20 Tokens are a set of token standards that follows Ethereum’s ERC-20 token standards.

The ERC-20 is a popular fungible cryptocurrency token compatible with Ethereum or EVM-compatible blockchains. It serves as a digital asset that can represent anything on the blockchain, which enables flexibility for many use cases.

This preset smart contract contains a specific interface that allows it to be used as a technical standard for development. Developers can leverage the ERC-20 token and its associated token rules for an easier developer experience. Popular decentralized exchange protocols like Uniswap and SushiSwap both leverage the ERC-20 token standard as building blocks for its seamless compatibility and integration into their ecosystems.

By introducing DST-20, MetaChain Layer will empower developers to easily build and deploy on Metachain Layer just as they would on Ethereum.

Public API Endpoints

Mainnet

gRPC

protobuf

Testnet

Socials

Twitter:https://twitter.com/defichain

Discord: https://discord.gg/yMPG83yaDA

Telegram: https://t.me/defiblockchain

Last updated