All files / src contract.ts

93.1% Statements 54/58
77.77% Branches 21/27
100% Functions 17/17
92.45% Lines 49/53

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 183660x                         1x 1x   1x 1x                                                             1x       311x               311x     311x 311x     311x 311x     311x 311x 1x         4698x       332x       332x 2x   330x                       1332x       29x       26x 3x     23x 23x 5x   23x                       4x 3x     4x   4x   4x             4x 4x 2x     2x 5x 2x     2x               3x 9x             3x 1x   12x 2x 1x       1x   1x  
import {
    ABI,
    ABIDef,
    ABISerializableObject,
    Action,
    APIClient,
    BytesType,
    Name,
    NameType,
    PermissionLevel,
    PermissionLevelType,
    Serializer,
    Transaction,
} from '@wharfkit/antelope'
import {PlaceholderAuth} from '@wharfkit/signing-request'
 
import {Table} from './contract/table'
import {formatExceptionMessage, TableScopeType} from './utils'
 
export interface ContractArgs {
    abi: ABIDef
    account: NameType
    client: APIClient
}
 
export interface ContractOptions {
    debug?: boolean
}
 
export interface ActionOptions {
    authorization?: PermissionLevelType[]
}
 
export type ActionDataType = BytesType | ABISerializableObject | Record<string, any>
 
export type ActionConstructor = (data: ActionDataType, options?: ActionOptions) => Action
 
export interface ActionsArgs {
    name: NameType
    data: ActionDataType
    authorization?: PermissionLevelType[]
}
 
/**
 * Represents a smart contract deployed to a specific blockchain.
 * Provides methods for interacting with the contract such as
 * calling actions, reading tables, and getting the ABI of the contract.
 */
export class Contract {
    readonly abi: ABI
    readonly account: Name
    readonly client: APIClient
    readonly debug: boolean = false
 
    /**
     * Constructs a new `Contract` instance.
     *
     * @param {ContractArgs} args - The required arguments for a contract.
     */
    constructor(args: ContractArgs, options: ContractOptions = {}) {
        Iif (!args.abi) {
            throw new Error('Contract requires an ABI')
        }
        this.abi = ABI.from(args.abi)
        Iif (!args.account) {
            throw new Error('Contract requires an account name')
        }
        this.account = Name.from(args.account)
        Iif (!args.client) {
            throw new Error('Contract requires an APIClient')
        }
        this.client = args.client
        if (options.debug) {
            this.debug = options.debug
        }
    }
 
    public get tableNames(): string[] {
        return this.abi.tables.map((table) => String(table.name))
    }
 
    public hasTable(name: NameType): boolean {
        return this.tableNames.includes(String(name))
    }
 
    public table<RowType>(name: NameType, scope?: TableScopeType, rowType?): Table<RowType | any> {
        if (!this.hasTable(name)) {
            throw new Error(`Contract (${this.account}) does not have a table named (${name})`)
        }
        return Table.from<RowType>({
            abi: this.abi,
            account: this.account,
            client: this.client,
            debug: this.debug,
            defaultScope: scope,
            name,
            rowType,
        })
    }
 
    public get actionNames(): string[] {
        return this.abi.actions.map((action) => String(action.name))
    }
 
    public hasAction(name: NameType): boolean {
        return this.actionNames.includes(String(name))
    }
 
    public action(name, data: ActionDataType, options?: ActionOptions): Action {
        if (!this.hasAction(name)) {
            throw new Error(`Contract (${this.account}) does not have an action named (${name})`)
        }
 
        let authorization = [PlaceholderAuth]
        if (options && options.authorization) {
            authorization = options.authorization.map((auth) => PermissionLevel.from(auth))
        }
        return Action.from(
            {
                account: this.account,
                name,
                authorization,
                data,
            },
            this.abi
        )
    }
 
    public async readonly(name, data?: ActionDataType): Promise<any> {
        if (!data) {
            data = {}
        }
        // Generate action
        const action = this.action(name, data)
        // Remove authorizations
        action.authorization = []
        // Assemble readonly transaction
        const transaction = Transaction.from({
            ref_block_num: 0,
            ref_block_prefix: 0,
            expiration: 0,
            actions: [action],
        })
        // Execute and retrieve response
        const response = await this.client.v1.chain.send_read_only_transaction(transaction)
        if (response.processed.except) {
            throw new Error(formatExceptionMessage(response.processed.except))
        }
        // Decode and return results
        const hexData = response.processed.action_traces[0].return_value_hex_data
        const returnType = this.abi.action_results.find((a) => Name.from(a.name).equals(name))
        Iif (!returnType) {
            throw new Error(`Return type for ${name} not defined in the ABI.`)
        }
        return Serializer.decode({
            data: hexData,
            type: returnType.result_type,
            abi: this.abi,
        })
    }
 
    public actions(actions: ActionsArgs[], options?: ActionOptions): Action[] {
        return actions.map((action) =>
            this.action(action.name, action.data, {
                authorization: action.authorization || options?.authorization,
            })
        )
    }
 
    public ricardian(name: NameType) {
        if (!this.hasAction(name)) {
            throw new Error(`Contract (${this.account}) does not have an action named (${name})`)
        }
        const action = this.abi.actions.find((action) => Name.from(action.name).equals(name))
        if (!action || !action.ricardian_contract) {
            throw new Error(
                `Contract (${this.account}) action named (${name}) does not have a defined ricardian contract`
            )
        }
        return action.ricardian_contract
    }
}