All files / src index.ts

67.28% Statements 109/162
53.24% Branches 41/77
66.66% Functions 16/24
68.62% Lines 105/153

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 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514138x                                       1x 1x   1x 1x                                                     1x 1x 1x 1x 1x       1x 1x 1x 1x     1x                         1x 8x 8x 8x             8x     8x 8x   4x 4x   4x 2x   4x 2x                   8x           8x           8x               8x 8x           8x     8x 1x             7x 7x 6x 6x 6x     6x 6x           6x   1x                 7x     7x         7x 7x             6x   1x               6x           6x 6x   4x   1x                   1x             5x   5x         5x                                   5x   5x 8x   8x     8x     8x                               8x                                               5x     8x       3x           5x   8x       5x 5x                       5x 5x   3x 3x           5x 2x   2x                   2x             3x     3x   3x                                                                                                                                       3x 3x   3x           5x           5x                   3x     3x 1x       3x 1x 1x 1x     3x             7x 7x 7x                 3x         3x             3x       1x  
import {
    AbstractTransactPlugin,
    Action,
    Asset,
    AssetType,
    Cancelable,
    Canceled,
    ChainDefinition,
    Name,
    PromptResponse,
    Serializer,
    Signature,
    SigningRequest,
    SigningRequestCreateArguments,
    Struct,
    TransactContext,
    TransactHookResponse,
    TransactHookTypes,
    Transaction,
    UInt32,
} from '@wharfkit/session'
import {Resources} from '@wharfkit/resources'
 
import defaultTranslations from './translations'
import {getNewActions, hasOriginalActions} from './utils'
 
interface ResourceProviderOptions {
    allowFees?: boolean
    // allowActions?: NameType[]
    endpoints?: Record<string, string>
    maxFee?: AssetType
}
 
interface ResourceProviderResponseData {
    request: [string, object]
    signatures: string[]
    version: unknown
    fee?: AssetType
    costs?: {
        cpu: AssetType
        net: AssetType
        ram: AssetType
    }
}
 
interface ResourceProviderResponse {
    code: number
    data: ResourceProviderResponseData
}
 
@Struct.type('transfer')
export class Transfer extends Struct {
    @Struct.field(Name) from!: Name
    @Struct.field(Name) to!: Name
    @Struct.field(Asset) quantity!: Asset
    @Struct.field('string') memo!: string
}
 
@Struct.type('buyrambytes')
export class BuyRAMBytes extends Struct {
    @Struct.field(Name) payer!: Name
    @Struct.field(Name) receiver!: Name
    @Struct.field(UInt32) bytes!: UInt32
}
 
export const defaultOptions = {
    endpoints: {
        aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906:
            'https://eos.greymass.com',
        '73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d':
            'https://jungle4.greymass.com',
        '4667b205c6838ef70ff7988f6e8257e8be0e1284a2f59699054a018f743b1d11':
            'https://telos.greymass.com',
        '1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4':
            'https://wax.greymass.com',
    },
}
 
export class TransactPluginResourceProvider extends AbstractTransactPlugin {
    id = 'transact-plugin-resource-provider'
    translations = defaultTranslations
    readonly allowFees: boolean = true
    // readonly allowActions: Name[] = [
    //     Name.from('eosio.token:transfer'),
    //     Name.from('eosio:buyrambytes'),
    // ]
    readonly maxFee?: Asset
 
    readonly endpoints: Record<string, string> = defaultOptions.endpoints
 
    constructor(options?: ResourceProviderOptions) {
        super()
        if (options) {
            // Set the endpoints and chains available
            if (options.endpoints) {
                this.endpoints = options.endpoints
            }
            if (typeof options.allowFees !== 'undefined') {
                this.allowFees = options.allowFees
            }
            if (typeof options.maxFee !== 'undefined') {
                this.maxFee = Asset.from(options.maxFee)
            }
            // TODO: Allow contact/action combos to be passed in and checked against to ensure no rogue actions were appended.
            // if (typeof options.allowActions !== 'undefined') {
            //     this.allowActions = options.allowActions.map((action) => Name.from(action))
            // }
        }
    }
 
