RoC Stable Platform - Collateral RIF Token
  • Introduction
  • RIF On Chain platform
    • Main concepts
    • System states
    • Public actions
      • User actions
      • Process actions
    • Contracts architecture
      • MoC
      • CommissionSplitter
      • MoCState
      • MoCBucketContainer
      • MoCSettlement
      • MoCHelperLib
      • MoCLibConnection
      • MoCConverter
      • MoCExchange
      • MoCConnector
      • MoCRiskProxManager
      • MoCInrate
      • MoCVendors
      • MoCWhitelist
      • MoCBase
      • OwnerBurnableToken
      • RiskProToken
      • StableToken
      • MoCToken
      • PriceProvider
    • Contract mocks
    • Relevant patterns and choices
    • Data dictionary
    • Getting started
  • Integration with RoC platform
    • Introduction to RoC
      • The MoC Contract
      • RoC Precisions
      • RoC State Contracts
    • Getting RIFPros
      • Minting RIFPros
      • Redeeming RIFPros
    • Getting USDRIF
      • Minting USDRIF
      • Redeeming USDRIF
        • On Settlement: redeemStableTokenRequest
        • On Settlement: alterRedeemRequestAmount
        • Outside Settlement: redeemFreeStableToken
        • On Liquidation State: redeemAllStableToken
        • How-to
    • Commission fees values
    • Vendors
    • Fees calculation
    • From outside the blockchain
      • Using RSK nodes
      • Using web3
      • Official RIF On Chain ABIs
      • Events
      • Example code minting RIFPros
      • Example code minting RIFPros without Truffle
      • Example code redeeming RIFPros
      • Example code redeeming RIFPros without Truffle
      • Example code minting USDRIF
      • Example code redeeming free USDRIF
      • Example code redeeming USDRIF Request
      • Example code redeeming all USDRIF
  • Smart contracts
    • Contracts verification
    • ABIs documentation
      • Blockable
      • Blocker
      • ERC20Mintable
      • Governed
      • Initializable
      • MakeStoppable
      • MakeUnstoppable
      • MoC
      • MoCBucketContainer
      • MoCConnector
      • MoCConverter
      • MoCEMACalculator
      • MoCExchange
      • MoCHelperLib
      • MoCHelperLibMock
      • MoCInrate
      • MoCInrateRiskproxChanger
      • MoCLibConnection
      • MoCPriceProviderMock
      • MoCReserve
      • MoCRiskProxManager
      • MoCSettlement
      • MoCSettlementMock
      • MoCState
      • MoCStateMock
      • MoCToken
      • MoCVendors
      • MoCWhitelist
      • MocInrateStableChanger
      • MockBlocker
      • MockMakeStoppable
      • MockMakeUnstoppable
      • MockStopper
      • MockUpgradeDelegator
      • MockUpgraderTemplate
      • OwnerBurnableToken
      • Pausable
      • PriceFeed
      • PriceFeederAdder
      • PriceFeederRemover
      • PriceProvider
      • PriceProviderChanger
      • PriceProviderMock
      • ReserveToken
      • RiskProToken
      • StableToken
      • Stoppable
      • Stopper
      • UpgradeDelegator
      • UpgraderTemplate
Powered by GitBook
On this page
  1. Integration with RoC platform
  2. From outside the blockchain

Example code minting USDRIF

In the following example we will learn how to:

  • Get the maximum amount of USDRIF available to mint.

  • Mint USDRIF.

You can find code examples into /examples dir.

We will use truffle and testnet network First we create a new node project.

mkdir example-mint-rdoc
cd example-mint-rdoc
npm init

Let's add the necessary dependencies to run the project.

npm install --save bignumber.js
npm install --save web3

Example:

const BigNumber = require('bignumber.js');
const Web3 = require('web3');
//You must compile the smart contracts or use the official ABIs of the repository
const MocAbi = require('../../build/contracts/MoC.json');
const MoCInrateAbi = require('../../build/contracts/MoCInrate.json');
const MoCExchangeAbi = require('../../build/contracts/MoCExchange.json');
const MoCStateAbi = require('../../build/contracts/MoCState.json');
const ReserveToken = require('../../build/contracts/ReserveToken.json');
const truffleConfig = require('../../truffle');

/**
 * Get a provider from truffle.js file
 * @param {String} network
 */
const getDefaultProvider = network =>
  truffleConfig.networks[network].provider || truffleConfig.networks[network].endpoint;

/**
 * Get a gasPrice from truffle.js file
 * @param {String} network
 */
const getGasPrice = network => truffleConfig.networks[network].gasPrice || 60000000;

/**
 * Get a new web3 instance from truffle.js file
 */
const getWeb3 = network => {
  const provider = getDefaultProvider(network);
  return new Web3(provider, null, {
    transactionConfirmationBlocks: 1
  });
};

const web3 = getWeb3('mocTestnet');
const gasPrice = getGasPrice('mocTestnet');

