All files / src index.ts

14.18% Statements 20/141
16.66% Branches 9/54
21.42% Functions 3/14
13.57% Lines 19/140

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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 48234x                     1x 1x   1x 1x 1x   2x   1x           1x                             1x                                           1x   1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1x  
import {
    AbstractTransactPlugin,
    Action,
    API,
    Asset,
    prependAction,
    ResolvedSigningRequest,
    SigningRequest,
    TransactContext,
    TransactHookResponse,
    TransactHookTypes,
} from '@wharfkit/session'
import {Resources, SampleUsage} from '@wharfkit/resources'
 
import {getException} from './exception'
import {Buyrambytes, Powerup} from './types'
import defaultTranslations from './translations'
 
enum ChainFeatures {
    /** eosio.buyram / eosio.buyrambytes https://github.com/EOSIO/eosio.contracts/blob/master/contracts/eosio.system/src/delegate_bandwidth.cpp#L43 */
    BuyRAM,
 
    /** FIO Bundled Transactions https://fio.wiki/knowledge-base/protocol/bundling-and-fees/ */
    // FIOBundledFees, // NYI
 
    /** eosio.powerup https://github.com/EOSIO/eosio.contracts/pull/397 */
    PowerUp,
 
    /** eosio.rentcpu / eosio.rentnet https://github.com/EOSIO/eosio.contracts/blob/master/contracts/eosio.system/src/powerup.cpp */
    // REX, // NYI
 
    /** eosio.delegatebw https://github.com/EOSIO/eosio.contracts/blob/master/contracts/eosio.system/src/delegate_bandwidth.cpp#L372 */
    // Staking, // NYI
}
 
interface ChainConfig {
    features: ChainFeatures[]
    sampleAccount: string
    symbol: Asset.Symbol
}
 
const chains: Record<string, ChainConfig> = {
    // EOS
    aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906: {
        features: [ChainFeatures.BuyRAM, ChainFeatures.PowerUp],
        sampleAccount: 'eosio.reserv',
        symbol: Asset.Symbol.from('4,EOS'),
    },
    // Jungle 4
    '73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d': {
        features: [ChainFeatures.BuyRAM, ChainFeatures.PowerUp],
        sampleAccount: 'eosio.reserv',
        symbol: Asset.Symbol.from('4,EOS'),
    },
    // WAX
    '1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4': {
        features: [ChainFeatures.BuyRAM, ChainFeatures.PowerUp],
        sampleAccount: 'boost.wax',
        symbol: Asset.Symbol.from('8,WAX'),
    },
}
 
/** Multiply all resource purchases to provide extra based on inaccurate estimates */
const multiplier = 1.5
 
export class TransactPluginAutoCorrect extends AbstractTransactPlugin {
    public id = 'transact-plugin-autocorrect'
    public translations = defaultTranslations
    public sample: SampleUsage | null = null
    public price: Asset | null = null
    public resources: string[] = []
    public iterations = 0
 
    register(context: TransactContext): void {
        Iif (!context.ui) {
            throw new Error('The TransactPluginAutoCorrect plugin requires a UI to be present.')
        }
        context.addHook(
            TransactHookTypes.beforeSign,
            async (
                request: SigningRequest,
                context: TransactContext
            ): Promise<TransactHookResponse> => this.run(request, context)
        )
    }
 
    async run(request: SigningRequest, context: TransactContext): Promise<TransactHookResponse> {
        // Abort if no UI is present
        Iif (!context.ui) {
            return {request}
        }
 
        // Reset internal state between transactions
        this.price = null
        this.resources = []
        this.iterations = 0
 
        // Retrieve translation helper from the UI, passing the app ID
        const t = context.ui.getTranslate(this.id)
 
        // Notifify the UI that we are checking the transaction
        const checkingPromise = context.ui
            .prompt({
                title: t('checking', {default: 'Checking transaction'}),
                body: '',
                elements: [],
            })
            .catch((error) => {
                // Throw if what we caught was a cancelation
                Iif (error) {
                    throw error
                }
                // Otherwise return the original if no error occurred but this was rejected
                return {request}
            })
 
        // Retrieve account data for the current account
        const account = await context.client.v1.chain.get_account(context.permissionLevel.actor)
 
        // Attempt to correct this transaction
        const correctedPromise = this.correct(request, context, account)
 
        const modified = await Promise.race([checkingPromise, correctedPromise])
 
        // If the request wasn't modified and no price exists, just return
        Iif (modified === request && !this.price) {
            return {request}
        }
 
        // Create unique set of resources that will be purchased
        const resources = Array.from(new Set(this.resources)).join('/')
 
        // Initiate a new cancelable prompt to inform the user of the fee required
        return context.ui
            .prompt({
                title: t('fee.title', {default: 'Accept Transaction Fee?'}),
                body: t('fee.body', {
                    default:
                        'Additional resources ({{resource}}) are required for your account to perform this transaction. Would you like to automatically purchase these resources from the network and proceed?',
                    resource: resources,
                }),
                elements: [
                    {
                        type: 'asset',
                        data: {
                            label: t('fee.cost', {
                                default: 'Cost of {{resource}}',
                                resource: resources,
                            }),
                            value: this.price,
                        },
                    },
                    {
                        type: 'accept',
                    },
                ],
            })
            .then(() => ({request: modified as SigningRequest}))
            .catch((error) => {
                // Throw if what we caught was a cancelation
                Iif (error) {
                    throw error
                }
                // Otherwise return the original if no error occurred but this was rejected
                return {request}
            })
    }
 
