Tron

JellySwap tron package

What is JellySwap?

JellySwap is a cross-chain atomic swap protocol that supports many different blockchains. The tron package is used to interact with the Tron Hash Time Locked Contracts and to handle blockchain events. The main components of the module are Providers, Contract, Event, Adapter and Config.

Install package

Using yarn

$ yarn add @jelly-swap/tron

Using npm

$ npm install @jelly-swap/tron

Importing

JavaScript (ES3)

const jellyTron = require('@jelly-swap/tron');

JavaScript (ES6) / TypeScript

import * as jellyTron from '@jelly-swap/tron';

Config Module

This module contains the main configuration for the whole package.

const config = jellyTron.Config(expiration?);

//Expected output
{
  network: 'TRX',
  explorer: 'https://shasta.tronscan.org/#/transaction/',
  providerUrl: 'https://api.shasta.trongrid.io/',
  contractAddress: 'TPASPFmeWcPcF5CR668P5dgrzK99ELb3pV',
  receiverAddress: '4192cf62d8c6dd4ebbd9547f41822591a10d21dcf5',
  blockTime: 3,
  expiration,
  decimals: 6,
  unix: true,
}

parameter

type

description

expiration

number

The Time Lock of the transaction. Optional

Provider Module

A Provider abstracts a connection to the Tron blockchain, for issuing queries and sending signed state changing transactions.

HttpProvider - allows you to connect to Tron nodes you control or have access to, including mainnet, testnets, proof-of-authority (PoA) nodes or Ganache by providing a URL to the node.

const httpProvider = new jellyTron.Providers.HttpProvider(address?, providerUrl?);

parameter

type

description

address

string

Public tron address. Optional.

providerUrl

string

Can be trongrid or other provider on testnet or mainnet. Optional.

TronlinkProvider - used with tronWeb application, or tronWeb-compatible Provider.

const tronLinkProvider = new jellyTron.Providers.TronlinkProvider(tronWeb);

parameter

type

description

tronWeb

object

Can be any tronWeb provider like the one from Tronlink.

WalletProvider - manages a private/public key pair which is used to cryptographically sign transactions and prove ownership on the Tron network. Use when there is no tronWebProvider available.

const walletProvider = new jellyTron.Providers.WalletProvider(privateKey, providerUrl?)

parameter

type

description

privateKey

string

Tron Private Key.

providerUrl

string

Can be trongrid or other provider on testnet or mainnet. Optional.

Contract Module

Contract module is used to interact with the Solidity Contract and get blockchain specific data (balance, blockNumber, subscribe to events, get past events).

Create contract instance:

const tronContract = new jellyTron.Contract(provider);

parameter

type

description

provider

object

Provider instance that will be used for transaction signing.

subscribe

await tronContract.subscribe(onEvent, filter?);

parameter

type

description

onEvent

function

Called when an event is received.

filter

function

Used to filter any received event. Optional.

getPastEvents

Returns past blockchain events.

const pastEvents = await tronContract.getPastEvents(eventType, filter?);

parameter

type

description

eventType

string

can be 'new', 'withdraw' or 'refund'

filter

function

Filter the received events.

Optional. If not passed all events will be returned.

getCurrentBlock

Returns the latest block.

const currentBlock = await tronContract.getCurrentBlock();

getBalance

Returns the balance of the given address.

const balance = await tronContract.getBalance(address);

parameter

type

description

address

string

Tron Public Address.

getStatus

Returns the swaps statuses by given ids.

const statuses = await tronContract.getStatus(ids);

parameter

type

description

ids

array

List of ids.

newContract

Creates and broadcasts a new swap transaction.

const transactionHashSwap = await tronContract.newContract(swap);

parameter

type

description

swap

TronContractSwap

Input data for the swap.

withdraw

Creates and broadcasts a withdraw transaction.

const transactionHashWithdraw = await tronContract.withdraw(withdraw);

parameter

type

description

withdraw

ContractWithdraw

Input data for the withdraw.

refund

Creates and broadcasts a refund transaction.

const transactionHashRefund = await tronContract.refund(contractRefund);

parameter

type

description

contractRefund

ContractRefund

Input data for the refund.

Event module

Event module is used to read past blockchain events and subscribe for new ones.

Initialize event module:

const tronEvents = new jellyTron.Event(tronContract);

parameter

type

description

tronContract

object

Tron contract instance.

