SKALE Chain to SKALE Chain ERC20 Transfer

As a SKALE Chain Owner, there are two main steps to managing SKALE Chain to SKALE Chain (S2S) ERC20 transfer through IMA:

Once you have completed step 1 to setup ERC20 tokens with another chain, end-users can transfer ERC20 tokens between SKALE Chains.

Setup ERC20 S2S Transfers

The following one-time setup is required for SKALE Chains with a default access control policy (default settings are: whitelisting enabled, automatic deployment disabled). For more information on IMA access control, see here.

0. Assign role

There is a bug in the current IMA version where the CHAIN_CONNECTOR_ROLE is unassigned at deployment. In order to connect other chains to support S2S transfers, you must first assign this role to TokenManagerLinker.

await MessageProxyForSchain.grantRole(CHAIN_CONNECTOR_ROLE, TokenManagerLinker.address)

1. Connect each SKALE Chain

You must connect each chain in both directions by executing two connectSchain() transaction on each respective chain.

⇢ To connect the target chain to the origin chain, run connectSchain(targetSchainName) in TokenManagerLinker contract on the origin chain.

⇠ To connect the origin chain to the target chain, run connectSchain(originSchainName) in TokenManagerLinker contract on the target chain.

Only the REGISTRAR_ROLE in TokenManagerLinker may execute connectSchain. So you must be granted with this role on this contract.
  • IMA-JS

  • Web3 JS

// import & init ima-js here

export async function connectSchain(ima) {
    let address = "YOUR_ADDRESS";
    let privateKey = "YOUR_PRIVATE_KEY";

    let opts = {
        address: address,
        privateKey: privateKey // remove privateKey from txOpts to use Metamask signing
    };

    await ima.schain.tokenManagerLinker.connectSchain(schainName, opts);
}
const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;

let schainABIs = require("[YOUR_SKALE_CHAIN_ABIs]");
let privateKey = Buffer.from('[YOUR_PRIVATE_KEY]', 'hex')
let account = "[YOUR_ACCOUNT_ADDRESS]";
let schainEndpoint = "[YOUR_SKALE_CHAIN_ENDPOINT]";
let chainId = "ORIGIN_CHAIN_ID";
let targetSchainName = "TARGET_SKALE_CHAIN_NAME";

const tokenManagerLinkerAddress = schainABIs.token_manager_linker_address;
const tokenManagerLinkerABI = schainABIs.token_manager_linker_abi;

const web3 = new Web3(new Web3.providers.HttpProvider(schainEndpoint));

let contract = new web3.eth.Contract(
  tokenManagerLinkerABI, 
  tokenManagerLinkerAddress
);

/* 
 * Prepare connectSchain
 */
let connectSchain = contract.methods.connectSchain(targetSchainName)
  .encodeABI();  

//get nonce
web3.eth.getTransactionCount(account).then((nonce) => {
  //create raw transaction
  const rawTx = {
    chainId: chainId,
    nonce: "0x" + nonce.toString(16),
    from: account, 
    nonce: "0x" + nonce.toString(16),
    data : connectSchain,
    to: tokenManagerLinkerAddress,
    gasPrice: 100000000000,
    gas: 8000000
  }

  //sign transaction
  const tx = new Tx(rawTx);
  tx.sign(privateKey);

  //serialize transaction
  const serializedTx = tx.serialize();

  //send signed transaction
  web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).
    on('receipt', receipt => {
      //record receipt to console
      console.log(receipt);
   }).
    catch(console.error);
});

2. Deploy ERC20 on Origin

Deploy your ERC20 contract on the Origin chain.

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract Token is ERC20, AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");

    constructor(
        string memory name,
        string memory symbol,
        uint8 decimals
    ) public ERC20(name, symbol) {
        _setupDecimals(decimals);
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function mint(address to, uint256 amount) public virtual {
        require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
        _mint(to, amount);
    }

}

3. Deploy ERC20 clone on Target

The ERC20 clone on the target chain MUST have both mint and burn functionalities. If the original ERC20 contract on origin does not have burn functionalities, then you must either assign BURNER_ROLE (if using Open Zeppelin’s Role-Based Access control) or add a burn() to the clone that is assigned/callable by the TokenManagerERC20.

// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract ERC20Clone is ERC20, AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");

    constructor(
        string memory name,
        string memory symbol,
        uint8 decimals
    ) public ERC20(name, symbol) {
        _setupDecimals(decimals);
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function mint(address to, uint256 amount) public virtual {
        require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
        _mint(to, amount);
    }

    function burn(uint256 amount) public virtual {
        require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner");
        _burn(msg.sender, amount);
    }
}

4. Register ERC20 clone in TokenManger on Target

You need to register the target token contract using the addERC20TokenByOwner method in the TokenManagerERC20 contract on the targetSchain. addERC20TokenByOwner(originSchainName, originERC20Address, targetERC20Address)

The parameters on target TokenManagerERC20.addERC20TokenByOwner() are not symmetric to origin! The only parameter to swap is the first parameter for SchainName.
  • IMA-JS

  • Web3 JS

// import & init ima-js here

export async function linkERC20TokenOrigin(schain) {
    let erc20OnOrigin = "[ADDRESS_OF_ERC20_TOKEN_ON_ORIGIN]";
    let erc20OnTarget = "[ADDRESS_OF_ERC20_TOKEN_ON_TARGET]";

    const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';

    let address = "[YOUR_ADDRESS]";
    let privateKey = "[YOUR_PRIVATE_KEY]";

    let opts = {
        address: address,
        privateKey: privateKey // remove privateKey from txOpts to use Metamask signing
    };

    const isERC20AddedTarget = await schain.erc20.getTokenCloneAddress(erc20OnTarget);
    if (isERC20AddedTarget === ZERO_ADDRESS) {
        await schain.erc20.addTokenByOwner(
            originChainName,
            erc20OnOrigin,
            erc20OnTarget,
            opts
        );
    }
}
const Web3 = require("web3");
const Tx = require("ethereumjs-tx").Transaction;