//Contract addresses on testnet
const mocContractAddress = '<contract-address>';
const mocInrateAddress = '<contract-address>';
const mocExchangeAddress = '<contract-address>';
const mocStateAddress = '<contract-address>';
const reserveTokenAddress = '<contract-address>';


const execute = async () => {
  web3.eth.defaultGas = 2000000;

  /**
   * Loads an specified contract
   * @param {ContractABI} abi
   * @param {String} contractAddress
   */
  const getContract = async (abi, contractAddress) => new web3.eth.Contract(abi, contractAddress);

  /**
   * Transforms BigNumbers into
   * @param {BigNumber} number
   */
  const toContract = number => new BigNumber(number).toFixed(0);

  // Loading moc contract
  const moc = await getContract(MocAbi.abi, mocContractAddress);
  if (!moc) {
    throw Error('Can not find MoC contract.');
  }

  // Loading mocInrate contract. It is necessary to get fees for transaction types
  const mocInrate = await getContract(MoCInrateAbi.abi, mocInrateAddress);
  if (!mocInrate) {
    throw Error('Can not find MoC Inrate contract.');
  }

  // Loading mocExchange contract. It is necessary to compute commissions and vendor markup
  const mocExchange = await getContract(MoCExchangeAbi.abi, mocExchangeAddress);
  if (!mocExchange) {
    throw Error('Can not find MoC Exchange contract.');
  }

  // Loading mocState contract. It is necessary to compute max USDRIF available to mint
  const mocState = await getContract(MoCStateAbi.abi, mocStateAddress);
  if (!mocState) {
    throw Error('Can not find MoCState contract.');
  }

  // Loading ReserveToken contract. It is necessary to set max available RIF to spend
  const reserveToken = await getContract(ReserveToken.abi, reserveTokenAddress);
  if (!reserveToken) {
    throw Error('Can not find ReserveToken contract.');
  }

  const [from] = await web3.eth.getAccounts();

  const setAllowance = async allowanceAmount =>{
    const weiAmount = web3.utils.toWei(allowanceAmount, 'ether');
    console.log(`Calling approve: ${weiAmount}, for address account: ${from}.`);
    await reserveToken.methods.approve(mocContractAddress, weiAmount).send({ from, gasPrice });
    const spendableBalance = await moc.methods.getAllowance(from).call();
    console.log(`Spendable balance for account ${from} is: ${spendableBalance}`);
  }

  const mintRDoc = async (rifAmount, allowanceAmount, vendorAccount) => {
    const weiAmount = web3.utils.toWei(rifAmount, 'ether');
    await setAllowance(allowanceAmount);
    let reserveTokenCommission;
    let mocCommission;
    let reserveTokenMarkup;
    let mocMarkup;
    // Set transaction types
    const txTypeFeesReserveToken = await mocInrate.methods.MINT_STABLETOKEN_FEES_RESERVE();
    const txTypeFeesMOC = await mocInrate.methods.MINT_STABLETOKEN_FEES_MOC();
    // Compute fees
    const params = {
      account: from,
      amount: toContractBN(weiAmount).toString(),
      txTypeFeesMOC: txTypeFeesMOC.toString(),
      txTypeFeesReserveToken: txTypeFeesReserveToken.toString(),
      vendorAccount
    };

    ({
      reserveTokenCommission,
      mocCommission,
      reserveTokenMarkup,
      mocMarkup
    } = await mocExchange.methods.calculateCommissionsWithPrices(params, { from }));
    // Computes totalReserveTokenAmount to call mintStableTokenVendors
    const totalReserveTokenAmount = toContract(reserveTokenCommission.plus(reserveTokenMarkup).plus(weiAmount));
    console.log(`Calling RDoc minting, account: ${from}, amount: ${weiAmount}.`);
    moc.methods
      .mintStableTokenVendors(weiAmount, vendorAccount)
      .send({ from, gasPrice }, function(error, transactionHash) {
        if (error) console.log(error);
        if (transactionHash) console.log('txHash: '.concat(transactionHash));
      })
      .on('transactionHash', function(hash) {
        console.log('TxHash: '.concat(hash));
      })
      .on('receipt', function(receipt) {
        console.log(receipt);
      })
      .on('error', console.error);
  };

  // Gets max USDRIF available to mint
  const getAbsoluteMaxRDoc = await mocState.methods.absoluteMaxStableToken().call();
  const rifAmount = '0.00001';
  const vendorAccount = '<vendor-address>';
  // Before start minting RDoc we need to set the allowance of RIF available to spend.
  const allowanceAmount = '0.001';

  console.log('=== Max doc amount available to mint: ', getAbsoluteMaxRDoc.toString());
  console.log('=== RIFs that are gonna be minted:  ', rifAmount);

  // Call mint
  await mintRDoc(rifAmount, allowanceAmount, vendorAccount);
};

execute()
  .then(() => console.log('Completed'))
  .catch(err => {
    console.log('Error', err);
  });
PreviousExample code redeeming RIFPros without TruffleNextExample code redeeming free USDRIF

Last updated 1 year ago