Liquid Avax
This is our subscription to Avalanche developers contest. We have chosen the "How to create staking derivatives on Avalanche" subject.

Quick prensentation

What is liquid staking ?

Liquid staking is an alternative to normal staking. The advantage of liquid staking is that staked asset are not locked anymore, while still earning returns and supporting the network decentralisation.

How does it work ?

Using the interface, the user is able to stake his $AVAX and get $sAVAX in exchange at a 1:1 rate. The user can also monitor all its current stakes if the stake is not finished yet and/or not withdrew by the backend. To redeem the funds, the user will need to provide back the $sAVAX tokens against what he will get his $AVAX again with the staking rewards.

Let's present the project more in depth...

This project is composed of several components:
    1.
    Frontend
    2.
    Smart Contract
    3.
    Backend

Frontend

The frontend, or user interface is our platform called "Liquid Avax". We forked Olive Swap, a fork of Pancake Swap for the sake of simplicity. Here are a quick preview of our frontend:
Let's stake 25 $AVAX...
We can now see our current stake with informations from the smart contract.
The stake should be redeemable at the end of the stake here.

Smart Contract

The smart contract is based on ERC20 smart contracts. It handles requests made by the frontend, and emits events for the backend.

Backend

The backend is basically a nodeJS script running 24/7 waiting for an Event such as "Staked" or "StakeEnded" to be emitted from the smart contract.
When the event "Staked" is emitted, it will retrieve the staker address, the stakeID, and the amount of $AVAX staked from it. This will be used to transfer the funds from the C to P chain and stake the funds on a node for a defined amount of time.
When the event "StakeEnded" is detected, the user will be able to redeem the funds. The backend will cross chain from P to C and send the funds to the smart contract.

Tutorial

Okay, we hope that you are now full set to go through the tutorial. We will start by the smart contract.

Smart contract

We start by importing the basic ERC20 smart contract (this is a common standart for creating tokens, more details here :) and the Ownable one (this is a contract wich permit to restrain function to an owner adress).
1
pragma solidity ^0.8.0;
2
​
3
import "ERC20.sol";
4
import "Ownable.sol";
Copied!
Then we need to write 4 main functions :
    One when a user deposit AVAX and mint sAVAX
    One to permit the backend to withdraw this funds
    One for the backend to put back fund + rewards on the contract
    And one to permit the user to get their funds back in exchange of sAVAX
In addition for clarity and reliability we will also need :
    One function to make the P-Chain tx viewable on C-chain (updated by the backend)
    One view function to view all stakes by an user
    One function to update some variables (as minimum staking time etc when future gouvernance changes it)
