All files / src index.ts

96.29% Statements 26/27
83.33% Branches 15/18
100% Functions 7/7
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 7942x 1x   1x             1x           1x 1x 1x           6x 1x   5x       1x   1x   1x                         5x 5x       5x 3x       2x     5x   5x 2x     3x       3x     2x     1x  
import {Action, APIClient, Asset, AssetType, Name, NameType} from '@wharfkit/antelope'
import {Contract, ContractKit} from '@wharfkit/contract'
 
import * as SystemTokenContract from './contracts/system.token'
 
interface TokenOptions {
    client: APIClient
    contract?: Contract
}
 
export class Token {
    client: APIClient
    contractKit: ContractKit
    contract: Contract
 
    constructor({client, contract}: TokenOptions) {
        this.client = client
        this.contract = contract || new SystemTokenContract.Contract({client})
        this.contractKit = new ContractKit({
            client: client,
        })
    }
 
    async getContract(contractName?: NameType) {
        if (contractName) {
            return this.contractKit.load(contractName)
        }
        return this.contract
    }
 
    async transfer(from: NameType, to: NameType, amount: AssetType, memo = ''): Promise<Action> {
        const quantity = Asset.from(amount)
 
        const contract = await this.getContract()
 
        return contract.action('transfer', {
            from: Name.from(from),
            to: Name.from(to),
            quantity,
            memo,
        })
    }
 
    async balance(
        accountName: NameType,
        symbolCode?: Asset.SymbolCodeType,
        contractName?: NameType
    ): Promise<Asset> {
        const contract = await this.getContract(contractName)
        const table = contract.table('accounts', accountName)
 
        let tableQuery
 
        if (symbolCode) {
            tableQuery = table.get(Asset.SymbolCode.from(symbolCode).value, {
                index_position: 'primary',
            })
        } else {
            tableQuery = table.get()
        }
 
        return tableQuery
            .then((accountBalance) => {
                if (!accountBalance) {
                    throw new Error(`Account ${accountName} does not exist.`)
                }
 
                Iif (symbolCode && !accountBalance.balance.symbol.code.equals(symbolCode)) {
                    throw new Error(`Symbol '${symbolCode}' does not exist.`)
                }
 
                return accountBalance?.balance
            })
            .catch((err) => {
                throw new Error(`Failed to fetch balance for ${accountName}: ${err}`)
            })
    }
}