    register(context: TransactContext): void {
        context.addHook(
            TransactHookTypes.beforeSign,
            async (
                request: SigningRequest,
                context: TransactContext
            ): Promise<TransactHookResponse> => {
                return this.request(request, context)
            }
        )
    }
 
    getEndpoint(chain: ChainDefinition): string {
        return this.endpoints[String(chain.id)]
    }
 
    async request(
        request: SigningRequest,
        context: TransactContext
    ): Promise<TransactHookResponse> {
        // Mock the translation function if no UI is available
        let t = (key: string, options: {default: string; [key: string]: unknown}) => options.default
        Iif (context.ui) {
            // Use the translate function if available
            t = context.ui.getTranslate(this.id)
        }
 
        // Determine appropriate URL for this request
        const endpoint = this.getEndpoint(context.chain)
 
        // If no endpoint was found, gracefully fail and return the original request.
        if (!endpoint) {
            return {
                request,
            }
        }
 
        // Resolve the request as a transaction for placeholders + tapos
        let modifiedRequest
        const abis = await request.fetchAbis(context.abiCache)
        if (request.requiresTapos()) {
            const info = await context.client.v1.chain.get_info()
            const header = info.getTransactionHeader(120)
            const modifiedArgs: SigningRequestCreateArguments = {
                transaction: request.resolveTransaction(abis, context.permissionLevel, header),
            }
            modifiedArgs.chainId = request.getChainId()
            Iif (request.isMultiChain()) {
                const ids = request.getChainIds()
                Iif (ids) {
                    modifiedArgs.chainIds = ids
                }
            }
            modifiedRequest = await SigningRequest.create(modifiedArgs, context.esrOptions)
        } else {
            modifiedRequest = await SigningRequest.create(
                {
                    transaction: request.resolveTransaction(abis, context.permissionLevel),
                },
                context.esrOptions
            )
        }
 
        // Validate that this request is valid for the resource provider
        this.validateRequest(modifiedRequest, context)
 
        // Assemble the request to the resource provider.
        const url = `${endpoint}/v1/resource_provider/request_transaction`
 
        // Perform the request to the resource provider.
        let response: Response
        let json: ResourceProviderResponse
        try {
            response = await context.fetch(url, {
                method: 'POST',
                body: JSON.stringify({
                    request: modifiedRequest,
                    signer: context.permissionLevel,
                }),
            })
            json = await response.json()
        } catch {
            return {
                request,
            }
        }
 
        // If the resource provider refused to process this request
        // OR the status isn't an expected 200 or 402,
        // return the original request without modification.
        Iif (response.status === 400 || ![200, 402].includes(response.status)) {
            return {
                request,
            }
        }
 
        const requiresPayment = response.status === 402
        if (requiresPayment) {
            // If the resource provider offered transaction with a fee, but plugin doesn't allow fees, return the original transaction.
            if (!this.allowFees) {
                // Notify that a fee was required but not allowed via allowFees: false.
                Iif (context.ui) {
                    context.ui.status(
                        `${t('rejected.no-fees', {
                            default:
                                'A resource provider offered to cover this transaction for a fee, but fee-based transactions are disabled by the configuration using `allowFees = false`.',
                        })} ${t('will-continue', {
                            default: 'The transaction will continue without the resource provider.',
                        })}`
                    )
                }
                return {
                    request,
                }
            }
        }
 
        // Retrieve the transaction from the response
        const modifiedTransaction = this.getModifiedTransaction(json)
        // Ensure the new transaction has an unmodified version of the original action(s)
        const originalActionsIntact = hasOriginalActions(
            modifiedRequest.getRawTransaction(),
            modifiedTransaction
        )
 
        Iif (!originalActionsIntact) {
            // Notify that the original actions requested were modified somehow, and reject the modification.
            Iif (context.ui) {
                context.ui.status(
                    `${t('rejected.original-modified', {
                        default:
                            'The original transaction returned by the resource provider has been modified too much. Continuing without the resource provider',
                    })} ${t('will-continue', {
                        default: 'The transaction will continue without the resource provider.',
                    })}`
                )
            }
            return {
                request,
            }
        }
 
        // Retrieve all newly appended actions from the modified transaction
        const addedActions = getNewActions(modifiedRequest.getRawTransaction(), modifiedTransaction)
 
        for (const action of addedActions) {
            const isNoop = action.name.equals('noop')
            const isTransfer =
                action.name.equals('transfer') &&
                (action.account.equals('eosio.token') || action.account.equals('core.vaulta'))
            const isBuyRAMBytes =
                action.name.equals('buyrambytes') &&
                (action.account.equals('eosio') || action.account.equals('core.vaulta'))
 
            Iif (!isNoop && !isTransfer && !isBuyRAMBytes) {
                Iif (context.ui) {
                    context.ui.status(
                        `${t('rejected.unexpected-action', {
                            default:
                                'The resource provider added an unexpected action to the transaction.',
                        })} ${t('will-continue', {
                            default: 'The transaction will continue without the resource provider.',
                        })}`
                    )
                }
                return {
                    request,
                }
            }
 
            Iif (isBuyRAMBytes) {
                const decoded = Serializer.decode({
                    data: action.data,
                    type: BuyRAMBytes,
                })
                Iif (!decoded.receiver.equals(context.permissionLevel.actor)) {
                    Iif (context.ui) {
                        context.ui.status(
                            `${t('rejected.invalid-buyrambytes', {
                                default:
                                    'The resource provider added a RAM purchase for an account other than the requesting account.',
                            })} ${t('will-continue', {
                                default:
                                    'The transaction will continue without the resource provider.',
                            })}`
                        )
                    }
                    return {
                        request,
                    }
                }
            }
        }
 
        const transferFees = addedActions
            .filter(
                (action: Action) =>
                    (action.account.equals('eosio.token') && action.name.equals('transfer')) ||
                    (action.account.equals('core.vaulta') && action.name.equals('transfer'))
            )
            .map((action: Action) => {
                return Serializer.decode({
                    data: action.data,
                    type: Transfer,
                }).quantity
            })
 
        const ramActions = addedActions.filter(
            (action: Action) =>
                action.name.equals('buyrambytes') &&
                (action.account.equals('eosio') || action.account.equals('core.vaulta'))
        )
 
        const ramFees: Asset[] = []
        Iif (ramActions.length > 0) {
            const resources = new Resources({api: context.client})
            const ramState = await resources.v1.ram.get_state()
            for (const action of ramActions) {
                const decoded = Serializer.decode({
                    data: action.data,
                    type: BuyRAMBytes,
                })
                ramFees.push(ramState.price_per(Number(decoded.bytes)))
            }
        }
 
        const allFees = [...transferFees, ...ramFees]
        const addedFees = allFees.reduce(
            (total: Asset, fee: Asset) => {
                total.units.add(fee.units)
                return total
            },
            Asset.fromUnits(0, allFees.length > 0 ? allFees[0].symbol : '4,TOKEN')
        )
 
        // If the resource provider offered transaction with a fee, but the fee was higher than allowed, return the original transaction.
        if (this.maxFee) {
            if (addedFees.units > this.maxFee.units) {
                // Notify that a fee was required but higher than allowed via maxFee.
                Iif (context.ui) {
                    context.ui.status(
                        `${t('rejected.max-fee', {
                            default:
                                'The fee requested by the resource provider is unusually high and has been rejected.',
                        })} ${t('will-continue', {
                            default: 'The transaction will continue without the resource provider.',
                        })}`
                    )
                }
                return {
                    request,
                }
            }
        }
 
        // Validate that the response is valid for the session.
        await this.validateResponseData(json)
 
        // Create a new signing request based on the response to return to the session's transact flow.
        const modified = await this.createRequest(json, context)
 
        Iif (context.ui && addedFees.value > 0) {
            // Determine which resources are being covered by this fee
            const resourceTypes: string[] = []
            if (json.data.costs) {
                const {cpu, net, ram} = json.data.costs
                Iif (Asset.from(cpu).value > 0) resourceTypes.push('CPU')
                Iif (Asset.from(net).value > 0) resourceTypes.push('NET')
                Iif (Asset.from(ram).value > 0) resourceTypes.push('RAM')
            } else {
                resourceTypes.push('Unknown')
            }
            // Initiate a new cancelable prompt to inform the user of the fee required
            const prompt: Cancelable<PromptResponse> = 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 and proceed?',
                    resource: String(resourceTypes.join('/')),
                }),
                elements: [
                    {
                        type: 'asset',
                        data: {
                            label: t('fee.cost', {
                                default: 'Cost of {{resource}}',
                                resource: String(resourceTypes.join('/')),
                            }),
                            value: addedFees,
                        },
                    },
                    {
                        type: 'accept',
                    },
                ],
            })
 
            // TODO: Set the timer to match the expiration of the transaction
            const timer = setTimeout(() => {
                prompt.cancel(
                    t('timeout', {default: 'The offer from the resource provider has expired.'})
                )
            }, 120000)
 
            // Return the promise from the prompt
            return prompt
                .then(async () => {
                    // Return the modified transaction and additional signatures
                    return new Promise((r) =>
                        r({
                            request: modified,
                            signatures: json.data.signatures.map((sig) => Signature.from(sig)),
                        })
                    ) as Promise<TransactHookResponse>
                })
                .catch((e) => {
                    // Throw if what we caught was a cancelation
                    Iif (e instanceof Canceled) {
                        throw e
                    }
                    // Otherwise if it wasn't a cancel, it was a reject, and continue without modification
                    return new Promise((r) => r({request})) as Promise<TransactHookResponse>
                })
                .finally(() => {
                    clearTimeout(timer) // TODO: Remove this, it's just here for testing
                })
        }
 
        // Return the modified transaction and additional signatures
        return new Promise((r) =>
            r({
                request: modified,
                signatures: json.data.signatures.map((sig) => Signature.from(sig)),
            })
        )
    }
 
    getModifiedTransaction(json): Transaction {
        switch (json.data.request[0]) {
            case 'action':
                throw new Error('A resource provider providing an "action" is not supported.')
            case 'actions':
                throw new Error('A resource provider providing "actions" is not supported.')
            case 'transaction':
                return Transaction.from(json.data.request[1])
        }
        throw new Error('Invalid request type provided by resource provider.')
    }
 
    async createRequest(
        response: ResourceProviderResponse,
        context: TransactContext
    ): Promise<SigningRequest> {
        // Create a new signing request based on the response to return to the session's transact flow.
        const request = await context.createRequest(response.data.request[1])
 
        // Set the required fee onto the request itself for wallets to process.
        if (response.code === 402 && response.data.fee) {
            request.setInfoKey('txfee', Asset.from(response.data.fee))
        }
 
        // If the fee costs exist, set them on the request for the signature provider to consume
        if (response.data.costs) {
            request.setInfoKey('txfeecpu', response.data.costs.cpu)
            request.setInfoKey('txfeenet', response.data.costs.net)
            request.setInfoKey('txfeeram', response.data.costs.ram)
        }
 
        return request
    }
    /**
     * Perform validation against the request to ensure it is valid for the resource provider.
     */
    validateRequest(request: SigningRequest, context: TransactContext): void {
        // Retrieve first authorizer and ensure it matches session context.
        const firstAction = request.getRawActions()[0]
        const firstAuthorizer = firstAction.authorization[0]
        Iif (!firstAuthorizer.actor.equals(context.permissionLevel.actor)) {
            throw new Error('The first authorizer of the transaction does not match this session.')
        }
    }
    /**
     * Perform validation against the response to ensure it is valid for the session.
     */
    async validateResponseData(response: Record<string, any>): Promise<void> {
        // If the data wasn't provided in the response, throw an error.
        Iif (!response) {
            throw new Error('Resource provider did not respond to the request.')
        }
 
        // If a malformed response with a fee was provided, throw an error.
        Iif (response.code === 402 && !response.data.fee) {
            throw new Error(
                'Resource provider returned a response indicating required payment, but provided no fee amount.'
            )
        }
 
        // If no signatures were provided, throw an error.
        Iif (!response.data.signatures || !response.data.signatures[0]) {
            throw new Error('Resource provider did not return a signature.')
        }
    }
}