We will also need some variables to stock the staking informations : We willuse a struct to store all informations relative to a stake :
1
struct Stake{
2
address payable user;
3
uint256 stakeId ;
4
uint256 amount ;
5
uint256 finalAmount ;
6
uint256 endingTimestamp ;
7
bool withdraw ;
8
bool updated ;
9
bool redeemed ;
10
string PChainTx ;
11
}
Copied!
and we will use a mapping to link an id to a stake and a int containing the number of stake:
1
uint256 public stakeNumber = 0;
2
mapping (uint256 => Stake) public stakeds ;
Copied!
To make frontend call easier we will also link an adress with all his stakes ids :
1
mapping(address=>uint256[]) public currentStakedByUser ;
Copied!
and some variables so we can change this values later in case of gouvernance votes :
1
uint256 public secondsInFuture = 14*24*3600 ;
2
uint256 public maxSecondsInFuture = 365*24*3600;
3
uint256 public secondsBeforeAllRedeem = 60*24*3600 ;
4
uint256 public minimumValue = 25 ether ;
Copied!
Now let's begin with our first fonction to allow users deposit a stake. This will just need 2 variables : the staking time (represented by a timestamp of the stake end) and the amount which is provided via msg.value in solidity We just need some checking (the staking time should be greater than 2 weeks and smaller than 1 year / the staking amount should be larger than 25 AVAX)
We create a new Stake element and we populate his attribute with known ones, we map it to retrieve it with his id, we add it to the list of stakes by user and we can now mint some fresh sAVAX to the user adress and increase the number of stakes. (we also emit an event which we will explain later)
1
function stake(uint256 timestamp) public payable {
2
require(timestamp > block.timestamp + secondsInFuture, "Ending period not enough in the future");
3
require(msg.value >= minimumValue, "Not enough avax for delegation");
4
Stake storage s = stakeds[stakeNumber];
5
s.stakeId = stakeNumber;
6
s.amount = msg.value ;
7
s.endingTimestamp = timestamp ;
8
s.user = payable(msg.sender) ;
9
currentStakedByUser[msg.sender].push(stakeNumber);
10
_mint(msg.sender, msg.value);
11
​
12
emit Staked(s.user, s.stakeId, msg.value);
13
stakeNumber++;
14
}
Copied!
Now let's code the function allowing the backend to withdraw the funds in order to stake it :
1
function withdraw(uint256 stakeId) public onlyOwner {
2
Stake storage s = stakeds[stakeId] ;
3
require(s.withdraw == false, "Already Withdrawn");
4
require(payable(msg.sender).send(s.amount), "Send failed");
5
s.withdraw = true ;
6
}
Copied!
This function is very simple, it requires the caller to be the owner (aka backend private key), then it checks if the backend did not alreayd withdrawn funds for that stake and then send them to the back end adress
Now let's code the function which just update the PChainTx attribute of a stake :
1
function setPChainTx(uint256 stakeId, string calldata h) public onlyOwner {
2
Stake storage s = stakeds[stakeId] ;
3
s.PChainTx = h ;
4
}
Copied!
again very simple we just need to require it to be called by the owner then we update the PChainTx attribute.
Now we will code the function called by the BackEnd to returns funds after the staking period ended :
1
function updateStake(uint256 stakeId, uint256 finalAmount) public payable onlyOwner {
2
require(msg.value >= finalAmount, "Not enough avax sent");
3
Stake storage s = stakeds[stakeId];
4
require(finalAmount >= s.amount, "final amount must be greater than deposited amount");
5
s.finalAmount = finalAmount;
6
s.updated = true ;
7
​
8
emit StakeEnded(stakeId, finalAmount);
9
}
Copied!
Once again only callable by the owner it requires to sent as much or more than the amount deposited by the user, the back end provide a finalAMount value representing the amount deposited + rewards earned while staking. We update the staking struct and emit an event (once again we will see that later)
Now we will call the function for a user to get his funds back :
1
function redeem(uint256 stakeId) public {
2
Stake storage s = stakeds[stakeId] ;
3
require(s.endingTimestamp > block.timestamp, "Staking period not ended");
4
require(s.updated == true, "Stake not yet transferred on C-chain");
5
require(s.redeemed == false, "Stake already redemeed");
6
require(balanceOf(msg.sender) >= s.amount, "Not enough sAVAX on address");
7
require(s.user == msg.sender || s.endingTimestamp > block.timestamp + secondsBeforeAllRedeem, "Not stake owner");
8
s.redeemed = true ;
9
_burn(msg.sender, s.amount);
10
require(payable(msg.sender).send(s.finalAmount), "Send failed");
11
}
Copied!
This one is a bit more complex, it can be called by anyone so we need to check if the person calling it is the person who deposited the stake (not that we introduced a possibility for anyone to call this function after a serious delay (like 2 months) in case someone forget / lost his account), we also need to check if the staking period as ended and if the backend already sent funds back from P-Chain and most important we need to check if he has enough sAVAX to burn on his address.
When we checked all we can now burn his sAVAX and send back the finalAmount of AVAX to his address.
We also need to remove the stake id from his active stake
1
uint256 index;
2
for (uint i=0; i<currentStakedByUser[msg.sender].length; i++){
3
if (currentStakedByUser[msg.sender][i] == stakeId) {
4
index = i ;
5
break;
6
}
7
}
8
currentStakedByUser[msg.sender][index] = currentStakedByUser[msg.sender][currentStakedByUser[msg.sender].length - 1];
9
delete currentStakedByUser[msg.sender][currentStakedByUser[msg.sender].length - 1];
10
currentStakedByUser[msg.sender].pop();
11
​
12
emit Redeem(stakeId, s.finalAmount);
Copied!
We do it by looping trough all of his current stakes and swapping the last one with the one we want to remove to finally popping the last element (weird solidity way of removing an element from a list)
Finally we code the functions allowing to updates gouvernance driven variables :
1
function updateVariables(uint256 secondsF, uint256 maxSecondsF, uint256 secondsAll, uint256 minimum) public onlyOwner {
2
maxSecondsInFuture = maxSecondsF ;
3
secondsInFuture = secondsF ;
4
secondsBeforeAllRedeem = secondsAll ;
5
minimumValue = minimum ;
6
}
Copied!
which simply updates all this variables at once.
Now the last function is simply a view function (not doing anything on the blockchain) :
1
function stakeByUser(address user) public view returns(uint256[] memory toto){
2
return currentStakedByUser[user];
3
}
Copied!
which allow to see all the current stakes by an address
We're almost done let's see the whole file :
1
pragma solidity ^0.8.0;
2
​
3
import "ERC20.sol";
4
import "Ownable.sol";
5
​
6
contract stakedAVAX is ERC20, Ownable {
7
​
8
uint256 public stakeNumber = 0;
9
mapping(address=>uint256[]) public currentStakedByUser ;
10
struct Stake{
11
address payable user;
12
uint256 stakeId ;
13
uint256 amount ;
14
uint256 finalAmount ;
15
uint256 endingTimestamp ;
16
bool withdraw ;
17
bool updated ;
18
bool redeemed ;
19
string PChainTx ;
20
}
21
mapping (uint256 => Stake) public stakeds ;
22
uint256 public secondsInFuture = 14*24*3600 ;
23
uint256 public maxSecondsInFuture = 365*24*3600;
24
uint256 public secondsBeforeAllRedeem = 60*24*3600 ;
25
uint256 public minimumValue = 25 ether ;
26
​
27
constructor() ERC20("stakedAVAX", "sAVAX") {
28
​
29
}
30
​
31
function stakeByUser(address user) public view returns(uint256[] memory toto){
32
return currentStakedByUser[user];
33
}
34
​
35
function stake(uint256 timestamp) public payable {
36
require(timestamp > block.timestamp + secondsInFuture, "Ending period not enough in the future");
37
require(msg.value >= minimumValue, "Not enough avax for delegation");
38
Stake storage s = stakeds[stakeNumber];
39
s.stakeId = stakeNumber;
40
s.amount = msg.value ;
41
s.endingTimestamp = timestamp ;
42
s.user = payable(msg.sender) ;
43
currentStakedByUser[msg.sender].push(stakeNumber);
44
_mint(msg.sender, msg.value);
45
​
46
emit Staked(s.user, s.stakeId, msg.value);
47
stakeNumber++;
48
}
49
​
50
function updateStake(uint256 stakeId, uint256 finalAmount) public payable onlyOwner {
51
require(msg.value >= finalAmount, "Not enough avax sent");
52
Stake storage s = stakeds[stakeId];
53
require(finalAmount >= s.amount, "final amount must be greater than deposited amount");
54
s.finalAmount = finalAmount;
55
s.updated = true ;
56
​
57
emit StakeEnded(stakeId, finalAmount);
58
}
59
​
60
function redeem(uint256 stakeId) public {
61
Stake storage s = stakeds[stakeId] ;
62
require(s.endingTimestamp > block.timestamp, "Staking period not ended");
63
require(s.updated == true, "Stake not yet transferred on C-chain");
64
require(s.redeemed == false, "Stake already redemeed");
65
require(balanceOf(msg.sender) >= s.amount, "Not enough sAVAX on address");
66
require(s.user == msg.sender || s.endingTimestamp > block.timestamp + secondsBeforeAllRedeem, "Not stake owner");
67
s.redeemed = true ;
68
_burn(msg.sender, s.amount);
69
require(payable(msg.sender).send(s.finalAmount), "Send failed");
70
​
71
uint256 index;
72
for (uint i=0; i<currentStakedByUser[msg.sender].length; i++){
73
if (currentStakedByUser[msg.sender][i] == stakeId) {
74
index = i ;
75
break;
76
}
77
}
78
currentStakedByUser[msg.sender][index] = currentStakedByUser[msg.sender][currentStakedByUser[msg.sender].length - 1];
79
delete currentStakedByUser[msg.sender][currentStakedByUser[msg.sender].length - 1];
80
currentStakedByUser[msg.sender].pop();
81
​
82
emit Redeem(stakeId, s.finalAmount);
83
}
84
​
85
function withdraw(uint256 stakeId) public onlyOwner {
86
Stake storage s = stakeds[stakeId] ;
87
require(s.withdraw == false, "Already Withdrawn");
88
require(payable(msg.sender).send(s.amount), "Send failed");
89
s.withdraw = true ;
90
​
91
}
92
​
93
function setPChainTx(uint256 stakeId, string calldata h) public onlyOwner {
94
Stake storage s = stakeds[stakeId] ;
95
s.PChainTx = h ;
96
}
97
​
98
function updateVariables(uint256 secondsF, uint256 maxSecondsF, uint256 secondsAll, uint256 minimum) public onlyOwner {
99
maxSecondsInFuture = maxSecondsF ;
100
secondsInFuture = secondsF ;
101
secondsBeforeAllRedeem = secondsAll ;
102
minimumValue = minimum ;
103
}
104
​
105
event Staked(address indexed user, uint256 stakeId, uint256 value);
106
​
107
event StakeEnded(uint256 stakeId, uint256 finalAmount);
108
​
109
event Redeem(uint256 stakeId, uint256 finalAmount);
110
}
Copied!
I simply added the constructor function calling the constructor from the ERC20 contract which defines the name and the symbol of our sAVAX token and the events which simply works like onchain logs, so it's easier for people building on top of project to retrieve when this action happened etc.
Now we can "upload" our SC onchain via remix by simply putting all three files in our directory and click deploy. (Tutorial)
Additionnaly, store the ABI of the contract in a file called "abi.json". This will be used to use the smart contract functions later.

