Skip to content

Repository files navigation

scryptlib

Javascript/TypeScript SDK for integration of Bitcoin SV Smart Contracts written in the sCrypt language.

Build Status

You can install scryptlib in your project as below:

$ npm install scryptlib

A smart contract is compiled to a locking script template. A contract function call is transformed to an unlocking script. Developers are responsible for setting the locking and unlocking scripts of a transaction properly before sending it to the Bitcoin network. This may include some actions described below:

  • Instantiate locking script: replace the constructor formal parameters, represented by placeholders in the locking script template, with actual parameters/arguments to form the complete locking script.

  • Assemble unlocking script: convert the arguments of a contract function call to script format and concatenate them to form the unlocking script.

By using scryptlib, both scripts can be obtained with ease.

Contract Artifact File

The compiler output results in a JSON file. It’s a representation used to build locking and unlocking scripts. We call this file a contract artifact file.

There are three ways to generate this file (named as <contract_name>.json):

  1. Use sCrypt VS Code extension to compile manually;
  2. Use the function compile programmatically:
import{compile}from'scryptlib';
...
compile({path: contractFilePath// the file path of the contract},{artifact: true// set this flag to be `true` to get the artifact file outputasm: true// set this flag to be `true` to get the asm file outputoptimize: false//set this flag to be `true` to get optimized asm opcodesourceMap: true//set this flag to be `true` to get source maphex: true//set this flag to be `true` to get hex format scriptstdout: false//set this flag to be `true` to make that the compiler will output the compilation result through stdout});
  1. compileAsync is the asynchronous version of the function compile
import{compileAsync}from'scryptlib';
...
compileAsync({path: contractFilePath// the file path of the contract},settings) : Promise<CompileResult>;
  1. Run npx command in CLI:
# install compiler binary
npx scryptlib download
# the latest compiler may be incompatible with the current scryptlib
npx scryptlib download latest
# compiling contract
npx scryptlib compile your_directory/your_scrypt.scrypt

Types

1. Basic Types

All basic types of the sCrypt language have their corresponding javascript classes in scryptlib. In this way, the type of parameters could be checked and potential bugs can be detected before running.

Types (scrypt)scryptlib (javascript/typescript)
intInt(1) or number or bigint
boolBool(true) or boolean
bytesBytes('0001') or stringToBytes("hello world 😊")
PubKeyPubKey('0001')
PrivKeyPrivKey(1)
SigSig('0001')
Ripemd160Ripemd160('0001')
Sha1Sha1('0001')
Sha256Sha256('0001')
SigHashTypeSigHashType('01')
SigHashPreimageSigHashPreimage('010001')
OpCodeTypeOpCodeType('76')

2. Array Types

scryptlib uses javascript array to represent the array types of the sCrypt language.

[[1,3,1]]// represent `int[1][3]` in **sCrypt** language[Bytes("00"),Bytes("00"),Bytes("00")]// represent `bytes[3]` in **sCrypt** language

3. Structure and Type Aliases

The structure in sCrypt needs to be represented by object in SDK. When creating a structure, all members must specify values. Use . to access structure members.

A type alias needs to be represented by a value corresponding to the original type

Structure and type aliases defined in sCrypt:

/*Person is structure and Male, Female are type aliases */structPerson{bytesaddr;boolisMale;intage;}typeMale=Person;typeFemale=Person;contractPersonContract{Maleman;Femalewoman;
...
}

Access Structure and type aliases by SDK :

constPersonContract=buildContractClass(loadArtifact('person.json'));letman={isMale: true,age: 14n,addr: Bytes("68656c6c6f20776f726c6421")};man.age=20n;letwoman={isMale: false,age: 18n,addr: Bytes("68656c6c6f20776f726c6421")};woman.addr=Bytes("")constinstance=newPersonContract(man,woman);

4. HashedMap

HashedMap is a hashtable-like data structure.

5. Library

Library is another composite types. When the constructor parameter of the contract contains library, we have to pass an array according to the constructor parameter of the library.

Library defined in sCrypt:

libraryL{privateintx;constructor(inta,intb){this.x=a+b;}functionf() : int{returnthis.x;}}contractTest{publicintx;Ll;publicfunctionunlock(intx){require(this.l.f()==x+this.x);}}

Access Library by SDK :

constTest=buildContractClass(loadArtifact('test.json'));letl=[1n,2n];lettest=newTest(1n,l);

Sometimes the constructor parameters of the library may be generic types. At this time, the sdk will deduce the generic type based on the constructor arguments you pass.

Deploy a Contract and Call Its Function

Both deploying a contract and calling a contract function are achieved by sending a transaction. Generally speaking,

  • deploying a contract needs the locking script in the output of this transaction to be set properly;
  • calling a contract function needs the unlocking script in the input of this transaction to be set properly.

There are 2 steps.

1. Get Locking and Unlocking Script

You can use the artifact file to build a reflected contract class in Javascript/TypeScript like this:

constMyContract=buildContractClass(JSON.parse(artifactFileContent));

To create an instance of the contract class, for example:

constinstance=newMyContract(1234n,true, ...parameters);

To get the locking script, use:

constlockingScript=instance.lockingScript;// To convert it to ASM/hex formatconstlockingScriptASM=lockingScript.toASM();constlockingScriptHex=lockingScript.toHex();

To get the unlocking script, just call the function and turn the result to bsv.Script object, for example:

constfuncCall=instance.someFunc(newSig('0123456'),newBytes('aa11ff'), ...parameters);constunlockingScript=funcCall.toScript();// To convert it to ASM/hex formatconstunlockingScriptASM=unlockingScript.toASM();constunlockingScriptHex=unlockingScript.toHex();

2. Wrap Locking and Unlocking Script into a Transaction

Chained APIs make building transactions super easy.

Local Unit Tests

A useful method verify(txContext) is provided for each contract function call. It would execute the function call with the given context locally. The txContext argument provides some context information of the current transaction, needed only if signature is checked inside the contract.

{tx?: bsv.Transaction;// current transaction represented in bsv.Transaction object
inputIndex?: number;// input index, default value: 0/** * @deprecated no need any more */
inputSatoshis?: number;// input amount in satoshis
opReturn?: string;// contract state in ASM format
opReturnHex?: string;// contract state in hex format}

It returns an object:

{
success: boolean;// script evaluates to true or false
error: string;// error message, empty if success}

It usually appears in unit tests, like:

constcontext={ tx, inputIndex, inputSatoshis };// 1) set context per verify()constfuncCall=instance.someFunc(Sig('0123456'),Bytes('aa11ff'), ...parameters);constresult=funcCall.verify(context);// 2) alternatively, context can be set at instance level and all following verify() will use itinstance.txContext=context;constresult=funcCall.verify();expect(result.success,result.error).to.be.true;assert.isFalse(result.success,result.error);

Contracts with State

sCrypt offers stateful contracts. Declare any property that is part of the state with a decorator @state in a contract, for example:

contractCounter{
@stateintcounter;constructor(intcounter){this.counter=counter;}}

Use the initial state to instantiate the contract and read the state by accessing the properties of the contract instance.

constinstance=newCounter(0n);letstate=instance.counter;// update stateinstance.counter++;

Then use instance.getNewStateScript() to get a locking script that includes the new state. It accepts an object as a parameter. Each key of the object is the name of a state property, and each value is the value of the state property. You should provide all state properties in the object.

consttx=newTx(inputSatoshis);letnewLockingScript=instance.getNewStateScript({counter: 1});tx.addOutput(newbsv.Transaction.Output({script: newLockingScript,satoshis: outputAmount}))preimage=getPreimage(tx,instance.lockingScript,inputSatoshis)

You can also access the state of the contract by accessing the properties of the instance.

instance.counter++;instance.person.name=Bytes('0001');

You can also maintain state manually to, for example, optimize your contract or use customized state de/serialization rawstate.

Instantiate Inline Assembly Variables

Assembly variables can be replaced with literal Script in ASM format using replace(). Each variable is prefixed by its unique scope, namely, the contract and the function it is under.

constasmVars={'contract1.function1.variable1': 'ff41','contract2.function2.variable2': 'OP_4'};instance.replaceAsmVars(asmVars);

You could find more examples using scryptlib in the boilerplate repository.

Construct contracts from raw transactions

In addition to using a constructor to create a contract, you can also use a raw transaction to construct it.

constaxios=require('axios');constCounter=buildContractClass(loadArtifact("counter_debug.json"));letresponse=awaitaxios.get("https://api.whatsonchain.com/v1/bsv/test/tx/7b9bc5c67c91a3caa4b3212d3a631a4b61e5c660f0369615e6e3a969f6bef4de/hex")// constructor from raw Transaction.letcounter=Counter.fromTransaction(response.data,0/** output index**/);// constructor from Utxo lockingScriptletcounterClone=Counter.fromHex(counter.lockingScript.toHex());

Support browsers that are not compatible with BigInt

Some contracts use Bigint to construct or unlock. but some browsers do not support Bigint, such as IE11. In this case, we use strings to build Bigint.

// polyfillimport'react-app-polyfill/ie11';import'core-js/features/number';import'core-js/features/string';import'core-js/features/array';letdemo=newDemo(Int("11111111111111111111111111111111111"),1n);letresult=demo.add(Int("11111111111111111111111111111111112")).verify();console.assert(result.success,result.error)

About

Javascript SDK

Resources

Stars

48 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages