Skip to main content

SmartContract

scrypt-ts / SmartContract

Class: SmartContract

The main contract class. To write a contract, extend this class as such:

Example

class YourSmartContract extends SmartContract {
// your smart contract code here
}

Table of contents​

Constructors​

Properties​

Accessors​

Other Methods​

Signature Verification Methods​

Constructors​

constructor​

• new SmartContract(...args)

Parameters​

NameType
...argsany[]

Defined in​

dist/smart-contract/contract.d.ts:149

Properties​

call​

• Private call: any

Defined in​

dist/smart-contract/contract.d.ts:422


dummySignSingleCallTx​

• Private dummySignSingleCallTx: any

Defined in​

dist/smart-contract/contract.d.ts:426


from​

• Optional from: IUnspentOutput | TxOutputRef

from is a reference to a transaction output where the props of this contract instance are located/stored on chain. In other words, it's the start point for the lifecycle of this instance.

Defined in​

dist/smart-contract/contract.d.ts:100


hasPrevouts​

• Private hasPrevouts: any

Defined in​

dist/smart-contract/contract.d.ts:317


multiContractCall​

• Private multiContractCall: any

Defined in​

dist/smart-contract/contract.d.ts:424


signSingleCallTx​

• Private signSingleCallTx: any

Defined in​

dist/smart-contract/contract.d.ts:425


singleContractCall​

• Private singleContractCall: any

Defined in​

dist/smart-contract/contract.d.ts:423


to​

• Optional to: TxInputRef

to is a reference to a transaction input where a public method of this contract instance is called. In other words, it's the end point for the lifecycle of this instance.

Defined in​

dist/smart-contract/contract.d.ts:105

Accessors​

asmArgs​

• get asmArgs(): AsmVarValues

Returns set ASM variable values.

Returns​

AsmVarValues

Defined in​

dist/smart-contract/contract.d.ts:201


balance​

• get balance(): number

Get the current locked balance of the contract

Returns​

number

Defined in​

dist/smart-contract/contract.d.ts:471


changeAddress​

• get changeAddress(): Ripemd160

Get the change address of the change output for to.tx.

Onchain

Returns​

Ripemd160

the change address of to.tx

Defined in​

dist/smart-contract/contract.d.ts:304


changeAmount​

• get changeAmount(): bigint

Get the amount of the change output for to.tx.

Onchain

Returns​

bigint

amount in satoshis

Defined in​

dist/smart-contract/contract.d.ts:292


codePart​

• get codePart(): string

Returns code part of the lockingScript, in hex format.

Returns​

string

Defined in​

dist/smart-contract/contract.d.ts:186


ctx​

• get ctx(): ScriptContext

