Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <header><img src="https://docs.synthetix.io/img/logos/synthetix_text_logo_white.png" /></header>

<main>
  <p>
    <input name="fromBlock" placeholder="Block number (leave blank for latest)" />
  </p>
  <p>
    <input name="address" placeholder="Enter Ethereum Address" />
  </p>

  <div class="flextables">
    <div>
      <h2>Summary</h2>
      <table></table>
      <section></section>
    </div>
    <div>
      <h2>Holdings</h2>
      <table></table>
      <section></section>
    </div>
  </div>
  
</main>

              
            
!

CSS

              
                body {
  font-family: 'Helvetica';
  padding: 0;
  margin: 0;
}

header {
  background-color: #0b0816;
  min-height: 50px;
  img {
    padding: 8px;
  }
}

main {
  padding: 20px;
}

input { 
  width: 300px; 
  padding: 5px;
}

button {
  cursor: pointer;
}

.flextables {
  display: flex;
  > * {
    width: 50%;
    
    table {
      margin-top: 25px;
      &:nth-child(1) {
         th {
          text-align: right;
        }
      }
      &:nth-child(2) {
        th {
          text-align: left;
        }
      }
    }
  }
 
}

              
            
!

JS

              
                const snxjs = new SynthetixJs.SynthetixJs(); 
const { formatBytes32String } = SynthetixJs.SynthetixJs.utils;
const { synths } = snxjs.contractSettings;
const input = document.querySelector('input[name=address]');
input.addEventListener('change', () => {
  lookup();
});

const summaryTable = document.querySelector('.flextables *:nth-child(1) table');
const portfolioTable = document.querySelector('.flextables *:nth-child(2) table');

const chartTrendingDebtContainer = document.querySelector('.flextables *:nth-child(1) section');
const chartPortfolioContainer = document.querySelector('.flextables *:nth-child(2) section');

const lookup = async () => {
  const fromBlock = document.querySelector('input[name=fromBlock]').value;
  const blockOptions = fromBlock ? { blockTag: Number(fromBlock) } : {};
  
   const account = input.value;
   summaryTable.innerHTML = '<img src="https://media.giphy.com/media/TvLuZ00OIADoQ/giphy.gif" width=150 />';
   portfolioTable.innerHTML = summaryTable.innerHTML;
   //chartTrendingDebtContainer.innerHTML = summaryTable.innerHTML;
   chartPortfolioContainer.innerHTML = summaryTable.innerHTML;
  try {
    const results = await Promise.all([snxjs.SynthetixState.issuanceRatio(), snxjs.ExchangeRates.contract.rateForCurrency(formatBytes32String('SNX'), blockOptions), snxjs.Synthetix.contract.transferableSynthetix(account, blockOptions), snxjs.Synthetix.contract.collateral(account, blockOptions), snxjs.Synthetix.contract.collateralisationRatio(account, blockOptions), snxjs.sUSD.contract.balanceOf(account, blockOptions), snxjs.Synthetix.contract.debtBalanceOf(account, formatBytes32String('sUSD'), blockOptions), snxjs.FeePool.contract.feesAvailable(account, blockOptions)]);
    const [ issuanceRatio, usdToSnxPrice, unlockedSnx, collateral, collateralRatio,sUSDBalance, debtBalance, [currentFeesAvailable, currentRewardsAvailable] ] = results.map(input => Array.isArray(input) ? input.map(snxjs.utils.formatEther) : snxjs.utils.formatEther(input));
    
    const currentCRatio = (1/collateralRatio)*100;
  
    summaryTable.innerHTML = `
      <tr><th>SNX Price</th><td>${Number(usdToSnxPrice).toFixed(5)} USD</td></tr>
      <tr><th>Total Collateral</th><td>${Number(collateral * usdToSnxPrice).toFixed(2)} USD (${Number(collateral).toFixed(2)} SNX)</td></tr>
      <tr><th>Unlocked SNX</th><td>${Number(unlockedSnx * usdToSnxPrice).toFixed(2)} USD (${Number(unlockedSnx).toFixed(2)} SNX) ${Math.round(unlockedSnx/collateral * 100)}</td></tr>
      <tr><th>Ratio</th><td>${Number(collateralRatio).toFixed(5)}</td></tr>
      <tr><th>Current sUSD Balance</th><td>${Number(sUSDBalance).toFixed(2)} sUSD</td></tr>
      <tr><th>Total Debt Owed</th><td>${Number(debtBalance).toFixed(2)} sUSD</td></tr>
      <tr><th>Current Collateralization Ratio</th><td>${Math.round(currentCRatio)}%</td></tr>
      <tr><th>Fees Available</th><td>${numbro(currentFeesAvailable).format('0,0.00')}</td></tr>
      <tr><th>Rewards Available</th><td>${numbro(currentRewardsAvailable).format('0,0.00')}</td></tr>
    `;
  } catch (err) {
    summaryTable.innerHTML = `<span style="color:red">${err}</span>`;
  }
  
  
  
  const availableSynths = synths.filter(({ asset }) => asset);
  
  const balances = await Promise.all(availableSynths.map(({ name }) => snxjs[name].contract.balanceOf(account, blockOptions)));
  
  const balancesEffective = await Promise.all(availableSynths.map(({ name }, i) => snxjs.ExchangeRates.contract.effectiveValue(formatBytes32String(name), balances[i], formatBytes32String('sUSD'), blockOptions)));
  
  const balancesInUSD = balancesEffective.map(snxjs.utils.formatEther);
  
  const totalInPortfolio = balancesInUSD.reduce((a, b) => Number(a) + Number(b), 0);
  
  const holdings = availableSynths.map(({ name }, i) => {
    return {
      synthKey: name,
      balanceOf: snxjs.utils.formatEther(balances[i]), 
      balanceInUSD: balancesInUSD[i],
      percentage: balancesInUSD[i] / totalInPortfolio
    };
  }).filter(({ balanceOf }) => Number(balanceOf) > 0);
  
  portfolioTable.innerHTML = `<tr><th>Synth</th><th>Balance</th><th>USD value</th><th>Percentage</th></tr>`;
  
  holdings.sort((a, b) => Number(a.balanceInUSD) > Number(b.balanceInUSD) ? -1 : 1).forEach(({ synthKey, balanceOf, balanceInUSD, percentage }) => {
    portfolioTable.innerHTML += `<tr><td>${synthKey}</td><td>${Number(balanceOf).toFixed(4)}</td><td>$${Number(balanceInUSD).toFixed(2)}</td><td>${Number(percentage * 100).toFixed(2)}</td></tr>`;
  });
  
  // summary row
  portfolioTable.innerHTML += `<tr><td></td><td>Total USD</td><td>${Number(totalInPortfolio).toFixed(2)}</td><td></td></tr>`;

  const chart1 = new frappe.Chart(chartPortfolioContainer, {  
    data: {
      labels: holdings.map(({ synthKey }) => synthKey),
      datasets: [
          {
              name: "Synth Portfolio", 
              values: holdings.map(({ balanceInUSD }) => Number((balanceInUSD / totalInPortfolio * 100).toFixed(2)))
          }
      ]
    },
    type: 'percentage'
  });
      
  
  // show debt balance over time chart
  const currentBlockNumber = await snxjs.ethers.getDefaultProvider().getBlockNumber();
  const blocks = [];
  let debtBalances = [];

  for (let i = 0; i < 10; i++) {
    blocks.push(currentBlockNumber - (i*10000)); // about a day ago
  }

  debtBalances = (await Promise.all(blocks.map(blockTag => snxjs.Synthetix.contract.debtBalanceOf(account, formatBytes32String('sUSD'), { blockTag })))).map(snxjs.utils.formatEther);


  const chart2 = new frappe.Chart(chartTrendingDebtContainer, {  
    title: "Debt balance over time",
    data: {
      labels: blocks.reverse(),
      datasets: [
          {
              name: "Debt Balance", type: "line",
              values: debtBalances.reverse()
          }
      ]
    },
    type: 'line', 
    height: 250,
    colors: ['#7cd6fd', '#743ee2']
  });
  
};

              
            
!
999px

Console