getPast

Returns past blockchain events.

const pastEvents = await tronEvents.getPast(eventType, filter?, currentBlock?);

parameter

type

description

eventType

string

can be 'new', 'withdraw' or 'refund'

filter

function

Filter the received events.

Optional. If not passed all events will be returned.

currentBlock

number

Read events up to the currentBlock. Optional. If not passed the currentBlock will be assigned to the latest mined block.

subscribe

await tronEvents.subscribe(onEvent, filter?);

parameter

type

description

onEvent

function

Called when an event is received.

filter

function

Used to filter any received event. Optional.

Adapter module

The Adapter module is used to format the client data and prepare the input for the swaps.

Initialize adapter module:

const tronAdapter = new jellyTron.Adapter();

generateId

Generate swap id based on the input parameters. The same id will be generated by the Solidity Contract.

const id = tronAdapter.generateId(input);

parameter

type

description

input

ContractSwap

Input data for the swap.

addressValid

Checks if the passed address is valid or not.

const isAddressValid = tronAdapter.addressValid(address);

parameter

type

description

address

string

True if address is valid.

parseAddress

Returns the address in lower case.

const addressParsed = tronAdapter.parseAddress(address);

parameter

type

description

address

string

Address in lower case.

parseOutputAddress

Returns tron address in hex format

const tronHex = tronAdapter.parseOutputAddress(address);

parameters

type

description

address

string

Public tron address.

parseToNative

Parse tron amount to sun amount i.e. 1 to 1000000

const result = tronAdapter.parseToNative(amount);

parameter

type

description

amount

number

String representation of the sun amount.

parseFromNative

Parse sun amount to tron amount i.e. 1000000 to 1

const result = tronAdapter.parseFromNative(amount);

parameter

type

description

amount

BigNumberish

String representation of the tron amount.

formatInput

Returns object of type UserInputSwap.

const swapInput = tronAdapter.formatInput(data, receiver?);

parameter

type

description

data

UserInputSwap

User input data.

receiver

string

Address of the receiver. Optional. If not passed uses the receiver from the config.

Example

const jellyTron = require('@jelly-swap/erc20');

const provider = new jellyTron.Providers.WalletProvider('Tron_PRIVATE_KEY');

const tronContract = new jellyTron.Contract(provider);

const adapter = new jellyTron.Adapter();