export function registerOnTargetChain() {
  let targetABIs = require("./contracts/target_ABIs.json");
  let originERC20ABI = require("./contracts/origin_ERC20_ABI.json");
  let targetERC20ABI = require("./contracts/target_ERC20_ABI.json");

  let privateKey = Buffer.from(
    "SCHAIN_OWNER_PRIVATE_KEY",
    "hex"
  );
  
  let erc20OwnerForTarget =
    process.env.SCHAIN_OWNER_ACCOUNT;

  let target = process.env.TARGET_ENDPOINT;
  let originChainName = process.env.ORIGIN_CHAIN_NAME;
  let targetChainId = process.env.TARGET_CHAIN_ID;

  const targetTokenManagerAddress = targetABIs.token_manager_erc20_address;
  const targetTokenManagerABI = targetABIs.token_manager_erc20_abi;

  const erc20AddressOnOrigin = originERC20ABI.erc20_address;
  const erc20AddressOnTarget = targetERC20ABI.erc20_address;

  const web3ForTarget = new Web3(target);

  let TokenManager = new web3ForTarget.eth.Contract(
    targetTokenManagerABI,
    targetTokenManagerAddress
  );

  /**
   * Uses the SKALE TokenManagerERC20
   * contract function addERC20TokenByOwner
   */
let addERC20TokenByOwner = TokenManager.methods
    .addERC20TokenByOwner(originChainName, erc20AddressOnOrigin, erc20AddressOnTarget)
    .encodeABI();     // IMPORTANT: arguments here are not symmetric to origin addERC20TokenByOwner

    web3ForTarget.eth.getTransactionCount(erc20OwnerForTarget).then((nonce) => {
    const rawTxAddERC20TokenByOwner = {
      chainId: targetChainId,
      from: erc20OwnerForTarget,
      nonce: "0x" + nonce.toString(16),
      data: addERC20TokenByOwner,
      to: targetTokenManagerAddress,
      gas: 6500000,
      gasPrice: 100000000000,
      value: web3ForTarget.utils.toHex(
        web3ForTarget.utils.toWei("0", "ether")
      )
    };

    //sign transaction
    const txAddERC20TokenByOwner = new Tx(rawTxAddERC20TokenByOwner, {
      chain: "rinkeby",
      hardfork: "petersburg"
    });

    txAddERC20TokenByOwner.sign(privateKey);

    const serializedTxDeposit = txAddERC20TokenByOwner.serialize();

    //send signed transaction (addERC20TokenByOwner)
    web3ForTarget.eth
      .sendSignedTransaction("0x" + serializedTxDeposit.toString("hex"))
      .on("receipt", (receipt) => {
        console.log(receipt);
      })
      .catch(console.error);
  });

5. Assign MINTER and BURNER roles to TokenManager on Target.

Now you need to assign the TokenManagerERC20 contact on your SKALE Chain as the MINTER_ROLE and BURNER_ROLE for the ERC20 clone on the target. With OpenZeppelin’s framework, you simply need to execute an AddMinter, AddBurner, and/or grantRole transaction on the SKALE chain token contract.

Example Add Minter Role

  • Web3 JS

import Common from "ethereumjs-common";
const Tx = require("ethereumjs-tx").Transaction;
const Web3 = require("web3");

export function addMinter() {
  let schainABIs = require("./contracts/schain_ABIs.json");
  let schainERC20ABI = require("./contracts/schain_ERC20_ABI.json");

  let contractOwnerPrivateKey = Buffer.from(
    "CONTRACT_OWNER_PRIVATE_KEY",
    "hex"
  );
  let contractOwnerAccount =
    process.env.REACT_APP_INSECURE_CONTRACT_OWNER_ACCOUNT;

  let schainEndpoint = process.env.REACT_APP_INSECURE_SKALE_CHAIN;
  let chainId = process.env.REACT_APP_INSECURE_CHAIN_ID;

  const customCommon = Common.forCustomChain(
    "mainnet",
    {
      name: "skale-network",
      chainId: chainId
    },
    "istanbul"
  );

  const erc20ABI = schainERC20ABI.erc20_abi;
  const erc20Address = schainERC20ABI.erc20_address;

  const tokenManagerERC20Address = schainABIs.token_manager_erc20_address;

  const web3ForSchain = new Web3(schainEndpoint);

  let schainERC20Contract = new web3ForSchain.eth.Contract(
    erc20ABI,
    erc20Address
  );

  /**
   * Uses the openzeppelin ERC20Mintable
   * contract function addMinter
   * https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC20
   */
let addMinter = schainERC20Contract.methods
    .addMinter(tokenManagerERC20Address)
    .encodeABI();

  web3ForSchain.eth.getTransactionCount(contractOwnerAccount).then((nonce) => {
    //create raw transaction
    const rawTxAddMinter = {
      chainId: chainId,
      from: contractOwnerAccount,
      nonce: nonce,
      data: addMinter,
      to: erc20Address,
      gasPrice: 100000000000,
      gas: 8000000,
      value: 0
    };
    //sign transaction
    const txAddMinter = new Tx(rawTxAddMinter, { common: customCommon });
    txAddMinter.sign(contractOwnerPrivateKey);

    const serializedTxAddMinter = txAddMinter.serialize();

    //send signed transaction (add minter)
    web3ForSchain.eth
      .sendSignedTransaction("0x" + serializedTxAddMinter.toString("hex"))
      .on("receipt", (receipt) => {
        console.log(receipt);
      })
      .catch(console.error);
  });

Get Started with S2S ERC20 Transfer

Be sure to follow any one-time setup and mapping steps described here before initiating S2S transfers.

1. S2S Transfer ERC20 From Origin

To send ERC20 tokens from a user’s wallet to another SKALE Chain, you will need to use the transferToSchainERC20 function within the TokenManagerERC20 IMA contract on the origin chain.

This method is called from the origin chain to move ERC20 tokens to a target chain.

The TokenManagerERC20 contract is predeployed on each SKALE Chain. To get the SKALE Chain ABIs, check out the current release page.

  • IMA-JS

  • Web3 JS

export function initTestTokenContractSchain(schain) {
    // initialize ERC20 contract
    const abiData = require("[ERC20_ABI_ON_CHAIN]");
    return new schain.web3.eth.Contract(
        abiData.erc20_abi,
        abiData.erc20_address);
}

export async function transfer() {
    const schain = new SChain(sChainWeb3, sChainAbi); // origin schain

    let tokenName = "[TOKEN_NAME]";
    let schainERC20 = initTestTokenContractSchain(imaschain);

    let address = "YOUR_ADDRESS";
    let privateKey = "YOUR_PRIVATE_KEY";

    let amount = "[AMOUNT_IN_WEI]";

    let opts = {
        address: address,
        privateKey: privateKey // remove privateKey from txOpts to use Metamask signing
    };

    schain.erc20.addToken(tokenName, schainERC20);

    await schain.erc20.approve(tokenName, amount, opts);
    await schain.erc20.transferToSchain(
        targetSchainName,
        schainERC20.address,
        amount,
        opts
    );
}
const Web3 = require("web3");
const Tx = require("ethereumjs-tx").Transaction;

let originABIs = "IMA_ABI_ON_ORIGIN";
let originERC20ABI = "ERC20_ABI_ON_ORIGIN";

let privateKey = Buffer.from("END_USER_PRIVATE_KEY", 'hex')
let address = "ADDRESS";

let origin = "ORIGIN_ENDPOINT";
let targetChainName = "TARGET_CHAIN_NAME";
let originChainId = "ORIGIN_CHAIN_ID";

const tokenManagerAddress = originABIs.token_manager_erc20_address;
const tokenManagerABI = originABIs.token_manager_erc20_abi;

const erc20ABI = originERC20ABI.erc20_abi;
const erc20Address = originERC20ABI.erc20_address;

const web3ForOrigin = new Web3(origin);

let tokenManager = new web3ForOrigin.eth.Contract(
    tokenManagerABI,
    tokenManagerAddress
);

const customCommon = Common.forCustomChain(
    "mainnet", {
        name: "skale-network",
        chainId: originChainId
    },
    "istanbul"
);

let contractERC20 = new web3ForOrigin.eth.Contract(erc20ABI, erc20Address);

let approve = contractERC20.methods
    .approve(
        tokenManagerAddress,
        web3ForOrigin.utils.toHex(web3ForOrigin.utils.toWei("1", "ether"))
    )
    .encodeABI();

let transfer = tokenManager.methods
    .transferToSchainERC20(
        targetChainName,
        erc20Address,
        web3ForOrigin.utils.toHex(web3ForOrigin.utils.toWei("1", "ether"))
    )
    .encodeABI();

web3ForOrigin.eth.getTransactionCount(address).then(nonce => {
    //create raw transaction
    const rawTxApprove = {
        chainId: originChainId,
        from: address,
        nonce: "0x" + nonce.toString(16),
        data: approve,
        to: erc20Address,
        gas: 6500000,
        gasPrice: 100000000000
    };

    //sign transaction
    const txApprove = new Tx(rawTxApprove, {
        common: customCommon
    });
    txApprove.sign(privateKey);

    const serializedTxApprove = txApprove.serialize();

    //send signed transaction (approve)
    web3ForOrigin.eth
        .sendSignedTransaction("0x" + serializedTxApprove.toString("hex"))
        .on("receipt", receipt => {
            console.log(receipt);
            web3ForOrigin.eth
                .getTransactionCount(address)
                .then(nonce => {
                    const rawTxDeposit = {
                        chainId: originChainId,
                        from: address,
                        nonce: "0x" + nonce.toString(16),
                        data: transfer,
                        to: tokenManagerAddress,
                        gas: 6500000,
                        gasPrice: 100000000000
                    };

                    //sign transaction
                    const txDeposit = new Tx(rawTxDeposit, {
                        common: customCommon
                    });

                    txDeposit.sign(privateKey);

                    const serializedTxDeposit = txDeposit.serialize();

                    //send signed transaction (deposit)
                    web3ForOrigin.eth
                        .sendSignedTransaction("0x" + serializedTxDeposit
                            .toString("hex"))
                        .on("receipt", receipt => {
                            console.log(receipt);
                        })
                        .catch(console.error);
                });
        })
        .catch(console.error);
});

2. Exit from SKALE Chain

To exit ERC20 tokens back to the origin chain, you will need to use the transferToSchainERC20 function within the TokenManagerERC20 IMA contract on the target chain, and specify the erc20Address on the origin chain.

The TokenManagerERC20 IMA contract is pre-deployed to your SKALE Chain. Please reach out to your account manager to receive the ABIs specific for your SKALE Chain.

  • IMA-JS

  • Web3 JS

export function initTestTokenContractSchain(schain) {
    // initialize ERC20 contract
    const abiData = require("[ERC20_ABI_ON_TARGET_CHAIN]");
    return new schain.web3.eth.Contract(
        abiData.erc20_abi,
        abiData.erc20_address);
}


export async function transfer() {
    const schain = new SChain(sChainWeb3, sChainAbi); // target schain

    let tokenName = "[TOKEN_NAME]";
    let schainERC20 = initTestTokenContractSchain(schain);

    let address = "YOUR_ADDRESS";
    let privateKey = "YOUR_PRIVATE_KEY";

    let tokenAddressOriginChain = "[TOKEN_ADDRESS]";

    let amount = "[AMOUNT_IN_WEI]";

    let opts = {
        address: address,
        privateKey: privateKey // remove privateKey from txOpts to use Metamask signing
    };

    schain.erc20.addToken(tokenName, schainERC20);

    await schain.erc20.approve(tokenName, amount, opts);
    await schain.erc20.transferToSchain(
        targetSchainName,
        tokenAddressOriginChain, // KEY DIFFERENCE - you should set address of the token on the origin chain
        amount,
        opts
    );
}
const Web3 = require("web3");
const Tx = require("ethereumjs-tx").Transaction;

let targetABIs = "IMA_ABI_ON_TARGET";
let originERC20ABI = "ERC20_ABI_ON_ORIGIN";

let privateKey = Buffer.from("END_USER_PRIVATE_KEY", 'hex')
let address = "ADDRESS";

let target = "TARGET_ENDPOINT";
let originChainName = "ORIGIN_CHAIN_NAME";
let targetChainId = "TARGET_CHAIN_ID";

const tokenManagerAddress = targetABIs.token_manager_erc20_address;
const tokenManagerABI = targetABIs.token_manager_erc20_abi;

const erc20ABI = targetERC20ABI.erc20_abi;
const erc20TargetAddress = targetERC20ABI.erc20_address;
const erc20OriginAddress = originERC20ABI.erc20_address;

const web3ForTarget = new Web3(target);

let tokenManager = new web3ForTarget.eth.Contract(
    tokenManagerABI,
    tokenManagerAddress
);

const customCommon = Common.forCustomChain(
    "mainnet", {
        name: "skale-network",
        chainId: targetChainId
    },
    "istanbul"
);

let contractERC20 = new web3ForTarget.eth.Contract(erc20ABI, erc20TargetAddress);

let approve = contractERC20.methods
    .approve(
        tokenManagerAddress,
        web3ForTarget.utils.toHex(web3ForTarget.utils.toWei("1", "ether"))
    )
    .encodeABI();

let transfer = tokenManager.methods
    .transferToSchainERC20(
        originChainName,
        erc20OriginAddress,
        web3ForTarget.utils.toHex(web3ForTarget.utils.toWei("1", "ether"))
    )
    .encodeABI();

    web3ForTarget.eth.getTransactionCount(address).then(nonce => {
    //create raw transaction
    const rawTxApprove = {
        chainId: targetChainId,
        from: address,
        nonce: "0x" + nonce.toString(16),
        data: approve,
        to: erc20Address,
        gas: 6500000,
        gasPrice: 100000000000
    };

    //sign transaction
    const txApprove = new Tx(rawTxApprove, {
        common: customCommon
    });
    txApprove.sign(privateKey);

    const serializedTxApprove = txApprove.serialize();

    //send signed transaction (approve)
    web3ForTarget.eth
        .sendSignedTransaction("0x" + serializedTxApprove.toString("hex"))
        .on("receipt", receipt => {
            console.log(receipt);
            web3ForTarget.eth
                .getTransactionCount(address)
                .then(nonce => {
                    const rawTxDeposit = {
                        chainId: targetChainId,
                        from: address,
                        nonce: "0x" + nonce.toString(16),
                        data: transfer,
                        to: tokenManagerAddress,
                        gas: 6500000,
                        gasPrice: 100000000000
                    };

                    //sign transaction
                    const txDeposit = new Tx(rawTxDeposit, {
                        common: customCommon
                    });

                    txDeposit.sign(privateKey);

                    const serializedTxDeposit = txDeposit.serialize();

                    //send signed transaction (deposit)
                    web3ForTarget.eth
                        .sendSignedTransaction("0x" + serializedTxDeposit
                            .toString("hex"))
                        .on("receipt", receipt => {
                            console.log(receipt);
                        })
                        .catch(console.error);
                });
        })
        .catch(console.error);
});