All files session.ts

91.87% Statements 147/160
90.47% Branches 114/126
82.35% Functions 14/17
92.35% Lines 145/157

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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 6001x 1x                           1x   1x                 1x 1x                         1x                                                                                     1x   146x   146x 146x   146x         146x                     146x     146x 143x 3x 2x   1x           145x     145x 45x   145x 46x   145x 47x   145x 95x   145x 46x   145x 145x       145x 45x   145x 49x   96x   145x 46x   145x 1x   144x   145x 46x               4x             1x             206x                     47x 47x                 4x                       43x                                                                                                 55x       55x 4x 51x 4x   47x 47x                 55x 55x                               19x 19x     19x 2x   1x         2x   19x                                     55x     55x       55x         55x     55x 55x   1x       55x 55x           55x   55x       55x         55x                           55x   7x   7x 7x   7x         55x     55x                     55x   22x   22x   22x     22x 19x     22x   16x   16x           55x 55x 54x     54x 7x 7x       54x           53x     53x 2x 2x 2x 2x 2x 2x 2x                   53x     53x 6x     53x 8x   2x       8x           8x     8x   8x   2x         53x 6x       53x       2x 1x 1x 1x 1x     1x     1x 1x     1x                           1x                 1x               1x   1x               1x         1x     146x 53x               14x 14x                        
import zlib from 'pako'
import {
    APIClient,
    Checksum256Type,
    FetchProvider,
    Name,
    NameType,
    PermissionLevel,
    PermissionLevelType,
    Serializer,
    Signature,
    SignedTransaction,
    Transaction,
    TransactionType,
} from '@wharfkit/antelope'
import {ChainDefinition} from '@wharfkit/common'
import type {ChainDefinitionType, Fetch, LocaleDefinitions} from '@wharfkit/common'
import {
    ChainId,
    RequestDataV2,
    RequestDataV3,
    RequestSignature,
    ResolvedSigningRequest,
    SigningRequest,
} from '@wharfkit/signing-request'
 
import {ABICache, ABICacheInterface} from '@wharfkit/abicache'
import {
    AbstractTransactPlugin,
    BaseTransactPlugin,
    TransactABIDef,
    TransactArgs,
    TransactContext,
    TransactOptions,
    TransactPlugin,
    TransactPluginsOptions,
    TransactResult,
    TransactRevisions,
} from './transact'
import {SessionStorage} from './storage'
import {getFetch} from './utils'
import {SerializedWalletPlugin, WalletPlugin, WalletPluginSignResponse} from './wallet'
import {UserInterface} from './ui'
 
/**
 * Arguments required to create a new [[Session]].
 */
export interface SessionArgs {
    actor?: NameType
    chain: ChainDefinitionType
    permission?: NameType
    permissionLevel?: PermissionLevelType | string
    walletPlugin: WalletPlugin
}
 
/**
 * Options for creating a new [[Session]].
 */
export interface SessionOptions {
    abis?: TransactABIDef[]
    abiCache?: ABICacheInterface
    allowModify?: boolean
    appName?: NameType
    broadcast?: boolean
    expireSeconds?: number
    fetch?: Fetch
    storage?: SessionStorage
    transactPlugins?: AbstractTransactPlugin[]
    transactPluginsOptions?: TransactPluginsOptions
    ui?: UserInterface
}
 
export interface SerializedSession {
    actor: NameType
    chain: Checksum256Type
    default?: boolean
    permission: NameType
    walletPlugin: SerializedWalletPlugin
}
 
/**
 * A representation of a session to interact with a specific blockchain account.
 */
export class Session {
    readonly appName?: string
    readonly abis: TransactABIDef[] = []
    readonly abiCache: ABICacheInterface
    readonly allowModify: boolean = true
    readonly broadcast: boolean = true
    readonly chain: ChainDefinition
    readonly expireSeconds: number = 120
    readonly fetch: Fetch
    readonly permissionLevel: PermissionLevel
    readonly storage?: SessionStorage
    readonly transactPlugins: TransactPlugin[]
    readonly transactPluginsOptions: TransactPluginsOptions = {}
    readonly ui?: UserInterface
    readonly walletPlugin: WalletPlugin
 