Backend

Now that the smart contract is ready to go, let's prepare the backend in consequence!
I you want to use github, create a repository, clone it, and enable "VCS" if you want to keep track on your work. Otherwise, just create a directory that you will open in your IDE.
Now, we will setup a node development environment.
First, check if node is installed on your machine. To verify this, run
1
node -v
Copied!
If the output looks like this:
1
v14.16.0
Copied!
You don't need to follow the installation steps.
If not, please install node v14.16.0 or earlier.

Windows / macOS

    1.
    Go to this link: https://nodejs.org/en/​
    2.
    Click on xx.xx.x LTS recommended for most users
    3.
    Follow the procedure described after running the downloaded file

Ubuntu 20.4

1
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
Copied!
Please also verify that npm is properly installed, it should be bundled with node:
1
npm -v
Copied!
If the output is something that is similar to this:
1
7.17.0
Copied!
You're ready!
Start by creating an Avalanche wallet here: https://wallet.avax.network/ by clicking on "Create new wallet", and "Generate key phrase". After that you accessed to your wallet, head on to "Manage keys", and "View C Chain private key".
Make sure to never share this private key. Anyone can access your wallet using it.
Copy and paste it in a ".json" file. Let's call it "privateData.json". If you plan to publish to your repo, create a .gitignore containing all the private stuff.
1
{
2
"privateKey": "D0N075H4r37H15704NY0N3"
3
}
Copied!
Create a new file, we can call it backend.js .
Now, let's initiate the NodeJS development environment.
1
npm init
Copied!
Follow the prompt.
As we will import packages as ES6 modules, add this in the package.json :
1
"type": "module",
Copied!
Now, you can copy/paste the code skeleton in the .js file
1
// This script will be used to do the cross-chain transfer of the owner wallet from C to P chain and stake them
2
// to the user-chosen node.
3
​
4
import fs from "fs";
5
import { Avalanche, BinTools, BN, Buffer } from "avalanche";
6
import Web3 from "web3";
7
​
8
let xChain, xKeyChain, xChainAddressString;
9
let cChain, cKeyChain, cChainAddressString;
10
let pChain, pKeyChain, pChainAddressString;
11
​
12
let xChainBlockchainID, cChainBlockchainID, pChainBlockchainID;
13
​
14
let web3;
15
​
16
let contractAbi;
17
​
18
let masterAddress = "0x7bD7A7D2Ba70db40740780828b236F9246BB7F78";
19
let privateKey = JSON.parse(await fs.readFileSync("./data.json")).privateKey;
20
​
21
let utxoset;
22
​
23
const FOURTHEEN_DAYS = 60*60*24*14;
24
const FULL_YEAR = 60*60*24*365;
25
​
26
async function waitForStaked() {
27
​
28
}
29
​
30
async function stakeToNode(stakeAmount, stakeId, locktime, sender, txHash) {
31
32
}
33
​
34
async function CtoP(amountWithDecimals, stakeId, endingTimestamp, sender, txHash) { //a C --> P cross-chain transfer doesn't exists, but C --> X, X --> P does.
35
36
}
37
​
38
let binTools = BinTools.getInstance();
39
​
40
let privateKey;
41
​
42
async function importKeys() {
43
44
}
45
​
46
let transactionStatus;
47
​
48
async function waitForStatusX(transactionId) {
49
transactionStatus = await xChain.getTxStatus(transactionId);
50
return transactionStatus;
51
}
52
​
53
async function waitForStatusP(transactionId) {
54
transactionStatus = (await pChain.getTxStatus(transactionId)).status;
55
return transactionStatus;
56
}
57
​
58
async function waitForStatusC(transactionId) {
59
transactionStatus = await cChain.getAtomicTxStatus(transactionId);
60
return transactionStatus;
61
}
62
​
63
async function pollTransaction(func, transactionID, resolve, reject) {
64
transactionStatus = await func(transactionID);
65
if (transactionStatus === "Rejected") {
66
reject(transactionStatus);
67
}
68
if (transactionStatus !== "Accepted") {
69
setTimeout(pollTransaction, 100, func, transactionID, resolve, reject);
70
} else {
71
resolve(transactionStatus);
72
}
73
}
74
​
75
let xAvaxAssetId, cAvaxAssetId, pAvaxAssetId;
76
let xFees, cFees, pFees;
77
​
78
let avalancheInstance;
79
​
80
async function getInformations() {
81
​
82
}
83
​
84
async function setup() {
85
await getInformations();
86
await importKeys();
87
88
cChainAddressString = cKeyChain.getAddressStrings();
89
pChainAddressString = pKeyChain.getAddressStrings();
90
}
91
​
92
async function main() {
93
await setup();
94
web3 = new Web3(`wss://api.avax-test.network/ext/bc/C/ws`)
95
contractAbi = JSON.parse(await fs.readFileSync("./abi.json"))
96
await waitForStaked();
97
}
98
​
99
main().catch((e) => {
100
console.log("We got an error! " + e);
101
})
Copied!
Notice the X-Chain, C-Chain, P-Chain in the code ?
The Avalanche network operates 3 chains.
    The X-Chain, or eXchange chain is the chain that is implementing the AVM (Avalanche virtual machine) with the Avalanche consensus. It is usually used to create, exchange assets.
    The C-Chain, or Contract chain is an instance of the EVM (Ethereum virtual machine) that is able to run smart contracts.
    The P-Chain, or Platform chain is implementing the snowman consensus, like the C-chain. It can be used to add a validator node (A node that validates transactions on the network to keep it secure), a delegator (an actor staking his assets on validator nodes to help securise the network, while earning returns), create custom chains, ...