async function start() {
    // Subscribe for contract events and pass handle function
    await tronContract.subscribe(e => {
        console.log(e);
    });


    // Get past blockchain events
    const swaps = await tronContract.getPastEvents('new', s => s);
    console.log(swaps);
    // [
    //  {
    //    network: 'TRX',
    //    eventName: 'NEW_CONTRACT',
    //    id: '0x337580a14c3479b47a64d9c29a2c84cf4a6dbbf52a6289a9a74551ed17814d03',
    //    receiver: 'TNT2qGatAynq1wntM7d61eawUHjHENzPCX',
    //    sender: 'TPMU6WL5yhDEiKkiifT4P8dK979AsB47PU',
    //    transactionHash: 'bdf08c2544d13bfb1313fa592d52d788a5289d8bf3fc064cb67c446f2bb5da6a',
    //    expiration: '1578391213',
    //    inputAmount: '97944919',
    //    outputAmount: '10000000000000000',
    //    outputNetwork: 'ETH',
    //    hashLock: '0x93b6f6868ac6c0e19b7b6711dc67a10f3aae54d7044afcdfd99b3bdf8092eae2',
    //    outputAddress: '0xF684C21Ec023E93da0B402ac0a274317eb51C2c7',
    //    status: 2
    //  },
    // ];

  
    const withdraws = await tronContract.getPastEvents('withdraw', w => w);
    console.log(withdraws);
    // [
      //    {
      //      network: 'TRX',
      //      eventName: 'WITHDRAW',
      //      id: '0x17b7ad912c2d9fd08121ee52f7b98898c496ef98d8080f931018f296f8fe946e',
      //      hashLock: '0x4c5b9f0fc5b7e9fb486c2192842d522c19c4f2f300f750037cfe5fb717b072d0',
      //      sender: 'tftzu6xmosstxebdigew1ggpvz7kpnflvd',
      //      receiver: 'tpmu6wl5yhdeikkiift4p8dk979asb47pu',
      //      secret: '0x6b09bc23fe2c8269bf59faa6e4330d259fbe21318a3f761202d3a268cc34f631',
      //      transactionHash: '47ef2be1836337674cd1ed1d95a6bb73d88732ee3590641e2211205173f4fcfe'
      //    },
    // ];


    const refunds = await tronContract.getPastEvents('refund', r => r);
    console.log(refunds);
    // [
      //    {
      //      network: 'TRX',
      //      eventName: 'REFUND',
      //      id: '0xc918098376ae04ee7a0c50eb92c926972f38a25ef35db2923b84ebeca0c17395',
      //      hashLock: '0x15974209c6bde2f2e287f6342913d594eb7d1d0333e7969ce5fd387f8d5189c9',
      //      sender: 'tpmu6wl5yhdeikkiift4p8dk979asb47pu',
      //      receiver: 'tmfb44bfbnnbhqrfj9btvp4lsqjyz6zfjv',
      //      transactionHash: '8462bd41d3779e945adca4ede28e101268a28c6d63eb133371e7a9839e82c18c'
      //    },
    // ];


    const currentBlock = await tronContract.getCurrentBlock();
    console.log(currentBlock);
    // 989132


    const balance = await tronContract.getBalance('TC79CuodSV61YfxbWrThRUszdj49JEceLg');
    console.log(balance);
    // 1000000


    const statuses = await tronContract.getStatus([
        '0x17b7ad912c2d9fd08121ee52f7b98898c496ef98d8080f931018f296f8fe946e', 
        '0xc918098376ae04ee7a0c50eb92c926972f38a25ef35db2923b84ebeca0c17395'
    ]);
    console.log(statuses);
    // [2, 3]

    // ACTIVE: 1,
    // REFUNDED: 2,
    // WITHDRAWN: 3,
    // EXPIRED: 4




    // ================ SWAP ================
    const userInputSwap = {
        inputAmount: '10',
        network: 'TRX',
        outputAddress: '0xB7B4043aD3E6986D39f344c551AA78266Fb140D2',
        outputAmount: '1000000000000000000',
        outputNetwork: 'DAI',
        secret: 'pond cram isolate chair float moon tongue firm spirit hand peace together',
        sender: '0x7bc272693510354a84e1632cca005253dbb08d16',
    };
    
    const swap = adapter.formatInput(userInputSwap);
    console.log(swap);
    //  {
    //    inputAmount: '10000000',
    //    network: 'TRX',
    //    outputAddress: '0xB7B4043aD3E6986D39f344c551AA78266Fb140D4',
    //    outputAmount: '1000000000000000000',
    //    outputNetwork: 'DAI',
    //    secret: 'pond cram isolate chair float moon tongue firm spirit hand peace together',
    //    sender: '0x7bc272693510354a84e1632cca005253dbb08d18',
    //    expiration: 1578501147,
    //    hashLock: '0x4af116ee28ecde1d2b71e49fb964fe76a20c694c94f6895c1baa8ed1d1b06dda',
    //    receiver: '4192cf62d8c6dd4ebbd9547f41822591a10d21dcf5',
    //    options:{
    //        feeLimit: 100000000,
    //        callValue: '10000000',       
    //        shouldResponse: false        
    //    }           
    //  }

    //broadcast swap transaction
    const swapHash = await tronContract.newContract(swap);
    console.log(swapHash);
    // 372dbfa7670f4e881d9303ca7b776d0dbe48137ef9d35be122db1fe482f8cdbe




    // ================ REFUND ================

    const refund = {
        id: '0xfa033fb78799f986cffba5e965db049d8da4f9764e6b791cb8aeb6df842c0e52',
    };

    const refundHash = await tronContract.refund(refund);
    console.log(refundHash);
    // 372dbfd7670f4e881d9303ca7b776d0dbe48137ef9d35be122db1fe482f8cdb6

    
    
    
    // ================ WITHDRAW ================

    const withdraw = {
        id: '0xfa033fb78799f986cffba5e965db049d8da4f9764e6b791cb8aeb6df842c0e54',
        secret: '0x307afe7a1a9bc9f94b7bf5b091441bac10222f4c797ee4441cb213aae7ac18a2',
    };

    const withdrawHash = await tronContract.withdraw(withdraw);
    console.log(withdrawHash);
    // d03a181ff6674b655f8e194ed4a9348127deda261d68e1fc3f48b6319aa6649f
}

Last updated