    /**
     * The constructor of the `Session` class.
     *
     * @param options SessionOptions
     */
    constructor(args: SessionArgs, options: SessionOptions = {}) {
        // Set the ChainDefinition for this session
        this.chain = ChainDefinition.from(args.chain)
 
        // Determine the permission level to use for this session
        if (args.permissionLevel) {
            this.permissionLevel = PermissionLevel.from(args.permissionLevel)
        } else if (args.actor && args.permission) {
            this.permissionLevel = PermissionLevel.from(`${args.actor}@${args.permission}`)
        } else {
            throw new Error(
                'Either a permissionLevel or actor/permission must be provided when creating a new Session.'
            )
        }
 
        // Set the WalletPlugin for this session
        this.walletPlugin = args.walletPlugin
 
        // Handle all the optional values provided
        if (options.appName) {
            this.appName = String(options.appName)
        }
        if (options.abis) {
            this.abis = [...options.abis]
        }
        if (options.allowModify !== undefined) {
            this.allowModify = options.allowModify
        }
        if (options.broadcast !== undefined) {
            this.broadcast = options.broadcast
        }
        if (options.expireSeconds) {
            this.expireSeconds = options.expireSeconds
        }
        Eif (options.fetch) {
            this.fetch = options.fetch
        } else {
            this.fetch = getFetch(options)
        }
        if (options.storage) {
            this.storage = options.storage
        }
        if (options.transactPlugins) {
            this.transactPlugins = options.transactPlugins
        } else {
            this.transactPlugins = [new BaseTransactPlugin()]
        }
        if (options.transactPluginsOptions) {
            this.transactPluginsOptions = options.transactPluginsOptions
        }
        if (options.abiCache) {
            this.abiCache = options.abiCache
        } else {
            this.abiCache = new ABICache(this.client)
        }
        if (options.ui) {
            this.ui = options.ui
        }
    }
 
    /**
     * Returns the name of the actor that is being used for this session.
     */
    get actor(): Name {
        return this.permissionLevel.actor
    }
 
    /**
     * Returns the name of the permission that is being used for this session.
     */
    get permission(): Name {
        return this.permissionLevel.permission
    }
 
    /**
     * Returns an APIClient configured for this session.
     */
    get client(): APIClient {
        return new APIClient({provider: new FetchProvider(this.chain.url, {fetch: this.fetch})})
    }
 
    /**
     * Templates in any missing fields from partial transactions.
     *
     * @param args TransactArgs
     * @returns TransactArgs
     */
    upgradeTransaction(args: TransactArgs): TransactArgs {
        // eosjs transact compat: upgrade to transaction if args have any header fields
        const anyArgs = args as any
        if (
            args.actions &&
            (anyArgs.expiration ||
                anyArgs.ref_block_num ||
                anyArgs.ref_block_prefix ||
                anyArgs.max_net_usage_words ||
                anyArgs.max_cpu_usage_ms ||
                anyArgs.delay_sec)
        ) {
            return (args = {
                transaction: {
                    expiration: '1970-01-01T00:00:00',
                    ref_block_num: 0,
                    ref_block_prefix: 0,
                    max_net_usage_words: 0,
                    max_cpu_usage_ms: 0,
                    delay_sec: 0,
                    ...anyArgs,
                },
            })
        }
        return args
    }
 
    /**
     * Lifted from @wharfkit/antelope-signing-request.
     *
     * Copy of: https://github.com/greymass/@wharfkit/signing-request/blob/6fc84b2355577d6461676bff417c76e4f6f2f5c3/src/signing-request.ts#L305
     *
     * TODO: Remove. This will no longer be needed once the `clone` functionality in ESR is updated
     */
    /* istanbul ignore next */
    private storageType(version: number): typeof RequestDataV3 | typeof RequestDataV2 {
        return version === 2 ? RequestDataV2 : RequestDataV3
    }
 
