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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 | 1327x 1x 1x 1x 1x 1x 1x 1x 1x 1x 234x 234x 234x 234x 234x 234x 234x 467x 105x 105x 105x 15x 1x 234x 234x 209x 25x 24x 1x 233x 233x 33x 233x 101x 233x 94x 233x 1x 233x 95x 233x 120x 233x 93x 233x 1x 233x 94x 233x 230x 3x 233x 93x 233x 96x 137x 233x 94x 233x 1x 232x 233x 104x 233x 8x 233x 93x 44x 1x 322x 1x 59x 59x 4x 55x 2x 2x 2x 53x 21x 21x 21x 21x 21x 68x 68x 5x 63x 4x 59x 59x 68x 68x 16x 16x 16x 2x 1x 2x 16x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 14x 14x 14x 14x 68x 68x 68x 19x 19x 19x 19x 16x 19x 15x 15x 68x 68x 67x 67x 14x 14x 67x 66x 66x 2x 2x 2x 2x 2x 2x 2x 66x 66x 13x 66x 12x 2x 12x 12x 12x 12x 2x 2x 2x 12x 12x 12x 12x 2x 66x 13x 66x 2x 1x 1x 1x 1x 1x 1x 1x 1x 68x 1x 1x 1x 1x 1x 1x 234x 137x 137x 9x 137x 70x 69x 68x 1x 1x 1x 1x 1x 68x 68x 68x 68x 1x 68x 1x 68x 38x 68x 9x 11x 9x 68x 5x 7x 6x 68x 2x 2x 2x 2x 12x 12x 30x 1x 1x 1x 1x 1x 1x 1x 1x 12x | import type {ChainDefinitionType, Fetch} from '@wharfkit/common'
import type {Contract} from '@wharfkit/contract'
import * as zlib from 'pako'
import {
APIClient,
Checksum256,
Checksum256Type,
FetchProvider,
Name,
NameType,
PermissionLevel,
PermissionLevelType,
Serializer,
Signature,
SignedTransaction,
Transaction,
TransactionType,
} from '@wharfkit/antelope'
import {ChainDefinition} from '@wharfkit/common'
import {
ChainId,
RequestDataV2,
RequestDataV3,
RequestSignature,
ResolvedSigningRequest,
SigningRequest,
} from '@wharfkit/signing-request'
import {ABICache, ABICacheInterface} from '@wharfkit/abicache'
import {
AbstractTransactPlugin,
BaseTransactPlugin,
BroadcastOptions,
TransactABIDef,
TransactArgs,
TransactContext,
TransactOptions,
TransactPlugin,
TransactPluginsOptions,
TransactResult,
TransactResultReturnValue,
TransactRevisions,
} from './transact'
import {SessionStorage} from './storage'
import {
actionMatchesPermission,
buildSendTransaction2Options,
extractActions,
getFetch,
getPluginTranslations,
rewriteAuthorizations,
} from './utils'
import {SerializedWalletPlugin, WalletPlugin, WalletPluginSignResponse} from './wallet'
import {UserInterface} from './ui'
import {SessionKeyManager} from './sessionkey/manager'
import {
isSessionKeyWallet,
SessionKeyMismatch,
SessionKeySetupResult,
SessionKeyStatus,
SessionKeyWalletInterface,
} from './sessionkey/types'
/**
* Arguments required to create a new [[Session]].
*/
export interface SessionArgs {
actor?: NameType
chain: ChainDefinitionType
data?: Record<string, any>
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
contracts?: Contract[]
expireSeconds?: number
fetch?: Fetch
storage?: SessionStorage
transactPlugins?: AbstractTransactPlugin[]
transactPluginsOptions?: TransactPluginsOptions
ui?: UserInterface
awaitIrreversible?: boolean
broadcastOptions?: BroadcastOptions
sessionKeyManager?: SessionKeyManager
onPersist?: (session: Session) => Promise<void>
}
export interface SerializedSession {
actor: NameType
chain: Checksum256Type
default?: boolean
permission: NameType
walletPlugin: SerializedWalletPlugin
data?: Record<string, any>
}
export type SessionType = Session | SerializedSession
/**
* A partially specified session, as accepted by [[SessionKit.restore]]. A value
* carrying every required field is used directly; anything less is treated as a
* lookup against the sessions held in storage.
*/
export interface PartialSerializedSession extends Partial<Omit<SerializedSession, 'chain'>> {
chain: Checksum256Type | ChainDefinition
}
/**
* 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 awaitIrreversible: boolean = false
readonly broadcast: boolean = true
readonly broadcastOptions?: BroadcastOptions
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 sessionKeyManager?: SessionKeyManager
readonly onPersist?: (session: Session) => Promise<void>
private _walletPlugin: WalletPlugin
private _data: Record<string, any> = {}
/**
* Get the wallet plugin for this session.
*/
get walletPlugin(): WalletPlugin {
return this._walletPlugin
}
/**
* Check if two sessions match by comparing chain, actor, and permission.
*
* @param s1 Session or SerializedSession
* @param s2 Session or SerializedSession
* @returns boolean indicating if the sessions match
*/
static matches(s1: SessionType, s2: SessionType): boolean {
const ser1 = s1 instanceof Session ? s1.serialize() : s1
const ser2 = s2 instanceof Session ? s2.serialize() : s2
return (
Checksum256.from(ser1.chain).equals(Checksum256.from(ser2.chain)) &&
Name.from(ser1.actor).equals(Name.from(ser2.actor)) &&
Name.from(ser1.permission).equals(Name.from(ser2.permission))
)
}
/**
* Get the data stored in this session instance.
*/
get data(): Record<string, any> {
return this._data
}
/**
* Set the data stored in this session instance.
*/
set data(data: Record<string, any>) {
this._data = data
}
/**
* 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
if (args.data) {
this._data = args.data
}
// Handle all the optional values provided
if (options.appName) {
this.appName = String(options.appName)
}
if (options.abis) {
this.abis = [...options.abis]
}
// Extract any ABIs from the Contract instances provided
if (options.contracts) {
this.abis.push(...options.contracts.map((c) => ({account: c.account, abi: c.abi})))
}
if (options.allowModify !== undefined) {
this.allowModify = options.allowModify
}
if (options.broadcast !== undefined) {
this.broadcast = options.broadcast
}
if (options.awaitIrreversible !== undefined) {
this.awaitIrreversible = options.awaitIrreversible
}
if (options.broadcastOptions !== undefined) {
this.broadcastOptions = options.broadcastOptions
}
if (options.expireSeconds) {
this.expireSeconds = options.expireSeconds
}
if (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
}
if (options.sessionKeyManager) {
this.sessionKeyManager = options.sessionKeyManager
}
if (options.onPersist) {
this.onPersist = options.onPersist
}
}
/**
* 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})})
}
/**
* Alters the session config to change the API endpoint in use
*/
setEndpoint(url: string) {
this.chain.url = url
}
/**
* 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 {
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,
},
}
}
// if any context free data is provided, upgrade to a transaction and include them
if (args.context_free_actions || args.context_free_data) {
const actions = args.actions || [args.action]
delete args.action
return {
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,
context_free_actions: [],
context_free_data: [],
actions,
...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
Iif (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> {
// Check if this transaction will be signed by session key (declared outside try for finally block)
const willUseSessionKey = this.willUseSessionKey(args)
// Save original minimal state to restore later
let originalMinimalState: boolean | undefined
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
const awaitIrreversible =
options && options.awaitIrreversible !== undefined
? options.awaitIrreversible
: this.awaitIrreversible
const broadcastOptions =
options && options.broadcastOptions !== undefined
? options.broadcastOptions
: this.broadcastOptions
// The abi provider to use for this transaction, falling back to the session instance
const abiCache = this.getMergedAbiCache(args, options)
// 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
// Rewrite authorizations for session key if applicable
Iif (willUseSessionKey) {
args = this.rewriteAuthorizationsForSessionKey(args)
}
// The context object for this transaction
const context = new TransactContext({
abiCache,
appName: this.appName,
chain: this.chain,
client: this.client,
createRequest: (a: TransactArgs) => this.createRequest(a, abiCache),
fetch: this.fetch,
permissionLevel: this.permissionLevel,
storage: this.storage,
transactPlugins,
transactPluginsOptions,
ui: this.ui,
})
if (context.ui) {
// Enable minimal mode for session key transactions
Iif (willUseSessionKey && context.ui.setMinimal) {
// Save current minimal state to restore later
Iif (context.ui.getMinimal) {
originalMinimalState = context.ui.getMinimal()
}
context.ui.setMinimal(true)
}
// 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) =>
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,
returns: [],
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)
if (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(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)
if (requestWasModified) {
if (allowModify) {
result.request = resolved.request
result.resolved = resolved
result.transaction = resolved.resolvedTransaction
} else E{
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,
})
const tx2Options = buildSendTransaction2Options(awaitIrreversible, broadcastOptions)
try {
result.response = await context.client.v1.chain.send_transaction2(
signed,
tx2Options
)
} catch (error: any) {
const status = error?.response?.status
if (status === 404 || status === 501) {
result.response = await context.client.v1.chain.send_transaction(signed)
} else E{
throw error
}
}
// Find and process any return values from the transaction
if (result.response.processed && result.response.processed.action_traces) {
result.returns = await processReturnValues(result.response, abiCache)
}
// 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
if (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 {
if (this.ui) {
await this.ui.onError(error)
}
}
throw new Error(error)
} finally {
Iif (willUseSessionKey && this.ui?.setMinimal) {
this.ui.setMinimal(originalMinimalState ?? false)
}
}
}
/**
* 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 the session to a plain object for storage.
*
* @returns SerializedSession object containing chain, actor, permission, and wallet plugin data
*/
serialize = (): SerializedSession => {
const serializableData: Record<string, any> = {
chain: this.chain.id,
actor: this.permissionLevel.actor,
permission: this.permissionLevel.permission,
walletPlugin: {
id: this.walletPlugin.id,
data: this.walletPlugin.data,
},
}
// Only include data if it's not empty
if (Object.keys(this._data).length > 0) {
serializableData.data = this.data
}
return Serializer.objectify(serializableData)
}
/**
* Check if this session has a session key wallet.
* Type guard that narrows walletPlugin to SessionKeyWalletInterface.
*
* @returns True if the wallet plugin is a session key wallet
*/
hasSessionKey(): this is Session & {walletPlugin: SessionKeyWalletInterface} {
return isSessionKeyWallet(this.walletPlugin)
}
/**
* Determine if the given transaction will be signed using the session key.
* Checks if session has a session key and all relevant actions are whitelisted.
*
* @param args The transaction arguments to check
* @returns True if the session key will be used for signing
*/
willUseSessionKey(args: TransactArgs): boolean {
if (!this.hasSessionKey()) {
return false
}
const actions = extractActions(args)
Iif (actions.length === 0) {
return false
}
const actionsMatchingSession = actions.filter((action) =>
actionMatchesPermission(action, this.permissionLevel)
)
if (actionsMatchingSession.length === 0) {
return false
}
return this.walletPlugin.allActionsWhitelisted(actionsMatchingSession)
}
/**
* Rewrite action authorizations to use the session key permission instead of the primary permission.
* Only rewrites actions that match the session permission and are whitelisted.
*
* @param args The transaction arguments to rewrite
* @returns Modified TransactArgs with session key permissions, or original args if not applicable
*/
rewriteAuthorizationsForSessionKey(args: TransactArgs): TransactArgs {
Iif (!isSessionKeyWallet(this.walletPlugin)) {
return args
}
const sessionKeyPermission = this.walletPlugin.getPermission()
const actions = extractActions(args)
Iif (actions.length === 0) {
return args
}
const actionsMatchingSession = actions.filter((action) =>
actionMatchesPermission(action, this.permissionLevel)
)
Iif (actionsMatchingSession.length === 0) {
return args
}
Iif (!this.walletPlugin.allActionsWhitelisted(actionsMatchingSession)) {
return args
}
return rewriteAuthorizations(args, this.permissionLevel, sessionKeyPermission)
}
getMergedAbiCache(args: TransactArgs, options?: TransactOptions): ABICacheInterface {
const abiCache = options?.abiCache || this.abiCache
// If the abiCache supports appending ABIs, merge all from args/options
Iif (!abiCache['setAbi']) {
throw new Error('Custom `abiCache` does not support `setAbi` method.')
}
// Append all ABIs that exist on the Session
this.abis.forEach((def: TransactABIDef) => abiCache.setAbi(def.account, def.abi))
if (options?.abis) {
// If we have ABIs from the TransactOptions, append
options.abis.forEach((def: TransactABIDef) => abiCache.setAbi(def.account, def.abi))
}
if (options?.contracts) {
// Append ABIs from any Contract instances
options.contracts.forEach((c) => abiCache.setAbi(c.account, c.abi))
}
if (args.action && args.action['abi']) {
// Merge any partial ABIs from the action
abiCache.setAbi(args.action.account, args.action['abi'], true)
}
if (args.actions) {
args.actions.forEach((action) => {
if (action['abi']) {
// Merge any partial ABIs from the actions
abiCache.setAbi(action.account, action['abi'], true)
}
})
}
if (args.transaction && args.transaction.actions) {
args.transaction.actions.forEach((action) => {
if (action['abi']) {
// Merge any partial ABIs from the transaction
abiCache.setAbi(action.account, action['abi'], true)
}
})
}
return abiCache
}
/**
* Get the current status of the session key for this session.
*
* @returns SessionKeyStatus indicating whether a session key is active, inactive, has a mismatch, or is not set up
*/
async getSessionKeyStatus(): Promise<SessionKeyStatus> {
const status: SessionKeyStatus = {active: false, exists: false, state: 'not-setup'}
Iif (!this.sessionKeyManager) {
return status
}
Iif (this.sessionKeyManager.hasSessionKey(this)) {
status.active = true
status.exists = true
status.state = 'active'
Iif (isSessionKeyWallet(this.walletPlugin)) {
status.permission = this.walletPlugin.getPermission()
status.publicKey = this.walletPlugin.getPublicKey()
}
return status
}
const result = await this.sessionKeyManager.checkExistingSessionKey(this)
Iif (result.exists) {
status.exists = true
status.state = result.mismatch ? 'mismatch' : 'inactive'
status.permission = result.permission
status.mismatch = result.mismatch
}
return status
}
/**
* Set up a session key for this session, creating a new permission with a generated key.
* Shows consent UI if configured, handles conflicts with existing keys, and persists the session.
*
* @returns SessionKeySetupResult containing the public key and permission name
* @throws Error if session keys are not configured or if setup is cancelled by user
*/
async setupSessionKey(): Promise<SessionKeySetupResult> {
Iif (!this.sessionKeyManager) {
throw new Error('Session keys are not configured. Add sessionKey to SessionKitOptions.')
}
Iif (!this.sessionKeyManager.config.skipConsent && this.ui?.onSessionKeyConsent) {
const consent = await this.ui.onSessionKeyConsent({
appName: String(this.appName || 'this app'),
whitelist: this.sessionKeyManager.whitelist.map((e) => ({
contract: String(e.contract),
actions: e.actions?.map((a) => String(a)),
})),
})
Iif (!consent) {
throw new Error('Session key setup cancelled by user')
}
}
const result = await this.sessionKeyManager.setup(this, async (existingKeys) => {
Iif (!this.ui?.onSessionKeyConflict) {
throw new Error(
'Session keys require a UserInterface implementing onSessionKeyConflict.'
)
}
return this.ui.onSessionKeyConflict({
appName: String(this.appName || 'this app'),
existingKeyCount: existingKeys.length,
})
})
Iif (this.onPersist) {
await this.onPersist(this)
}
return result
}
/**
* Remove the session key from this session, reverting to the primary wallet.
* Removes the key from the blockchain permission and persists the session.
*
* @throws Error if session keys are not configured or if the session does not have a session key
*/
async removeSessionKey(): Promise<void> {
Iif (!this.sessionKeyManager) {
throw new Error('Session keys are not configured. Add sessionKey to SessionKitOptions.')
}
await this.sessionKeyManager.remove(this)
Iif (this.onPersist) {
await this.onPersist(this)
}
}
/**
* Validate the session key whitelist against the on-chain permission links.
* Returns any mismatches between configured whitelist and actual blockchain state.
*
* @returns SessionKeyMismatch if there are differences, undefined if in sync or no session key
*/
async validateSessionKeyWhitelist(): Promise<SessionKeyMismatch | undefined> {
Iif (!this.sessionKeyManager) {
return undefined
}
return this.sessionKeyManager.validateWhitelist(this)
}
/**
* Update the on-chain permission links to match the configured whitelist.
* Adds missing links and removes extra links, then persists the session.
*
* @throws Error if session keys are not configured or if the session does not have a session key
*/
async updateSessionKeyLinks(): Promise<void> {
Iif (!this.sessionKeyManager) {
throw new Error('Session keys are not configured. Add sessionKey to SessionKitOptions.')
}
await this.sessionKeyManager.updateLinks(this)
Iif (this.onPersist) {
await this.onPersist(this)
}
}
}
async function processReturnValues(
response: any,
abiCache: ABICacheInterface
): Promise<TransactResultReturnValue[]> {
const decoded: TransactResultReturnValue[] = []
for (const actionTrace of response.processed.action_traces) {
if (actionTrace.return_value_hex_data) {
const contract = Name.from(actionTrace.act.account)
const action = Name.from(actionTrace.act.name)
const abi = await abiCache.getAbi(contract)
const returnType = abi.action_results.find((a) => Name.from(a.name).equals(action))
if (returnType) {
try {
const data = Serializer.decode({
data: actionTrace.return_value_hex_data,
type: returnType.result_type,
abi,
})
decoded.push({
contract,
action,
hex: actionTrace.return_value_hex_data,
data,
returnType,
})
} catch (error) {
// eslint-disable-next-line no-console -- warn the developer since this may be unintentional
console.warn(`Error decoding return value for ${contract}::${action}:`, error)
decoded.push({
contract,
action,
hex: actionTrace.return_value_hex_data,
data: '',
returnType,
})
}
} else E{
// eslint-disable-next-line no-console -- warn the developer since this may be unintentional
console.warn(`No return type found for ${contract}::${action}`)
decoded.push({
contract,
action,
hex: actionTrace.return_value_hex_data,
data: '',
returnType: {
name: action,
result_type: '',
},
})
}
}
}
return decoded
}
|