You can directly access the context through this.ctx in any public @method. [ScriptContext][https://docs.scrypt.io/how-to-write-a-contract/scriptcontext](https://docs.scrypt.io/how-to-write-a-contract/scriptcontext) can be considered additional information a public method gets when called, besides its function parameters.

Onchain

Returns​

ScriptContext

Defined in​

dist/smart-contract/contract.d.ts:481


dataPart​

• get dataPart(): Script

Returns​

Script

Defined in​

dist/smart-contract/contract.d.ts:354


debug​

• get debug(): DebugFunctions

A set of functions for debugging contracts, which can only be called in @method methods.

Returns​

DebugFunctions

Defined in​

dist/smart-contract/contract.d.ts:467


lockingScript​

• get lockingScript(): Script

Returns a lockingScript of contract.

Returns​

Script

Defined in​

dist/smart-contract/contract.d.ts:178


methods​

• get methods(): Record<string, (...args: any) => Promise<ContractTransaction>>

An object to access all public @methods

Returns​

Record<string, (...args: any) => Promise<ContractTransaction>>

Defined in​

dist/smart-contract/contract.d.ts:430


prevouts​

• get prevouts(): ByteString

Get the prevouts for to.tx.

Onchain

Returns​

ByteString

prevouts in satoshis

Defined in​

dist/smart-contract/contract.d.ts:298


provider​

• get provider(): Provider

Get the connected [provider][https://docs.scrypt.io/how-to-test-a-contract#provider](https://docs.scrypt.io/how-to-test-a-contract#provider)

Returns​

Provider

Defined in​

dist/smart-contract/contract.d.ts:379


scriptHash​

• get scriptHash(): string

Returns sha256 hash of the current locking script, formatted as a LE hex string.

Returns​

string

Defined in​

dist/smart-contract/contract.d.ts:190


scriptSize​

• get scriptSize(): number

Returns script size of lockingScript.

Returns​

number

Defined in​

dist/smart-contract/contract.d.ts:182


signer​

• get signer(): Signer

Get the connected [signer][https://docs.scrypt.io/how-to-test-a-contract#signer](https://docs.scrypt.io/how-to-test-a-contract#signer)

Returns​

Signer

Defined in​

dist/smart-contract/contract.d.ts:375


utxo​

• get utxo(): IUnspentOutput

Get the utxo where the contract is currently located

Returns​

IUnspentOutput

Defined in​

dist/smart-contract/contract.d.ts:475

Other Methods​

bindTxBuilder​

▸ bindTxBuilder(methodName, txBuilder): void

Bind a transation builder for a public @method

Parameters​

NameTypeDescription
methodNamestringthe public @method name
txBuilderMethodCallTxBuilder<SmartContract>a transation builder

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:438


buildChangeOutput​

▸ buildChangeOutput(): ByteString

A built-in function to create an [change output][https://wiki.bitcoinsv.io/index.php/Change](https://wiki.bitcoinsv.io/index.php/Change).

Onchain

Returns​

ByteString

Defined in​

dist/smart-contract/contract.d.ts:233


buildContractInput​

▸ buildContractInput(fromUTXO?): Input

Build an input that includes the contract

Parameters​

NameTypeDescription
fromUTXO?IUnspentOutputA parameter to specify the utxo where the contract is located

Returns​

Input

an input that includes the contract

Defined in​

dist/smart-contract/contract.d.ts:448


buildDeployTransaction​

▸ buildDeployTransaction(utxos, amount, changeAddress): Promise<Transaction>

creates a tx to deploy the contract. Users override it to cutomize a deployment tx as below.

Example

override async buildDeployTransaction(utxos: UTXO[], amount: number, changeAddress?: bsv.Address | string): Promise<bsv.Transaction> {
const deployTx = new bsv.Transaction()
// add p2pkh inputs for paying tx fees
.from(utxos)
// add contract output
.addOutput(new bsv.Transaction.Output({
script: this.lockingScript,
satoshis: amount,
}))
// add the change output if passing `changeAddress`
if (changeAddress) {
deployTx.change(changeAddress);
if (this._provider) {
deployTx.feePerKb(await this.provider.getFeePerKb());
}
}

return deployTx;
}

Parameters​

NameTypeDescription
utxosIUnspentOutput[]represents one or more P2PKH inputs for paying transaction fees.
amountnumberthe balance of contract output
changeAddressstring | Addressa change address

Returns​

Promise<Transaction>

Defined in​

dist/smart-contract/contract.d.ts:409


buildStateOutput​

▸ buildStateOutput(amount): ByteString

A built-in function to create an output containing the new state. It takes an input: the number of satoshis in the output.

Onchain

Parameters​

NameTypeDescription
amountbigintthe number of satoshis in the output

Returns​

ByteString

an output containing the new state

Defined in​

dist/smart-contract/contract.d.ts:227


checkPreimage​

▸ checkPreimage(txPreimage): boolean

Using the [OP_PUSH_TX][https://medium.com/@xiaohuiliu/op-push-tx-3d3d279174c1](https://medium.com/@xiaohuiliu/op-push-tx-3d3d279174c1) technique, check if txPreimage is the preimage of the current transaction.

Onchain

Parameters​

NameTypeDescription
txPreimageSigHashPreimageThe format of the preimage is [specified][https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm](https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm)

Returns​

boolean

true if txPreimage is the preimage of the current transaction. Otherwise false.

Defined in​

dist/smart-contract/contract.d.ts:274


checkPreimageAdvanced​

▸ checkPreimageAdvanced(txPreimage, privKey, pubKey, inverseK, r, rBigEndian, sigHashType): boolean

Same as checkPreimage, but support customized more settings.

Onchain

Parameters​

NameTypeDescription
txPreimageSigHashPreimageThe format of the preimage is [specified][https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm](https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm)
privKeyPrivKeyprivate Key
pubKeyPubKeypublic key
inverseKbigintinverseK
rbigintr
rBigEndianstringmust be mininally encoded, to conform to strict DER rule https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#der-encoding
sigHashTypeSigHashTypeA SIGHASH flag is used to indicate which part of the transaction is signed by the ECDSA signature.

Returns​

boolean

true if txPreimage is the preimage of the current transaction. Otherwise false.

Defined in​

dist/smart-contract/contract.d.ts:259


checkPreimageSigHashType​

▸ checkPreimageSigHashType(txPreimage, sigHashType): boolean

Same as checkPreimage, but support customized sighash type

Onchain

Parameters​

NameTypeDescription
txPreimageSigHashPreimageThe format of the preimage is [specified][https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm](https://github.com/bitcoin-sv/bitcoin-sv/blob/master/doc/abc/replay-protected-sighash.md#digest-algorithm)
sigHashTypeSigHashTypeA SIGHASH flag is used to indicate which part of the transaction is signed by the ECDSA signature.

Returns​

boolean

true if txPreimage is the preimage of the current transaction. Otherwise false.

Defined in​

dist/smart-contract/contract.d.ts:267


connect​

▸ connect(providerOrSigner): Promise<void>

connect a provider or a signer.

Parameters​

NameTypeDescription
providerOrSignerProvider | Signera provider or a signer

Returns​

Promise<void>

Defined in​

dist/smart-contract/contract.d.ts:371


deploy​

▸ deploy(amount?, options?): Promise<TransactionResponse>

Deploy the contract

Parameters​

NameTypeDescription
amount?numbersatoshis locked in the contract, 1 sat by default
options?ObjectAn optional parameter that can specify the change address
options.address?Address-
options.changeAddress?Address-

Returns​

Promise<TransactionResponse>

The transaction id of the successfully deployed contract

Defined in​

dist/smart-contract/contract.d.ts:416


getStateScript​

▸ getStateScript(): ByteString

A built-in function to create a locking script containing the new state.

Onchain

Returns​

ByteString

a locking script that containing the new state

Defined in​

dist/smart-contract/contract.d.ts:239


insertCodeSeparator​

▸ insertCodeSeparator(): void

Insert and OP_CODESEPARATOR at this point of the functions logic. More detail about [OP_CODESEPARATOR][https://wiki.bitcoinsv.io/index.php/OP_CODESEPARATOR](https://wiki.bitcoinsv.io/index.php/OP_CODESEPARATOR)

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:279


isStateful​

▸ isStateful(): boolean

Check if the contract is a stateful contract

Returns​

boolean

true if contract has a @prop(true) property

Defined in​

dist/smart-contract/contract.d.ts:453


markAsGenesis​

▸ markAsGenesis(): SmartContract

Mark the contract as genesis contracts

Returns​

SmartContract

Defined in​

dist/smart-contract/contract.d.ts:220


next​

▸ next(opt?): SmartContract

Parameters​

NameTypeDescription
opt?Objectproperties that only references are copied, but not deep clone their values.
opt.refCloneProps?string[]-

Returns​

SmartContract

a cloned contract instance with this.from = undefined and this.to = undefined

Defined in​

dist/smart-contract/contract.d.ts:214


setAsmVars​

▸ setAsmVars(asmVarValues): void

If the compiled contract contains any ASM variable templates (e.g. P2PKH.unlock.pubKeyHash), replace them with the passed values.

Parameters​

NameTypeDescription
asmVarValuesAsmVarValuestype that contains the actual values.

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:197


setDataPartInASM​

▸ setDataPartInASM(dataPart): void

set the data part of the contract in ASM format

Parameters​

NameType
dataPartstring

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:348


setDataPartInHex​

▸ setDataPartInHex(dataPart): void

set the data part of the contract in hex format

Parameters​

NameType
dataPartstring

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:353


sigTypeOfMethod​

▸ sigTypeOfMethod(methodName): number

Get [sigHash type][https://docs.scrypt.io/how-to-write-a-contract/scriptcontext#sighash-type](https://docs.scrypt.io/how-to-write-a-contract/scriptcontext#sighash-type) of the public @method function.

Parameters​

NameTypeDescription
methodNamestringname of the public @method function.

Returns​

number

a sigHash type

Defined in​

dist/smart-contract/contract.d.ts:459


compile​

▸ Static compile(): Promise<Artifact>

compiling the scrypt source which is the output of transpiling. Calling this function to output the contract artifact file. only used for testing. This function should not be called in production environment.

Returns​

Promise<Artifact>

if compiling succeed, otherwise it throws error.

Defined in​

dist/smart-contract/contract.d.ts:124


fromTx​

▸ Static fromTx<T>(this, tx, atOutputIndex, offchainValues?): T

recover a SmartContract instance from the transaction if the contract contains onchain properties of type HashedMap or HashedSet it's required to pass all their offchain raw data at this transaction moment

Type parameters​

NameType
Textends SmartContract<T>

Parameters​

NameTypeDescription
this(...args: any[]) => T-
txTransactiontransaction
atOutputIndexnumberoutput index of tx
offchainValues?Record<string, any>the value of offchain properties, the raw data of onchain HashedMap and HashedSet properties, at this transaction moment

Returns​

T

Defined in​

dist/smart-contract/contract.d.ts:499


getArtifact​

▸ Static getArtifact(): Artifact

The contract class needs to call this function before instantiating.

Returns​

Artifact

Defined in​

dist/smart-contract/contract.d.ts:138


loadArtifact​

▸ Static loadArtifact(artifactFile?): void

This function is usually called on the front-end. The contract class needs to call this function before instantiating.

Parameters​

NameTypeDescription
artifactFile?string | Artifacta merged contract artifact object, or its file path

Returns​

void

Defined in​

dist/smart-contract/contract.d.ts:132


multiContractCall​

▸ Static multiContractCall(partialContractTx, signer, options?): Promise<MultiContractTransaction>

When the @methods of multiple contracts is called in a transaction, this function signs and broadcasts the final transaction.

Parameters​

NameTypeDescription
partialContractTxContractTransactiona ContractTransation with a unsigned transation.
signerSignera signer to sign the transation.
options?MultiContractCallOptions-

Returns​

Promise<MultiContractTransaction>

a MultiContractTransation with a signed transation.

Defined in​

dist/smart-contract/contract.d.ts:510


parseCallData​

▸ Static parseCallData(tx, inputIndex): CallData

parse call data when a contract public method called in a transation.

Parameters​

NameType
txTransaction
inputIndexnumber

Returns​

CallData

Defined in​

dist/smart-contract/contract.d.ts:517


Signature Verification Methods​

checkMultiSig​

▸ checkMultiSig(signatures, publickeys): boolean

Compares the first signature against each public key until it finds an ECDSA match. Starting with the subsequent public key, it compares the second signature against each remaining public key until it finds an ECDSA match. The process is repeated until all signatures have been checked or not enough public keys remain to produce a successful result. All signatures need to match a public key. Because public keys are not checked again if they fail any signature comparison, signatures must be placed in the scriptSig using the same order as their corresponding public keys were placed in the scriptPubKey or redeemScript. If all signatures are valid, 1 is returned, 0 otherwise. Due to a bug, one extra unused value is removed from the stack.

Onchain

See

https://wiki.bitcoinsv.io/index.php/Opcodes_used_in_Bitcoin_Script

Parameters​

NameType
signaturesSig[]
publickeysPubKey[]

Returns​

boolean

Defined in​

dist/smart-contract/contract.d.ts:286


checkSig​

▸ checkSig(signature, publickey, errorMsg?): boolean

A built-in function verifies an ECDSA signature. It takes two inputs from the stack, a public key (on top of the stack) and an ECDSA signature in its DER_CANONISED format concatenated with sighash flags. It outputs true or false on the stack based on whether the signature check passes or fails.

Onchain

See

https://wiki.bitcoinsv.io/index.php/Opcodes_used_in_Bitcoin_Script

Parameters​

NameType
signatureSig
publickeyPubKey
errorMsg?string

Returns​

boolean

Defined in​

dist/smart-contract/contract.d.ts:246