    /**
     * Create a clone of the given SigningRequest
     *
     * Overrides: https://github.com/greymass/@wharfkit/signing-request/blob/6fc84b2355577d6461676bff417c76e4f6f2f5c3/src/signing-request.ts#L1112
     *
     * @param {SigningRequest} request The SigningRequest to clone
     * @param {ABICacheInterface} abiCache The ABICacheInterface to use for the clone
     * @returns Returns a cloned SigningRequest with updated abiCache and zlib
     */
    /* istanbul ignore next */
    cloneRequest(request: SigningRequest, abiCache: ABICacheInterface): SigningRequest {
        // Lifted from @wharfkit/antelope-signing-request method `clone()`
        // This was done to modify the zlib and abiProvider
        // TODO: Modify ESR library to expose this `clone()` functionality
        // TODO: This if statement should potentially just be:
        //          request = args.request.clone(abiProvider, zlib)
        let signature: RequestSignature | undefined
        if (request.signature) {
            signature = RequestSignature.from(JSON.parse(JSON.stringify(request.signature)))
        }
        const RequestData = this.storageType(request.version)
        const data = RequestData.from(JSON.parse(JSON.stringify(request.data)))
        return new SigningRequest(request.version, data, zlib, abiCache, signature)
    }
 
    /**
     * Convert any provided form of TransactArgs to a SigningRequest
     *
     * @param {TransactArgs} args
     * @param {ABICacheInterface} abiCache
     * @returns Returns a SigningRequest
     */
    async createRequest(args: TransactArgs, abiCache: ABICacheInterface): Promise<SigningRequest> {
        let request: SigningRequest
        const options = {
            abiProvider: abiCache,
            zlib,
        }
        if (args.request && args.request instanceof SigningRequest) {
            request = this.cloneRequest(args.request, abiCache)
        } else if (args.request) {
            request = SigningRequest.from(args.request, options)
        } else {
            args = this.upgradeTransaction(args)
            request = await SigningRequest.create(
                {
                    ...args,
                    chainId: this.chain.id,
                },
                options
            )
        }
        // Always set the broadcast flag to false on signing requests, Wharf needs to do it
        request.setBroadcast(false)
        return request
    }
 
    /**
     * Update a SigningRequest, ensuring its old metadata is retained.
     *
     * @param {SigningRequest} previous
     * @param {SigningRequest} modified
     * @param abiCache
     * @returns
     */
    async updateRequest(
        previous: SigningRequest,
        modified: SigningRequest,
        abiCache: ABICacheInterface
    ): Promise<SigningRequest> {
        const updatedRequest: SigningRequest = this.cloneRequest(modified, abiCache)
        const info = updatedRequest.getRawInfo()
        // Take all the metadata from the previous and set it on the modified request.
        // This will preserve the metadata as it is modified by various plugins.
        previous.data.info.forEach((metadata) => {
            if (info[metadata.key]) {
                // eslint-disable-next-line no-console -- warn the developer since this may be unintentional
                console.warn(
                    `During an updateRequest call, the previous request had already set the ` +
                        `metadata key of "${metadata.key}" which will not be overwritten.`
                )
            }
            updatedRequest.setRawInfoKey(metadata.key, metadata.value)
        })
        return updatedRequest
    }
 