You may have noticed that we imported some packages at the top of the code. Here is how to install a package and store it in the package.json:
1
npm install <package>
Copied!
And this how to install AvalancheJS for instance:
1
npm install avalanche
Copied!
Do that for each used package at the top of the code.
The "fs" package is used to manipulate files. In this case, it is our solution to not hard code the private key and keep it safe. But it is also used to instanciate the sAVAX contract by providing its address and ABI (the ABI is a .json file).
AvalancheJS is the Javascript library from Ava labs to interact with an Avalanche node. You can find their repository here with relevant code examples. https://github.com/ava-labs/avalanchejs​
The "web3" package will be used to interact with our smart contract, and to listen to the event emitted by this last one.
​
Let's start by gathering informations that will be needed in the future. The protocol that we will be using here for our web3 constructor is websocket, because http is not supported when it comes to subscribe to events.
1
async function getInformations() {
2
const ip = "localhost";
3
const port = 9650;
4
const protocol = "http";
5
const networkID = 5;
6
avalancheInstance = new Avalanche(ip, port, protocol, networkID);
7
8
xChain = avalancheInstance.XChain();
9
xKeyChain = xChain.keyChain();
10
xChainBlockchainID = xChain.getBlockchainID();
11
12
cChain = avalancheInstance.CChain();
13
cKeyChain = cChain.keyChain();
14
cChainBlockchainID = cChain.getBlockchainID();
15
cChainAddress = cKeyChain.getAddressStrings();
16
17
pChain = avalancheInstance.PChain();
18
pKeyChain = pChain.keyChain();
19
pChainBlockchainID = pChain.getBlockchainID();
20
pChainAddress = pKeyChain.getAddressStrings();
21
22
xAvaxAssetId = binTools.cb58Encode((await xChain.getAssetDescription("AVAX")).assetID);
23
cAvaxAssetId = binTools.cb58Encode((await cChain.getAssetDescription("AVAX")).assetID);
24
25
const web3Protocol = "wss";
26
const web3Path = '/ext/bc/C/ws';
27
28
web3 = new Web3(`${web3Protocol}://api.avax-test.network${web3Path}`);
29
30
contractAbi = JSON.parse(await fs.readFileSync("./sAvaxABI.json"))
31
}
Copied!
Now, we will be importing the private key in order to be able to issue transactions, and storing the C-Chain and P-Chain addresses for later. We are getting the private key from our file and converting it to buffer for the C-chain. Note that for the X and P-Chain, we need to derivate it to CB58 format.
1
async function importKeys() {
2
let buffer = Buffer.from(privateKey, 'hex')
3
let CB58Encoded = `PrivateKey-${binTools.cb58Encode(buffer)}`
4
xKeyChain.importKey(CB58Encoded);
5
cKeyChain.importKey(buffer);
6
pKeyChain.importKey(CB58Encoded);
7
8
cChainAddress = cKeyChain.getAddressStrings();
9
pChainAddress = pKeyChain.getAddressStrings();
10
}
Copied!
So, we are now ready to listen to events emitted by the smart contract. The event we are currently interested in is the "Staked" event. It is triggered everytime someone stakes his assets, and will provide some key informations to use later...
1
async function waitForStaked() {
2
let stakingContract = new web3.eth.Contract(contractAbi, "0x5bD27eF83d57915FC3eE7feB2FebEB9c69d52B04");
3
let stakedEvent = stakingContract.events.Staked();
4
await web3.eth.subscribe('logs', {
5
address: stakedEvent.arguments[0].address,
6
topics: stakedEvent.arguments[0].topics,
7
}, async function (error, logs) {
8
if (!error) {
9
console.log("New stake")
10
let dataHex = logs.data.substring(2);
11
let id = parseInt(dataHex.substring(0, 64), 16);
12
let amountWithDecimals = parseInt(dataHex.substring(64), 16);
13
14
web3.eth.defaultAccount = masterAddress
15
let data = stakingContract.methods.withdraw(id).encodeABI();
16
let nonce = await web3.eth.getTransactionCount(masterAddress, "pending");
17
let tx = {from:masterAddress, to:"0x5bD27eF83d57915FC3eE7feB2FebEB9c69d52B04", data:data, gasPrice:225*10**9, gas:2100000, nonce:nonce}
18
let stx = await web3.eth.accounts.signTransaction(tx, privateKey);
19
let htx = await web3.eth.sendSignedTransaction(stx.rawTransaction);
20
console.log(htx)
21
await CtoP(id, amountWithDecimals);
22
} else {
23
console.log(error)
24
}
25
})
26
}
Copied!
In this snippet, we are subscribing to the logs of the "Staked" event after instanciating the sAVAX contract. Everytime this event is triggered, we can decode the logs. It shows as an hex, you could for example console.log(logs.data) if you're curious about it. We are then withdrawing the assets sent to the smart contract (as the smart contract owner).
We now have enough data to cross-chain before staking to a node. First, make sure that you have enough funds on your C-chain address. Go to the "AVAX test faucet": https://faucet.avax-test.network/. Copy and paste your C-chain address from the Avalanche wallet and request some (fake) AVAX.
1
async function CtoP() { //a C --> P cross-chain transfer doesn't exists, but C --> X, X --> P does.
2
3
// Includes the fees in the transferred AVAX
4
5
xChainAddress = xKeyChain.getAddressStrings();
6
cChainAddress = cKeyChain.getAddressStrings();
7
pChainAddress = pKeyChain.getAddressStrings();
8
9
let amount = new BN("1000000000"); //1 AVAX
10
11
let cChainHexAddress = "0x7bD7A7D2Ba70db40740780828b236F9246BB7F78";
12
13
let nonce = await web3.eth.getTransactionCount(cChainHexAddress, "pending");
14
15
let unsignedCtoXTx = await cChain.buildExportTx(
16
amount,
17
cAvaxAssetId,
18
xChainBlockchainID,
19
cChainHexAddress,
20
cChainAddress[0],
21
xChainAddress,
22
nonce,
23
)
24
25
let signedCtoXTx = await unsignedCtoXTx.sign(cKeyChain);
26
27
let CtoXTxId = await cChain.issueTx(signedCtoXTx);
28
29
console.log("CtoXTxId " + CtoXTxId);
30
31
let fee = cChain.getDefaultTxFee();
32
33
amount = amount.sub(fee);
34
35
return new Promise(function (resolve, reject) {
36
pollTransaction(waitForStatusC, CtoXTxId, resolve, reject);
37
}).then(async (resolve, reject) => {
38
if (resolve === "Accepted") {
39
utxoset = (await xChain.getUTXOs(
40
xChainAddress,
41
cChainBlockchainID,
42
)).utxos;
43
44
let unsignedImportXTx = await xChain.buildImportTx(
45
utxoset,
46
xChainAddress,
47
cChainBlockchainID,
48
xChainAddress,
49
xChainAddress,
50
)
51
52
let signedImportXTx = await unsignedImportXTx.sign(xKeyChain);
53
54
let importXTx = await xChain.issueTx(signedImportXTx);
55
56
console.log("importXTx " + importXTx);
57
58
fee = xChain.getDefaultTxFee();
59
60
amount = amount.sub(fee);
61
62
// C --> X done, now let's start X --> P.
63
64
utxoset = (await xChain.getUTXOs(
65
xChainAddress,
66
//xChainBlockchainID
67
)).utxos;
68
69
let unsignedXtoPTx = await xChain.buildExportTx(
70
utxoset,
71
amount,
72
pChainBlockchainID,
73
pChainAddress,
74
xChainAddress,
75
)
76
77
let signedXtoPTx = unsignedXtoPTx.sign(xKeyChain);
78
79
let XtoPTxId = await xChain.issueTx(signedXtoPTx);
80
81
console.log("XtoPTxId " + XtoPTxId);
82
83
fee = xChain.getDefaultTxFee();
84
85
amount = amount.sub(fee);
86
87
return new Promise(function (resolve, reject) {
88
pollTransaction(waitForStatusX, XtoPTxId, resolve, reject);
89
}).then(async (resolve, reject) => {
90
if (resolve === "Accepted") { // ... And import the transaction on the P chain.
91
utxoset = (await pChain.getUTXOs(
92
pChainAddress,
93
pChainBlockchainID
94
)).utxos;
95
96
let unsignedImportPTx = await pChain.buildImportTx(
97
utxoset,
98
pChainAddress,
99
xChainBlockchainID,
100
pChainAddress,
101
pChainAddress,
102
)
103
104
let signedImportPTx = unsignedImportPTx.sign(pKeyChain);
105
106
let importPTx = await pChain.issueTx(signedImportPTx);
107
108
console.log("importPTx " + importPTx);
109
110
fee = pChain.getDefaultTxFee();
111
112
amount = amount.sub(fee);
113
} else {
114
// Error
115
}
116
})
117
} else {
118
// Throw an error
119
}
120
})
121
}
Copied!
This code snippet is doing a cross-chain transfer between the C-chain and P-chain with 1 $AVAX, deducting the fees for each transaction. You can find the value of the fees on Avalanche here: https://docs.avax.network/learn/platform-overview/transaction-fees#fee-schedule. Just keep in mind that at least 25 AVAX (after deducting the fees, and on mainnet) are needed to delegate to a node.
We cannot directly do a C-chain to P-chain transaction, but we can do C-chain to X-chain and X-chain to P-chain. For each transaction export, we need to wait for the transaction to be marked as "Accepted" to import the transaction. This is why the pollTransaction will check the transaction status each 100ms and resolve the Promise when the transaction is accepted. If this is not done, we would try to export more funds than the ones that are in our wallet, and fail the transaction because of insufficient funds.
We are now ready to delegate to a node now that the funds are on the P-chain.
We highly recommend to run your own Avalanche node rather than the public API if you run on mainnet, and need a high fiability (production use).

Frontend

We won't try to learn you how to create a frontend in this tutorial, but we've forked one from Olive Swap just to give you an insight. Here is how to run the frontend:
Start by installing git. This will be used to clone the repo of our frontend.

Windows

    1.
    Download git through this link: https://gitforwindows.org/​
    2.
    With the installation prompt, choose to use git from the command prompt
    3.
    Create a directory. We could call it "Liquidavax-frontend"
    4.
    Win+R
    5.
    type cmd
1
cd <pathtoLiquidavax-frontend> (ex: cd C:\Users\iFrostizz\Desktop\MyProjects\Liquidavax-frontend)
2
git clone https://github.com/iFrostizz/fluidavax-frontend --branch devel
3
cd ./fluidavax-frontend
4
npm install --global yarn
5
yarn install --force
6
yarn start
Copied!

Ubuntu

1
sudo apt-get update
2
sudo apt-get install git
Copied!
Create a directory, and head to it. Then, clone the github repository of the frontend.
1
git clone https://github.com/iFrostizz/fluidavax-frontend --branch devel
2
cd ./fluidavax-frontend
3
npm install --global yarn
4
yarn install --force
5
yarn start
Copied!
​
Open your browser. The url will mostly be localhost:3000
Last modified 1mo ago