All files / src accounts.ts

80% Statements 36/45
68.75% Branches 11/16
70.83% Functions 17/24
80% Lines 36/45

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 2201x 1x     1x 1x 1x                                           1x             15x     15x 15x 15x         14x       12x       1x       3x   2x                                                                                                                                                 2x 2x   1x                   1x           4x 4x     3x   3x 1x                 3x     1x       1x               1x           7x 7x               7x     4x 4x 4x     3x 3x                          
import {API, APIClient, Asset, AssetType, Checksum256, Name, NameType} from '@greymass/eosio'
import {ChainId, ChainName} from 'anchor-link'
import type {ChainIdType} from 'anchor-link'
 
import {PermissionActions} from './accounts/actions/permissions'
import {Permission} from './permissions'
import {ResourceActions} from './accounts/actions/resources'
 
// import type { Session } from '@wharfkit/session'
 
// Remove these when Contract and Session are used
export interface Session {
    [key: string]: any
}
 
export interface SessionTransactResult {
    id: Checksum256
}
 
export interface Resources {
    cpu_available: number
    cpu_used: number
    net_available: number
    net_used: number
    ram_quota: number
    ram_usage: number
}
 
export class Account {
    account_name: Name
    chain_id: ChainId
    api_client: APIClient
    account_data: API.v1.AccountObject | undefined
    account_data_timestamp: number | undefined
    // contract: Contract | undefined
    cache_duration: number = 1000 * 60 * 5 // 5 minutes
 
    constructor(accountName: Name, chainId: ChainId, apiClient: APIClient) {
        this.account_name = accountName
        this.chain_id = chainId
        this.api_client = apiClient
        // this.contract = new Contract(chainId, this, options?.session)
    }
 
    static from(accountName: NameType, chain: ChainIdType, apiClient: APIClient): Account {
        return new Account(Name.from(accountName), ChainId.from(chain), apiClient)
    }
 
    get accountName(): Name {
        return this.account_name
    }
 
    get chainId(): ChainId {
        return this.chain_id
    }
 
    async getPermission(permissionName: NameType): Promise<Permission | undefined> {
        const accountData = await this.getAccountData()
 
        return Permission.from({permissionName, accountData})
    }
 
    updatePermission(
        permission: Permission,
        {session}: {session: Session}
    ): Promise<SessionTransactResult> {
        return PermissionActions.shared().updateAuth(permission.actionData, {
            account: this,
            session,
        })
    }
 
    removePermission(
        permissionName: NameType,
        {session}: {session: Session}
    ): Promise<SessionTransactResult> {
        return PermissionActions.shared().deleteAuth(
            Name.from(permissionName),
            Name.from(this.account_name),
            {account: this, session}
        )
    }
 
    buyRam(amount: AssetType, {session}: {session: Session}): Promise<SessionTransactResult> {
        return ResourceActions.shared().buyRam(this.accountName, this.accountName, amount, {
            account: this,
            session,
        })
    }
 
    buyRamBytes(bytes: number, {session}: {session: Session}): Promise<SessionTransactResult> {
        return ResourceActions.shared().buyRamBytes(this.accountName, this.accountName, bytes, {
            account: this,
            session,
        })
    }
 
    sellRam(bytes: number, {session}: {session: Session}): Promise<SessionTransactResult> {
        return ResourceActions.shared().sellRam(this.accountName, bytes, {account: this, session})
    }
 
    delegateResources(
        cpu: AssetType,
        net: AssetType,
        transfer: boolean,
        {session}: {session: Session}
    ): Promise<SessionTransactResult> {
        return ResourceActions.shared().delegateResources(
            this.accountName,
            this.accountName,
            net,
            cpu,
            transfer,
            {account: this, session}
        )
    }
 
    undelegateResources(
        cpu: AssetType,
        net: AssetType,
        {session}: {session: Session}
    ): Promise<SessionTransactResult> {
        return ResourceActions.shared().undelegateResources(
            this.accountName,
            this.accountName,
            cpu,
            net,
            {account: this, session}
        )
    }
 
    async getResources(): Promise<Resources> {
        return new Promise((resolve, reject) => {
            this.getAccountData()
                .then((accountData) => {
                    resolve({
                        net_available: Number(accountData.net_limit.available),
                        net_used: Number(accountData.net_limit.available),
                        cpu_available: Number(accountData.cpu_limit.available),
                        cpu_used: Number(accountData.cpu_limit.used),
                        ram_quota: Number(accountData.ram_quota),
                        ram_usage: Number(accountData.ram_usage),
                    })
                })
                .catch((err) => {
                    reject(err)
                })
        })
    }
 
    getBalance(contract: NameType = 'eosio.token', symbol?: Asset.SymbolType): Promise<Asset> {
        return new Promise((resolve, reject) => {
            this.api_client.v1.chain
                .get_currency_balance(contract, String(this.accountName), symbol && String(symbol))
                .then((balances) => {
                    const balance = (balances as any)[0]
 
                    if (!balance) {
                        reject(
                            new Error(
                                `No balance found for ${symbol} token of ${contract} contract on chain ${
                                    ChainName[this.chain_id.chainName]
                                }.`
                            )
                        )
                    }
 
                    resolve(balance)
                })
                .catch((err) => {
                    Eif (
                        err.message.includes('No data') ||
                        err.message.includes('Account Query Exception')
                    ) {
                        reject(
                            new Error(
                                `Token contract ${contract} does not exist on chain ${
                                    ChainName[this.chain_id.chainName]
                                }.`
                            )
                        )
                    }
                    reject(err)
                })
        })
    }
 
    getAccountData(): Promise<API.v1.AccountObject> {
        return new Promise((resolve, reject) => {
            Iif (
                this.account_data &&
                this.account_data_timestamp &&
                this.account_data_timestamp + this.cache_duration > Date.now()
            ) {
                return resolve(this.account_data)
            }
 
            this.api_client.v1.chain
                .get_account(String(this.accountName))
                .then((accountData) => {
                    this.account_data = accountData
                    this.account_data_timestamp = Date.now()
                    resolve(accountData)
                })
                .catch((error) => {
                    Eif (error.message.includes('Account not found')) {
                        return reject(
                            new Error(
                                `Account ${this.account_name} does not exist on chain ${
                                    ChainName[this.chain_id.chainName]
                                }.`
                            )
                        )
                    }
                    reject(error)
                })
        })
    }
}