    /**
     * Perform a transaction using this session.
     *
     * @param {TransactArgs} args
     * @param {TransactOptions} options
     * @returns {TransactResult} The status and data gathered during the operation.
     * @mermaid - Transaction sequence diagram
     * flowchart LR
     *   A((Transact)) --> B{{"Hook(s): beforeSign"}}
     *   B --> C[Wallet Plugin]
     *   C --> D{{"Hook(s): afterSign"}}
     *   D --> E[Broadcast Plugin]
     *   E --> F{{"Hook(s): afterBroadcast"}}
     *   F --> G[TransactResult]
     */
    async transact(args: TransactArgs, options?: TransactOptions): Promise<TransactResult> {
        try {
            // The number of seconds before this transaction expires
            const expireSeconds =
                options && options.expireSeconds ? options.expireSeconds : this.expireSeconds
 
            // Whether or not the request should be broadcast during the transact call
            const willBroadcast =
                options && typeof options.broadcast !== 'undefined'
                    ? options.broadcast
                    : this.broadcast
 
            // The abi provider to use for this transaction, falling back to the session instance
            const abiCache = options?.abiCache || this.abiCache
 
            // Collect all the ABIs that have been passed in manually
            const abiDefs: TransactABIDef[] = [...this.abis]
            if (options?.abis) {
                // If we have ABIs in the options, add them.
                abiDefs.push(...options.abis)
            }
 
            // If an array of ABIs are provided, set them on the abiCache
            Eif (abiCache['setAbi']) {
                abiDefs.forEach((def: TransactABIDef) => abiCache['setAbi'](def.account, def.abi))
            } else {
                throw new Error('Custom `abiCache` does not support `setAbi` method.')
            }
 
            // The TransactPlugins to use for this transaction, falling back to the session instance
            const transactPlugins = options?.transactPlugins || this.transactPlugins
            const transactPluginsOptions =
                options?.transactPluginsOptions || this.transactPluginsOptions
 
            // A flag to determine whether or not the request can be modified by the beforeSign hooks or wallet plugins
            let allowModify =
                options && typeof options.allowModify !== 'undefined'
                    ? options.allowModify
                    : this.allowModify
 
            // The context object for this transaction
            const context = new TransactContext({
                abiCache,
                appName: this.appName,
                chain: this.chain,
                client: this.client,
                createRequest: (args: TransactArgs) => this.createRequest(args, abiCache),
                fetch: this.fetch,
                permissionLevel: this.permissionLevel,
                storage: this.storage,
                transactPlugins,
                transactPluginsOptions,
                ui: this.ui,
            })
 
            if (context.ui) {
                // Notify the UI that a transaction is about to begin
                await context.ui.onTransact()
                // Merge in any new localization strings from the plugins
                for (const translation of transactPlugins.map((transactPlugin) =>
                    this.getPluginTranslations(transactPlugin)
                )) {
                    context.ui.addTranslations(translation)
                }
            }
 
            // Process incoming TransactArgs and convert to a SigningRequest
            let request: SigningRequest = await this.createRequest(args, abiCache)
 
            // Create TransactResult to eventually respond to this call with
            const result: TransactResult = {
                chain: this.chain,
                request,
                resolved: undefined,
                revisions: new TransactRevisions(request),
                signatures: [],
                signer: this.permissionLevel,
                transaction: undefined,
            }
 
            // Call the `beforeSign` hooks that were registered by the TransactPlugins
            for (const hook of context.hooks.beforeSign) {
                // Get the response of the hook by passing a cloned request.
                const response = await hook(request.clone(), context)
 
                Eif (response) {
                    // Save revision history for developers to debug modifications to requests.
                    result.revisions.addRevision(response, String(hook), allowModify)
 
                    // If modification is allowed, change the current request.
                    if (allowModify) {
                        request = await this.updateRequest(request, response.request, abiCache)
                    }
 
                    if (response.signatures) {
                        // If signatures were returned, append them
                        result.signatures = [...result.signatures, ...response.signatures]
                        // Disable any further modifications to the request if the request was signed
                        allowModify = false
                    }
                }
            }
 
            // Resolve the final SigningRequest and assign it to the TransactResult
            result.request = request
            result.resolved = await context.resolve(request, expireSeconds)
            result.transaction = result.resolved.resolvedTransaction
 
            // Merge in any new localization strings from the wallet plugin
            if (context.ui) {
                await context.ui.onSign()
                context.ui.addTranslations(this.getPluginTranslations(this.walletPlugin))
            }
 
            // Retrieve the signature(s) and request modifications for this request from the WalletPlugin
            const walletResponse: WalletPluginSignResponse = await this.walletPlugin.sign(
                result.resolved,
                context
            )
 
            // Merge signatures in to the TransactResult
            result.signatures.push(...walletResponse.signatures)
 
            // If a ResolvedSigningRequest was returned from the wallet, determine if it was modified, then if it was allowed.
            if (walletResponse.resolved) {
                const {resolved} = walletResponse
                const requestWasModified = !result.resolved.transaction.equals(resolved.transaction)
                Eif (requestWasModified) {
                    Eif (allowModify) {
                        result.request = resolved.request
                        result.resolved = resolved
                        result.transaction = resolved.resolvedTransaction
                    } else {
                        throw new Error(
                            `The ${this.walletPlugin.metadata.name} plugin modified the transaction when it was not allowed to.`
                        )
                    }
                }
            }
 
            // Run the `afterSign` hooks that were registered by the TransactPlugins
            for (const hook of context.hooks.afterSign) await hook(result, context)
 
            // Notify the UI that the signing operations are complete
            if (context.ui) {
                await context.ui.onSignComplete()
            }
 
            if (willBroadcast) {
                if (context.ui) {
                    // Notify the UI that broadcast logic will be run against the transaction
                    await context.ui.onBroadcast()
                }
 
                // Assemble the SignedTransaction to broadcast
                const signed = SignedTransaction.from({
                    ...result.resolved.transaction,
                    signatures: result.signatures,
                })
 
                // Broadcast the SignedTransaction and save the API response to the TransactResult
                result.response = await context.client.v1.chain.send_transaction(signed)
 
                // Run the `afterBroadcast` hooks that were registered by the TransactPlugins
                for (const hook of context.hooks.afterBroadcast) await hook(result, context)
 
                if (context.ui) {
                    // Notify the UI that the transaction has completed the broadcast logic
                    await context.ui.onBroadcastComplete()
                }
            }
 
            // Notify the UI that the transaction has completed
            if (context.ui) {
                await context.ui.onTransactComplete()
            }
 
            // Return the TransactResult to the caller
            return result
        } catch (error: any) {
            // TODO: Improve API response detection and error handling
            // Possible plugin that interprets them?
            if (error.response && error.response.json) {
                const {json} = error.response
                Eif (json.error && json.error.details) {
                    const e = new Error(json.error.details[0].message)
                    Iif (this.ui) {
                        await this.ui.onError(e)
                    }
                    throw e
                }
            } else {
                Eif (this.ui) {
                    await this.ui.onError(error)
                }
            }
            throw new Error(error)
        }
    }
 