    async correct(
        request: SigningRequest,
        context: TransactContext,
        account: API.v1.AccountObject
    ): Promise<SigningRequest> {
        // TODO: Remove this once we are confident it won't create infinite loops against bad APIs
        // Keep track of how many interations have been done
        this.iterations++
        Iif (this.iterations > 3) {
            throw new Error('Too many iterations. Please report this bug if you see it.')
        }
 
        // If the chain is not configured to correct issues or no UI is present, abort.
        const config = chains[String(context.chain.id)]
        Iif (!config || !context.ui) {
            return request
        }
 
        // Set instance of resource library
        const resources = new Resources({
            api: context.client,
            sampleAccount: config.sampleAccount,
        })
 
        // Resolve any placeholders and complete the transaction for compute.
        const resolved = await context.resolve(request)
 
        // Call compute_transaction against the resolved transaction to detect any issues.
        return context.client.v1.chain
            .compute_transaction(resolved.transaction)
            .then((response) => {
                // Extract any exceptions from the response
                const exception = getException(response)
                // Handling of exception when no error is thrown
                Iif (exception && exception.stack && typeof exception.stack[0] === 'object') {
                    switch (exception.name) {
                        case 'tx_net_usage_exceeded': {
                            const {net_usage} = exception.stack[0].data
                            const needed = net_usage * multiplier
                            Iif (config.features.includes(ChainFeatures.PowerUp)) {
                                return this.powerup(
                                    context,
                                    resolved,
                                    account,
                                    resources,
                                    0,
                                    needed
                                )
                            }
                            break
                        }
                        case 'tx_cpu_usage_exceeded': {
                            const {billed, billable} = exception.stack[0].data
                            const needed = (billed - billable) * multiplier
                            Iif (config.features.includes(ChainFeatures.PowerUp)) {
                                return this.powerup(
                                    context,
                                    resolved,
                                    account,
                                    resources,
                                    needed,
                                    0
                                )
                            }
                            break
                        }
                        case 'ram_usage_exceeded': {
                            const {available, needs} = exception.stack[0].data
                            const needed = (needs - available) * multiplier
                            Iif (config.features.includes(ChainFeatures.BuyRAM)) {
                                return this.buyram(context, resolved, account, resources, needed)
                            }
                            break
                        }
                        default: {
                            // no errors detected
                            break
                        }
                    }
                }
                return request
            })
            .catch((response) => {
                // Extract any exceptions from the response
                Iif (response.error) {
                    // Handling of exception when it is thrown
                    switch (response.error.name) {
                        case 'tx_net_usage_exceeded': {
                            const [, net_usage] = response.error.details[0].message.match(
                                /transaction net usage is too high: (\d+) > (\d+)/
                            )
                            const needed = Number(net_usage) * multiplier
                            Iif (config.features.includes(ChainFeatures.PowerUp)) {
                                return this.powerup(
                                    context,
                                    resolved,
                                    account,
                                    resources,
                                    0,
                                    needed
                                )
                            }
                            break
                        }
                        case 'tx_cpu_usage_exceeded': {
                            const [, cpu_usage] = response.error.details[0].message.match(
                                /billed CPU time \((\d+) us\) is greater than the maximum billable CPU time for the transaction/
                            )
                            const needed = Number(cpu_usage) * multiplier
                            Iif (config.features.includes(ChainFeatures.PowerUp)) {
                                return this.powerup(
                                    context,
                                    resolved,
                                    account,
                                    resources,
                                    needed,
                                    0
                                )
                            }
                            break
                        }
                        case 'ram_usage_exceeded': {
                            const [, , needs, has] = response.error.details[0].message.match(
                                /account (\w.+) has insufficient ram; needs (\d+) bytes has (\d+) bytes/
                            )
                            const needed = (Number(needs) - Number(has)) * multiplier + 2
                            Iif (config.features.includes(ChainFeatures.BuyRAM)) {
                                return this.buyram(context, resolved, account, resources, needed)
                            }
                            break
                        }
                        default: {
                            // an unknown error was detected
                            console.log('unknown error', response) // eslint-disable-line no-console
                            break
                        }
                    }
                }
                // Return the request
                return request
            })
    }
    async buyram(
        context: TransactContext,
        resolved: ResolvedSigningRequest,
        account: API.v1.AccountObject,
        resources: Resources,
        needed: number
    ): Promise<SigningRequest> {
        // Get state of the blockchain and determine RAM price
        const config = chains[String(context.chain.id)]
        const ram = await resources.v1.ram.get_state()
        Iif (!this.sample) {
            this.sample = await resources.getSampledUsage()
        }
 
        // Determine price of resources
        const price = Asset.from(ram.price_per(needed).value, config.symbol)
 
        // Keep a running total of the price
        if (this.price) {
            this.price.units.add(price.units)
        } else {
            this.price = price
        }
 
        // And which resources are being paid for by this fee
        this.resources.push('RAM')
 
        // TODO: Implement maximum RAM fee to ensure potential bugs don't cause massive fees
        // How to determine a normal price per network?
        // const maxFee = 1
        // if (this.price.value > maxFee) {
        //     throw new Error('Fee is too high')
        // }
 
        // Create a new buyrambytes action to append
        const newAction = Action.from({
            account: 'eosio',
            name: 'buyrambytes',
            authorization: [resolved.signer],
            data: Buyrambytes.from({
                payer: resolved.signer.actor,
                receiver: resolved.signer.actor,
                bytes: needed,
            }),
        })
 
        // Create a new request based on this full transaction
        const newRequest = prependAction(resolved.request, newAction)
 
        // Attempt to correct the new request
        return this.correct(newRequest, context, account)
    }
 
    async powerup(
        context: TransactContext,
        resolved: ResolvedSigningRequest,
        account: API.v1.AccountObject,
        resources: Resources,
        cpu: number,
        net: number
    ): Promise<SigningRequest> {
        // Get state of the blockchain and determine powerup price
        const config = chains[String(context.chain.id)]
        const powerup = await resources.v1.powerup.get_state()
        Iif (!this.sample) {
            this.sample = await resources.getSampledUsage()
        }
 
        // If powering up, always set a minimum to avoid API speed variance
        Iif (cpu < 2500) {
            cpu = 2500
        }
 
        Iif (net < 10000) {
            net = 10000
        }
 
        // Determine price of resources
        const minPriceValue = Number(Asset.fromUnits(1, config.symbol).value)
 
        let cpuPrice: number
        try {
            cpuPrice = Number(powerup.cpu.price_per(this.sample, cpu))
        } catch {
            cpuPrice = cpu > 0 ? minPriceValue : 0
        }
 
        let netPrice: number
        try {
            netPrice = Number(powerup.net.price_per(this.sample, net))
        } catch {
            netPrice = net > 0 ? minPriceValue : 0
        }
 
        const price = Asset.from(cpuPrice + netPrice * multiplier, config.symbol)
 
        // Keep a running total of the price
        if (this.price) {
            this.price.units.add(price.units)
        } else {
            this.price = price
        }
 
        // And which resources are being paid for by this fee
        this.resources.push('CPU', 'NET')
 
        // TODO: Implement maximum RAM fee to ensure potential bugs don't cause massive fees
        // How to determine a normal price per network?
        // const maxFee = 1
        // if (this.price.value > maxFee) {
        //     throw new Error('Fee is too high')
        // }
 
        // Create a new powerup action to append
        const newAction = Action.from({
            account: 'eosio',
            name: 'powerup',
            authorization: [resolved.signer],
            data: Powerup.from({
                payer: resolved.signer.actor,
                receiver: resolved.signer.actor,
                days: 1,
                net_frac: powerup.net.frac(this.sample, net),
                cpu_frac: powerup.cpu.frac(this.sample, cpu),
                max_payment: price,
            }),
        })
 
        // Create a new request based on this full transaction
        let modifiedRequest = prependAction(resolved.request, newAction)
 
        // Determine if the account has enough RAM to powerup
        const ram_needed = 410 // 405 appears to be the exact amount, but purchase an additional small buffer
        Iif (Number(account.ram_quota) - Number(account.ram_usage) < ram_needed) {
            // Get state of the blockchain and determine RAM price
            const config = chains[String(context.chain.id)]
            const ram = await resources.v1.ram.get_state()
            Iif (!this.sample) {
                this.sample = await resources.getSampledUsage()
            }
 
            // Create a new buyrambytes action to append
            const ramAction = Action.from({
                account: 'eosio',
                name: 'buyrambytes',
                authorization: [resolved.signer],
                data: Buyrambytes.from({
                    payer: resolved.signer.actor,
                    receiver: resolved.signer.actor,
                    bytes: ram_needed,
                }),
            })
 
            // Modify the account object to prevent multiple purchases during recurrsion
            account.ram_quota.add(ram_needed)
 
            // Modify the request
            modifiedRequest = prependAction(modifiedRequest, ramAction)
 
            // Determine price of resources
            const ramPrice = Asset.from(ram.price_per(ram_needed).value, config.symbol)
            this.price.units.add(ramPrice.units)
 
            // Notify that RAM is also being purchased
            this.resources.push('RAM')
        }
 
        // Attempt to correct the new request
        return await this.correct(modifiedRequest, context, account)
    }
}