    /**
     * Request a signature for a given transaction.
     *
     * This function will NOT use plugins and will NOT broadcast the transaction.
     *
     * @param {TransactionType} transaction A full transaction-like object
     * @returns {Promise<Signature[]>} The signature(s) for the transaction
     */
    async signTransaction(transaction: TransactionType): Promise<Signature[]> {
        // Create a TransactContext for the WalletPlugin to use
        const context = new TransactContext({
            abiCache: this.abiCache,
            chain: this.chain,
            client: this.client,
            createRequest: (args: TransactArgs) => this.createRequest(args, this.abiCache),
            fetch: this.fetch,
            permissionLevel: this.permissionLevel,
        })
        // Create a request based on the incoming transaction
        const request = await SigningRequest.create(
            {
                transaction,
                chainId: this.chain.id,
            },
            context.esrOptions
        )
        // Always set the broadcast flag to false on signing requests, Wharf needs to do it
        request.setBroadcast(false)
        // Resolve the request since the WalletPlugin expects a ResolvedSigningRequest
        const resolvedRequest = new ResolvedSigningRequest(
            request,
            this.permissionLevel,
            Transaction.from(transaction),
            Serializer.objectify(Transaction.from(transaction)),
            ChainId.from(this.chain.id)
        )
        // Request the signature from the WalletPlugin
        const walletResponse: WalletPluginSignResponse = await this.walletPlugin.sign(
            resolvedRequest,
            context
        )
        // Return the array of signature
        return walletResponse.signatures
    }
 
    serialize = (): SerializedSession =>
        Serializer.objectify({
            chain: this.chain.id,
            actor: this.permissionLevel.actor,
            permission: this.permissionLevel.permission,
            walletPlugin: this.walletPlugin.serialize(),
        })
 
    getPluginTranslations(transactPlugin: TransactPlugin | WalletPlugin): LocaleDefinitions {
        Eif (!transactPlugin.translations) {
            return {}
        }
        const prefixed = {}
        const languages = Object.keys(transactPlugin.translations)
        languages.forEach((lang) => {
            if (transactPlugin.translations) {
                prefixed[lang] = {[transactPlugin.id]: transactPlugin.translations[lang]}
            }
        })
        return prefixed
    }
}