scryptlib
Advanced tools
Comparing version 2.0.0-beta.6 to 2.0.0
# CHANGELOG | ||
## 2.0.0 | ||
- remove scryptType class, use type | ||
- add bsv typescript defined | ||
- firstCall rename to isGenesis | ||
- auto complete transation sig and sighashpreimage. | ||
- optimize cli | ||
- remove FORKID from sighash flag | ||
- auto calc keyIndex | ||
- Fix genLaunchConfigFile | ||
- rename desc files to contractname.json now | ||
see [PR #211](https://github.com/sCrypt-Inc/scryptlib/pull/211) | ||
*Release Date: 2023/01/08* | ||
## 1.0.9 | ||
@@ -5,0 +24,0 @@ |
@@ -8,2 +8,3 @@ "use strict"; | ||
const deserializer_1 = require("./deserializer"); | ||
const launchConfig_1 = require("./launchConfig"); | ||
const serializer_1 = require("./serializer"); | ||
@@ -56,4 +57,2 @@ const stateful_1 = require("./stateful"); | ||
genLaunchConfig(txContext) { | ||
const constructorArgs = this.contract.ctorArgs().map(p => p.value); | ||
const pubFuncArgs = this.args.map(arg => arg.value); | ||
const pubFunc = this.methodName; | ||
@@ -71,3 +70,3 @@ const name = `Debug ${this.contract.contractName}`; | ||
} | ||
return utils_1.genLaunchConfigFile(constructorArgs, pubFuncArgs, pubFunc, name, program, txCtx, asmArgs); | ||
return launchConfig_1.genLaunchConfigFile(this.contract.resolver, this.contract.ctorArgs(), this.args, pubFunc, name, program, txCtx, asmArgs); | ||
} | ||
@@ -74,0 +73,0 @@ verify(txContext) { |
@@ -404,3 +404,3 @@ "use strict"; | ||
entity.params.forEach(property => { | ||
if (arg[property.name]) { | ||
if (typeof arg[property.name] !== 'undefined') { | ||
clone[property.name] = this.transformerArg(arg[property.name], property, state); | ||
@@ -412,2 +412,5 @@ } | ||
} | ||
else if (typeof arg === 'number') { | ||
return BigInt(arg); | ||
} | ||
return arg; | ||
@@ -652,2 +655,3 @@ } | ||
info: element, | ||
generic: typeCheck_1.hasGeneric(element), | ||
finalType: element.name, | ||
@@ -660,2 +664,3 @@ symbolType: scryptTypes_1.SymbolType.Struct | ||
info: element, | ||
generic: typeCheck_1.hasGeneric(element), | ||
finalType: element.name, | ||
@@ -668,2 +673,3 @@ symbolType: scryptTypes_1.SymbolType.Library | ||
info: element, | ||
generic: typeCheck_1.hasGeneric(element), | ||
finalType: element.name, | ||
@@ -737,7 +743,5 @@ symbolType: scryptTypes_1.SymbolType.Contract | ||
finalType: 'Ripemd160', | ||
generic: false, | ||
symbolType: scryptTypes_1.SymbolType.ScryptType | ||
}; | ||
alias.forEach(element => { | ||
resolvedTypes[element.name] = internal_1.resolveType(element.name, resolvedTypes, contract, statics, alias, library); | ||
}); | ||
const resolver = (type) => { | ||
@@ -749,2 +753,3 @@ if (resolvedTypes[type]) { | ||
return { | ||
generic: false, | ||
finalType: type, | ||
@@ -751,0 +756,0 @@ symbolType: scryptTypes_1.SymbolType.ScryptType |
export { buildContractClass, compile, compileAsync, compileContract, doCompileAsync, getPreimage, signTx, handleCompilerOutput, compileContractAsync, CompilingSettings } from './internal'; | ||
export { bsv, toHex, bin2num, int2Asm, bytes2Literal, bytesToHexString, getValidatedHexString, findStructByType, findStructByName, isArrayType, arrayTypeAndSize, newCall, getNameByType, genLaunchConfigFile, subArrayType, isGenericType, parseGenericType, readLaunchJson, getLowSPreimage, readBytes, parseAbiFromUnlockingScript, findConstStatic, findStatic, resolveConstValue, arrayTypeAndSizeStr, toLiteralArrayType, librarySign, structSign, resolveGenericType, canAssignProperty, buildTypeResolver, getStructDeclaration, getABIDeclaration, typeOfArg, compilerVersion, parseLiteral, isEmpty, JSONParser, getFullFilePath, path2uri, uri2path, md5, FunctionCall, stringToBytes, isScryptType, isSubBytes, toJSON, getMapSortedItem, getSetSortedItem } from './internal'; | ||
export { bsv, toHex, bin2num, int2Asm, bytes2Literal, bytesToHexString, getValidatedHexString, findStructByType, findStructByName, isArrayType, arrayTypeAndSize, newCall, getNameByType, genLaunchConfigFile, subArrayType, isGenericType, parseGenericType, readLaunchJson, getLowSPreimage, parseAbiFromUnlockingScript, findConstStatic, findStatic, resolveConstValue, arrayTypeAndSizeStr, toLiteralArrayType, librarySign, structSign, resolveGenericType, buildTypeResolver, getStructDeclaration, getABIDeclaration, typeOfArg, compilerVersion, parseLiteral, isEmpty, JSONParser, getFullFilePath, path2uri, uri2path, md5, FunctionCall, stringToBytes, isScryptType, isSubBytes, toJSON, getSortedItem } from './internal'; | ||
export { Int, Bool, Bytes, PrivKey, PubKey, Sig, Ripemd160, Sha1, Sha256, SigHashType, SigHashPreimage, OpCodeType, SupportedParamType, PubKeyHash, TxContext, ContractClass, Contract, SortedItem, HashedMap, HashedSet, StructObject, TypeResolver, PrimitiveTypes, AsmVarValues, Arguments, Argument, StructEntity, LibraryEntity, ABIEntity, ABIEntityType, ABI, ParamEntity, BuildType, RelatedInformation, ContractArtifact, VerifyResult, VerifyError, AbstractContract, DebugInfo, DebugModeTag, ContractEntity, TypeInfo, SymbolType, DEFAULT_FLAGS } from './internal'; | ||
@@ -4,0 +4,0 @@ export { hash160, sha256, hash256, and, or, xor, invert, num2bin, buildOpreturnScript, len, buildPublicKeyHashScript, writeVarint, toLEUnsigned } from './internal'; |
@@ -33,3 +33,2 @@ "use strict"; | ||
Object.defineProperty(exports, "getLowSPreimage", { enumerable: true, get: function () { return internal_2.getLowSPreimage; } }); | ||
Object.defineProperty(exports, "readBytes", { enumerable: true, get: function () { return internal_2.readBytes; } }); | ||
Object.defineProperty(exports, "parseAbiFromUnlockingScript", { enumerable: true, get: function () { return internal_2.parseAbiFromUnlockingScript; } }); | ||
@@ -44,3 +43,2 @@ Object.defineProperty(exports, "findConstStatic", { enumerable: true, get: function () { return internal_2.findConstStatic; } }); | ||
Object.defineProperty(exports, "resolveGenericType", { enumerable: true, get: function () { return internal_2.resolveGenericType; } }); | ||
Object.defineProperty(exports, "canAssignProperty", { enumerable: true, get: function () { return internal_2.canAssignProperty; } }); | ||
Object.defineProperty(exports, "buildTypeResolver", { enumerable: true, get: function () { return internal_2.buildTypeResolver; } }); | ||
@@ -63,4 +61,3 @@ Object.defineProperty(exports, "getStructDeclaration", { enumerable: true, get: function () { return internal_2.getStructDeclaration; } }); | ||
Object.defineProperty(exports, "toJSON", { enumerable: true, get: function () { return internal_2.toJSON; } }); | ||
Object.defineProperty(exports, "getMapSortedItem", { enumerable: true, get: function () { return internal_2.getMapSortedItem; } }); | ||
Object.defineProperty(exports, "getSetSortedItem", { enumerable: true, get: function () { return internal_2.getSetSortedItem; } }); | ||
Object.defineProperty(exports, "getSortedItem", { enumerable: true, get: function () { return internal_2.getSortedItem; } }); | ||
var internal_3 = require("./internal"); | ||
@@ -67,0 +64,0 @@ Object.defineProperty(exports, "Int", { enumerable: true, get: function () { return internal_3.Int; } }); |
@@ -11,1 +11,2 @@ export * from './utils'; | ||
export * from './builtins'; | ||
export * from './launchConfig'; |
@@ -23,2 +23,3 @@ "use strict"; | ||
__exportStar(require("./builtins"), exports); | ||
__exportStar(require("./launchConfig"), exports); | ||
//# sourceMappingURL=internal.js.map |
@@ -10,3 +10,3 @@ export declare enum SymbolType { | ||
info?: unknown; | ||
generic?: boolean; | ||
generic: boolean; | ||
finalType: string; | ||
@@ -67,6 +67,5 @@ symbolType: SymbolType; | ||
export declare type HashedMap = Flavor<Map<SupportedParamType, SupportedParamType>, 'HashedMap'>; | ||
export declare function Int(n: number | bigint): Int; | ||
export declare function Int(n: number | bigint | string): Int; | ||
export declare function Bool(b: boolean): Bool; | ||
export declare function Bytes(b: string): Bytes; | ||
export declare function stringToBytes(str: string): Bytes; | ||
export declare function PrivKey(n: Int): PrivKey; | ||
@@ -96,4 +95,3 @@ export declare function PubKey(b: Bytes): PubKey; | ||
}; | ||
export declare function getMapSortedItem<K, V>(map: Map<K, V>, k: K): SortedItem<K>; | ||
export declare function getSetSortedItem<E>(set: Set<E>, k: E): SortedItem<E>; | ||
export declare function getSortedItem<K, V>(collection: Map<K, V> | Set<K>, k: K): SortedItem<K>; | ||
export declare type PrimitiveTypes = Int | Bool | Bytes | PrivKey | PubKey | Sig | Sha256 | Sha1 | SigHashType | Ripemd160 | OpCodeType | HashedMap | HashedSet; | ||
@@ -106,6 +104,4 @@ export declare type SubBytes = PubKey | Sig | Sha256 | Sha1 | SigHashType | Ripemd160 | OpCodeType; | ||
export declare function getValidatedHexString(hex: string, allowEmpty?: boolean): string; | ||
export declare function toJSON(value: SupportedParamType): unknown; | ||
export declare function parseLiteral(l: string, supportInt?: boolean): [SupportedParamType, ScryptType]; | ||
export declare function isScryptType(type: string): boolean; | ||
export declare function isSubBytes(type: string): boolean; | ||
export declare function isBytes(type: string): boolean; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isBytes = exports.isSubBytes = exports.isScryptType = exports.parseLiteral = exports.toJSON = exports.getValidatedHexString = exports.getSetSortedItem = exports.getMapSortedItem = exports.OpCodeType = exports.SigHashPreimage = exports.SigHashType = exports.SigHash = exports.HashedMap = exports.HashedSet = exports.Sha256 = exports.Sha1 = exports.PubKeyHash = exports.Ripemd160 = exports.Sig = exports.PubKey = exports.PrivKey = exports.stringToBytes = exports.Bytes = exports.Bool = exports.Int = exports.ScryptType = exports.SymbolType = void 0; | ||
exports.isBytes = exports.isSubBytes = exports.isScryptType = exports.getValidatedHexString = exports.getSortedItem = exports.OpCodeType = exports.SigHashPreimage = exports.SigHashType = exports.SigHash = exports.HashedMap = exports.HashedSet = exports.Sha256 = exports.Sha1 = exports.PubKeyHash = exports.Ripemd160 = exports.Sig = exports.PubKey = exports.PrivKey = exports.Bytes = exports.Bool = exports.Int = exports.ScryptType = exports.SymbolType = void 0; | ||
var SymbolType; | ||
@@ -39,8 +39,2 @@ (function (SymbolType) { | ||
exports.Bytes = Bytes; | ||
function stringToBytes(str) { | ||
const encoder = new TextEncoder(); | ||
const uint8array = encoder.encode(str); | ||
return getValidatedHexString(Buffer.from(uint8array).toString('hex')); | ||
} | ||
exports.stringToBytes = stringToBytes; | ||
function PrivKey(n) { | ||
@@ -110,3 +104,3 @@ return n; | ||
exports.OpCodeType = OpCodeType; | ||
function getMapSortedItem(map, k) { | ||
function getSortedItem(collection, k) { | ||
return Object.assign({ | ||
@@ -116,15 +110,6 @@ idx: -1n, | ||
}, { | ||
image: new Map(map) | ||
image: collection instanceof Map ? new Map(collection) : new Set(collection) | ||
}); | ||
} | ||
exports.getMapSortedItem = getMapSortedItem; | ||
function getSetSortedItem(set, k) { | ||
return Object.assign({ | ||
idx: -1n, | ||
item: k | ||
}, { | ||
image: new Set(set) | ||
}); | ||
} | ||
exports.getSetSortedItem = getSetSortedItem; | ||
exports.getSortedItem = getSortedItem; | ||
function getValidatedHexString(hex, allowEmpty = true) { | ||
@@ -144,135 +129,2 @@ const ret = hex.trim(); | ||
exports.getValidatedHexString = getValidatedHexString; | ||
function toJSON(value) { | ||
if (Array.isArray(value)) { | ||
const v = value; | ||
return v.map(i => toJSON(i)); | ||
} | ||
else if (typeof value === 'object') { | ||
const copy = {}; | ||
for (const key in value) { | ||
Object.assign(copy, { | ||
[key]: toJSON(value[key]) | ||
}); | ||
} | ||
return copy; | ||
} | ||
else if (typeof value === 'bigint') { | ||
if (value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)) { | ||
return Number(value); | ||
} | ||
else { | ||
return value.toString(); | ||
} | ||
} | ||
else if (typeof value === 'boolean') { | ||
return value; | ||
} | ||
else if (typeof value === 'string') { | ||
const [val, type] = parseLiteral(value); | ||
if (type === ScryptType.BYTES) { | ||
return `b'${val}'`; | ||
} | ||
return value; | ||
} | ||
} | ||
exports.toJSON = toJSON; | ||
function parseLiteral(l, supportInt = false) { | ||
// bool | ||
if (l === 'false') { | ||
return [false, ScryptType.BOOL]; | ||
} | ||
if (l === 'true') { | ||
return [true, ScryptType.BOOL]; | ||
} | ||
if (supportInt) { | ||
// hex int | ||
let m = /^(0x[0-9a-fA-F]+)$/.exec(l); | ||
if (m) { | ||
return [BigInt(m[1]), ScryptType.INT]; | ||
} | ||
// decimal int | ||
m = /^(-?\d+)$/.exec(l); | ||
if (m) { | ||
return [BigInt(m[1]), ScryptType.INT]; | ||
} | ||
} | ||
else { | ||
const m = /^([\da-fA-F]*)$/.exec(l); | ||
if (m) { | ||
return [Bytes(l), ScryptType.BYTES]; | ||
} | ||
} | ||
// bytes | ||
// note: special handling of empty bytes b'' | ||
let m = /^b'([\da-fA-F]*)'$/.exec(l); | ||
if (m) { | ||
return [Bytes(m[1]), ScryptType.BYTES]; | ||
} | ||
// String | ||
m = /^"([\s\S]*)"$/.exec(l); | ||
if (m) { | ||
return [stringToBytes(m[1]), ScryptType.BYTES]; | ||
} | ||
// PrivKey | ||
// 1) decimal int | ||
m = /^PrivKey\((-?\d+)\)$/.exec(l); | ||
if (m) { | ||
return [BigInt(m[1]), ScryptType.PRIVKEY]; | ||
} | ||
// 2) hex int | ||
m = /^PrivKey\((0x[0-9a-fA-F]+)\)$/.exec(l); | ||
if (m) { | ||
return [BigInt(m[1]), ScryptType.PRIVKEY]; | ||
} | ||
// PubKey | ||
m = /^PubKey\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.PUBKEY]; | ||
} | ||
// Sig | ||
m = /^Sig\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.SIG]; | ||
} | ||
// Ripemd160 | ||
m = /^Ripemd160\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.RIPEMD160]; | ||
} | ||
// Sha1 | ||
m = /^Sha1\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.SHA1]; | ||
} | ||
// Sha256 | ||
m = /^Sha256\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.SHA256]; | ||
} | ||
// SigHashType | ||
m = /^SigHashType\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.SIGHASHTYPE]; | ||
} | ||
// SigHashPreimage | ||
m = /^SigHashPreimage\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.SIGHASHPREIMAGE]; | ||
} | ||
// OpCodeType | ||
m = /^OpCodeType\(b'([\da-fA-F]+)'\)$/.exec(l); | ||
if (m) { | ||
const value = getValidatedHexString(m[1]); | ||
return [Bytes(value), ScryptType.OPCODETYPE]; | ||
} | ||
throw new Error(`<${l}> cannot be cast to ASM format, only sCrypt native types supported`); | ||
} | ||
exports.parseLiteral = parseLiteral; | ||
function isScryptType(type) { | ||
@@ -279,0 +131,0 @@ return Object.keys(ScryptType).map(key => ScryptType[key]).includes(type); |
@@ -1,2 +0,2 @@ | ||
import { AbstractContract, Arguments } from '.'; | ||
import { AbstractContract, Arguments, bsv } from '.'; | ||
import { Bytes, Int, SupportedParamType, TypeResolver } from './scryptTypes'; | ||
@@ -23,3 +23,7 @@ export default class Stateful { | ||
static deserializer(type: string, hex: string): SupportedParamType; | ||
static readBytes(br: bsv.encoding.BufferReader): { | ||
data: string; | ||
opcodenum: number; | ||
}; | ||
static parseStateHex(contract: AbstractContract, scriptHex: string): [boolean, Arguments]; | ||
} |
@@ -173,2 +173,37 @@ "use strict"; | ||
} | ||
static readBytes(br) { | ||
try { | ||
const opcodenum = br.readUInt8(); | ||
let len, data; | ||
if (opcodenum == 0) { | ||
data = ''; | ||
} | ||
else if (opcodenum > 0 && opcodenum < _1.bsv.Opcode.OP_PUSHDATA1) { | ||
len = opcodenum; | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === _1.bsv.Opcode.OP_PUSHDATA1) { | ||
len = br.readUInt8(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === _1.bsv.Opcode.OP_PUSHDATA2) { | ||
len = br.readUInt16LE(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === _1.bsv.Opcode.OP_PUSHDATA4) { | ||
len = br.readUInt32LE(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else { | ||
data = _1.num2bin(BigInt(opcodenum - 80), 1); | ||
} | ||
return { | ||
data: data, | ||
opcodenum: opcodenum | ||
}; | ||
} | ||
catch (e) { | ||
throw new Error('readBytes: ' + e); | ||
} | ||
} | ||
static parseStateHex(contract, scriptHex) { | ||
@@ -193,3 +228,3 @@ const metaScript = scriptHex.substr(scriptHex.length - 10, 10); | ||
else { | ||
const { data } = _1.readBytes(br); | ||
const { data } = Stateful.readBytes(br); | ||
stateTemplateArgs.set(`<${param.name}>`, data ? _1.bsv.Script.fromASM(data).toHex() : ''); | ||
@@ -196,0 +231,0 @@ } |
import { Argument, Arguments, LibraryEntity, ParamEntity, StructEntity } from '.'; | ||
import { SupportedParamType, TypeResolver } from './scryptTypes'; | ||
import { AliasEntity, StaticEntity } from './internal'; | ||
import { SupportedParamType, TypeInfo, TypeResolver } from './scryptTypes'; | ||
export declare function typeOfArg(a: SupportedParamType): string; | ||
@@ -21,2 +22,3 @@ /** | ||
export declare function checkSupportedParamType(arg: SupportedParamType, param: ParamEntity, resolver: TypeResolver): Error | undefined; | ||
export declare function hasGeneric(entity: StructEntity | LibraryEntity): boolean; | ||
export declare function deduceGenericStruct(param: ParamEntity, entity: StructEntity, resolver: TypeResolver): StructEntity | LibraryEntity | Error; | ||
@@ -29,1 +31,18 @@ export declare function deduceGenericLibrary(param: ParamEntity, entity: LibraryEntity, resolver: TypeResolver): LibraryEntity | Error; | ||
export declare function flatternArg(arg: Argument, resolver: TypeResolver, options: FlatOptions): Arguments; | ||
export declare function findConstStatic(statics: StaticEntity[], name: string): StaticEntity | undefined; | ||
export declare function findStatic(statics: StaticEntity[], name: string): StaticEntity | undefined; | ||
export declare function resolveType(type: string, originTypes: Record<string, TypeInfo>, contract: string, statics: StaticEntity[], alias: AliasEntity[], librarys: LibraryEntity[]): TypeInfo; | ||
/** | ||
* check if a type is generic type | ||
* @param type | ||
* @returns | ||
*/ | ||
export declare function isGenericType(type: string): boolean; | ||
/** | ||
* | ||
* @param type eg. HashedMap<int,int> | ||
* @param eg. ["HashedMap", ["int", "int"]}] An array generic types returned by @getGenericDeclaration | ||
* @returns {"K": "int", "V": "int"} | ||
*/ | ||
export declare function parseGenericType(type: string): [string, Array<string>]; | ||
export declare function resolveGenericType(genericTypeMap: Record<string, string>, type: string): string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.flatternArg = exports.deduceGenericLibrary = exports.deduceGenericStruct = exports.checkSupportedParamType = exports.subArrayType = exports.toLiteralArrayType = exports.arrayTypeAndSize = exports.arrayTypeAndSizeStr = exports.typeOfArg = void 0; | ||
exports.resolveGenericType = exports.parseGenericType = exports.isGenericType = exports.resolveType = exports.findStatic = exports.findConstStatic = exports.flatternArg = exports.deduceGenericLibrary = exports.deduceGenericStruct = exports.hasGeneric = exports.checkSupportedParamType = exports.subArrayType = exports.toLiteralArrayType = exports.arrayTypeAndSize = exports.arrayTypeAndSizeStr = exports.typeOfArg = void 0; | ||
const _1 = require("."); | ||
@@ -207,2 +207,3 @@ const internal_1 = require("./internal"); | ||
} | ||
exports.hasGeneric = hasGeneric; | ||
function isGenericParamType(entity, t) { | ||
@@ -219,4 +220,4 @@ return entity.genericTypes.includes(t); | ||
if (Object.keys(this.inferred).length > 0) { | ||
if (_1.isGenericType(type)) { | ||
const [name, types] = _1.parseGenericType(type); | ||
if (isGenericType(type)) { | ||
const [name, types] = parseGenericType(type); | ||
return internal_1.toGenericType(name, types.map(t => this.inferred[t] || t)); | ||
@@ -234,3 +235,3 @@ } | ||
const typeInfo = this.resolver(param.type); | ||
const [name, genericTypes] = _1.parseGenericType(typeInfo.finalType); | ||
const [name, genericTypes] = parseGenericType(typeInfo.finalType); | ||
if (this.entity.name !== name) { | ||
@@ -285,3 +286,3 @@ return new Error(`Generic inference failed, expected ${name} but got ${this.entity.name}`); | ||
if (!hasGeneric(entity)) { | ||
return new Error(`struct ${entity.name} does not has any generic type`); | ||
return entity; | ||
} | ||
@@ -298,3 +299,3 @@ const deducer = new GenericDeducer(entity, resolver); | ||
if (!hasGeneric(entity)) { | ||
return new Error(`library ${entity.name} does not has any generic type`); | ||
return entity; | ||
} | ||
@@ -504,2 +505,159 @@ const deducer = new GenericDeducer(entity, resolver); | ||
exports.flatternArg = flatternArg; | ||
function findConstStatic(statics, name) { | ||
return statics.find(s => { | ||
return s.const === true && s.name === name; | ||
}); | ||
} | ||
exports.findConstStatic = findConstStatic; | ||
function findStatic(statics, name) { | ||
return statics.find(s => { | ||
return s.name === name; | ||
}); | ||
} | ||
exports.findStatic = findStatic; | ||
function resolveAlias(alias, type) { | ||
const a = alias.find(a => { | ||
return a.name === type; | ||
}); | ||
if (a) { | ||
return resolveAlias(alias, a.type); | ||
} | ||
return type; | ||
} | ||
function resolveType(type, originTypes, contract, statics, alias, librarys) { | ||
type = resolveAlias(alias, type); | ||
if (_1.isArrayType(type)) { | ||
const [elemTypeName, sizes] = arrayTypeAndSizeStr(type); | ||
const elemTypeInfo = resolveType(elemTypeName, originTypes, contract, statics, alias, librarys); | ||
if (_1.isArrayType(elemTypeInfo.finalType)) { | ||
const [elemTypeName_, sizes_] = arrayTypeAndSizeStr(elemTypeInfo.finalType); | ||
const elemTypeInfo_ = resolveType(elemTypeName_, originTypes, contract, statics, alias, librarys); | ||
return { | ||
info: elemTypeInfo.info, | ||
generic: elemTypeInfo.generic, | ||
finalType: resolveConstStatic(contract, toLiteralArrayType(elemTypeInfo_.finalType, sizes.concat(sizes_)), statics), | ||
symbolType: elemTypeInfo.symbolType | ||
}; | ||
} | ||
return { | ||
info: elemTypeInfo.info, | ||
generic: elemTypeInfo.generic, | ||
finalType: resolveConstStatic(contract, toLiteralArrayType(elemTypeInfo.finalType, sizes), statics), | ||
symbolType: elemTypeInfo.symbolType | ||
}; | ||
} | ||
else if (isGenericType(type)) { | ||
const [name, genericTypes] = parseGenericType(type); | ||
const typeInfo = resolveType(name, originTypes, contract, statics, alias, librarys); | ||
const gts = genericTypes.map(t => resolveType(t, originTypes, contract, statics, alias, librarys).finalType); | ||
return { | ||
info: typeInfo.info, | ||
generic: true, | ||
finalType: internal_1.toGenericType(typeInfo.finalType, gts), | ||
symbolType: typeInfo.symbolType | ||
}; | ||
} | ||
if (originTypes[type]) { | ||
return originTypes[type]; | ||
} | ||
else if (scryptTypes_1.isScryptType(type)) { | ||
return { | ||
finalType: type, | ||
generic: false, | ||
symbolType: scryptTypes_1.SymbolType.ScryptType | ||
}; | ||
} | ||
else { | ||
return { | ||
finalType: type, | ||
generic: false, | ||
symbolType: scryptTypes_1.SymbolType.Unknown | ||
}; | ||
} | ||
} | ||
exports.resolveType = resolveType; | ||
function resolveConstStatic(contract, type, statics) { | ||
if (_1.isArrayType(type)) { | ||
const [elemTypeName, arraySizes] = arrayTypeAndSizeStr(type); | ||
const sizes = arraySizes.map(size => { | ||
if (/^(\d)+$/.test(size)) { | ||
return parseInt(size); | ||
} | ||
else { | ||
// size as a static const | ||
const size_ = (size.indexOf('.') > 0) ? size : `${contract}.${size}`; | ||
const value = findConstStatic(statics, size_); | ||
if (!value) { | ||
// Unable to solve when the subscript of the array is a function parameter, [CTC](https://scryptdoc.readthedocs.io/en/latest/ctc.html) | ||
return size; | ||
} | ||
return value.value; | ||
} | ||
}); | ||
return toLiteralArrayType(elemTypeName, sizes); | ||
} | ||
return type; | ||
} | ||
/** | ||
* check if a type is generic type | ||
* @param type | ||
* @returns | ||
*/ | ||
function isGenericType(type) { | ||
return /^([\w]+)<([\w,[\]\s<>]+)>$/.test(type); | ||
} | ||
exports.isGenericType = isGenericType; | ||
/** | ||
* | ||
* @param type eg. HashedMap<int,int> | ||
* @param eg. ["HashedMap", ["int", "int"]}] An array generic types returned by @getGenericDeclaration | ||
* @returns {"K": "int", "V": "int"} | ||
*/ | ||
function parseGenericType(type) { | ||
if (isGenericType(type)) { | ||
const m = type.match(/([\w]+)<([\w,[\]<>\s]+)>$/); | ||
if (m) { | ||
const library = m[1]; | ||
const realTypes = []; | ||
const brackets = []; | ||
let tmpType = ''; | ||
for (let i = 0; i < m[2].length; i++) { | ||
const ch = m[2].charAt(i); | ||
if (ch === '<' || ch === '[') { | ||
brackets.push(ch); | ||
} | ||
else if (ch === '>' || ch === ']') { | ||
brackets.pop(); | ||
} | ||
else if (ch === ',') { | ||
if (brackets.length === 0) { | ||
realTypes.push(tmpType.trim()); | ||
tmpType = ''; | ||
continue; | ||
} | ||
} | ||
tmpType += ch; | ||
} | ||
realTypes.push(tmpType.trim()); | ||
return [library, realTypes]; | ||
} | ||
} | ||
throw new Error(`"${type}" is not generic type`); | ||
} | ||
exports.parseGenericType = parseGenericType; | ||
function resolveGenericType(genericTypeMap, type) { | ||
if (Object.keys(genericTypeMap).length > 0) { | ||
if (isGenericType(type)) { | ||
const [name, types] = parseGenericType(type); | ||
return internal_1.toGenericType(name, types.map(t => genericTypeMap[t] || t)); | ||
} | ||
if (_1.isArrayType(type)) { | ||
const [elem, sizes] = arrayTypeAndSizeStr(type); | ||
return toLiteralArrayType(elem, sizes.map(t => genericTypeMap[t] || t)); | ||
} | ||
return genericTypeMap[type] || type; | ||
} | ||
return type; | ||
} | ||
exports.resolveGenericType = resolveGenericType; | ||
//# sourceMappingURL=typeCheck.js.map |
/// <reference types="node" /> | ||
import * as bsv from 'bsv'; | ||
export { bsv }; | ||
import { ABIEntity, LibraryEntity, TypeInfo } from '.'; | ||
import { OpCode, StaticEntity } from './compilerWrapper'; | ||
import { VerifyError } from './contract'; | ||
import { AbstractContract, AliasEntity, AsmVarValues, CompileResult, DebugLaunch, FileUri, Script, StructEntity, SupportedParamType, TxContext } from './internal'; | ||
import { ABIEntity, LibraryEntity } from '.'; | ||
import { OpCode } from './compilerWrapper'; | ||
import { AbstractContract, CompileResult, Script, StructEntity, SupportedParamType } from './internal'; | ||
export declare const DEFAULT_FLAGS: number; | ||
@@ -52,5 +51,3 @@ export declare const DEFAULT_SIGHASH_TYPE: number; | ||
export declare function newCall(Cls: typeof AbstractContract, args: Array<SupportedParamType>): AbstractContract; | ||
export declare function genLaunchConfigFile(constructorArgs: SupportedParamType[], pubFuncArgs: SupportedParamType[], pubFunc: string, name: string, program: string, txContext: TxContext, asmArgs: AsmVarValues): FileUri; | ||
export declare function resolveConstValue(node: any): string | undefined; | ||
export declare function resolveType(type: string, originTypes: Record<string, TypeInfo>, contract: string, statics: StaticEntity[], alias: AliasEntity[], librarys: LibraryEntity[]): TypeInfo; | ||
export declare function ansiRegex({ onlyFirst }?: { | ||
@@ -60,24 +57,4 @@ onlyFirst?: boolean; | ||
export declare function stripAnsi(string: string): string; | ||
export declare function findConstStatic(statics: StaticEntity[], name: string): StaticEntity | undefined; | ||
export declare function findStatic(statics: StaticEntity[], name: string): StaticEntity | undefined; | ||
export declare function buildContractCode(hexTemplateArgs: Map<string, string>, hexTemplateInlineASM: Map<string, string>, hexTemplate: string): bsv.Script; | ||
export declare function readBytes(br: bsv.encoding.BufferReader): { | ||
data: string; | ||
opcodenum: number; | ||
}; | ||
/** | ||
* check if a type is generic type | ||
* @param type | ||
* @returns | ||
*/ | ||
export declare function isGenericType(type: string): boolean; | ||
/** | ||
* | ||
* @param type eg. HashedMap<int,int> | ||
* @param eg. ["HashedMap", ["int", "int"]}] An array generic types returned by @getGenericDeclaration | ||
* @returns {"K": "int", "V": "int"} | ||
*/ | ||
export declare function parseGenericType(type: string): [string, Array<string>]; | ||
export declare function readLaunchJson(error: VerifyError): DebugLaunch | undefined; | ||
/** | ||
* Parse out which public function is called through unlocking script | ||
@@ -89,6 +66,4 @@ * @param contract | ||
export declare function parseAbiFromUnlockingScript(contract: AbstractContract, hex: string): ABIEntity; | ||
export declare function resolveGenericType(genericTypeMap: Record<string, string>, type: string): string; | ||
export declare function librarySign(genericEntity: LibraryEntity): string; | ||
export declare function structSign(structEntity: StructEntity): string; | ||
export declare function canAssignProperty(libraryAst: LibraryEntity): boolean; | ||
export declare function JSONParser(file: string): Promise<boolean>; | ||
@@ -95,0 +70,0 @@ export declare function JSONParserSync(file: string): any; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.md5 = exports.findSrcInfoV1 = exports.findSrcInfoV2 = exports.JSONStringify = exports.JSONParserSync = exports.JSONParser = exports.canAssignProperty = exports.structSign = exports.librarySign = exports.resolveGenericType = exports.parseAbiFromUnlockingScript = exports.readLaunchJson = exports.parseGenericType = exports.isGenericType = exports.readBytes = exports.buildContractCode = exports.findStatic = exports.findConstStatic = exports.stripAnsi = exports.ansiRegex = exports.resolveType = exports.resolveConstValue = exports.genLaunchConfigFile = exports.newCall = exports.compileContractAsync = exports.compileContract = exports.isEmpty = exports.readFileByLine = exports.subscript = exports.toGenericType = exports.findStructByType = exports.getNameByType = exports.isArrayType = exports.findStructByName = exports.uri2path = exports.path2uri = exports.isNode = exports.getLowSPreimage = exports.hashIsPositiveNumber = exports.getPreimage = exports.signTx = exports.hexStringToBytes = exports.bytesToHexString = exports.bytes2Literal = exports.utf82Hex = exports.toHex = exports.uint82hex = exports.asm2int = exports.int2Asm = exports.DEFAULT_SIGHASH_TYPE = exports.DEFAULT_FLAGS = exports.bsv = void 0; | ||
exports.md5 = exports.findSrcInfoV1 = exports.findSrcInfoV2 = exports.JSONStringify = exports.JSONParserSync = exports.JSONParser = exports.structSign = exports.librarySign = exports.parseAbiFromUnlockingScript = exports.buildContractCode = exports.stripAnsi = exports.ansiRegex = exports.resolveConstValue = exports.newCall = exports.compileContractAsync = exports.compileContract = exports.isEmpty = exports.readFileByLine = exports.subscript = exports.toGenericType = exports.findStructByType = exports.getNameByType = exports.isArrayType = exports.findStructByName = exports.uri2path = exports.path2uri = exports.isNode = exports.getLowSPreimage = exports.hashIsPositiveNumber = exports.getPreimage = exports.signTx = exports.hexStringToBytes = exports.bytesToHexString = exports.bytes2Literal = exports.utf82Hex = exports.toHex = exports.uint82hex = exports.asm2int = exports.int2Asm = exports.DEFAULT_SIGHASH_TYPE = exports.DEFAULT_FLAGS = exports.bsv = void 0; | ||
const json_ext_1 = require("@discoveryjs/json-ext"); | ||
@@ -9,7 +9,5 @@ const bsv = require("bsv"); | ||
const fs = require("fs"); | ||
const os_1 = require("os"); | ||
const path_1 = require("path"); | ||
const sourcemap_codec_1 = require("sourcemap-codec"); | ||
const url_1 = require("url"); | ||
const _1 = require("."); | ||
const compilerWrapper_1 = require("./compilerWrapper"); | ||
@@ -222,4 +220,4 @@ const internal_1 = require("./internal"); | ||
} | ||
if (isGenericType(type)) { | ||
const [tn, _] = parseGenericType(type); | ||
if (typeCheck_1.isGenericType(type)) { | ||
const [tn, _] = typeCheck_1.parseGenericType(type); | ||
return getNameByType(tn); | ||
@@ -315,54 +313,2 @@ } | ||
exports.newCall = newCall; | ||
function genLaunchConfigFile(constructorArgs, pubFuncArgs, pubFunc, name, program, txContext, asmArgs) { | ||
// some artifact without sourceMap will not have file property. | ||
if (!program) { | ||
return ''; | ||
} | ||
const debugConfig = { | ||
type: 'scrypt', | ||
request: 'launch', | ||
internalConsoleOptions: 'openOnSessionStart', | ||
name: name, | ||
program: program, | ||
constructorArgs: internal_1.toJSON(constructorArgs), | ||
pubFunc: pubFunc, | ||
pubFuncArgs: internal_1.toJSON(pubFuncArgs) | ||
}; | ||
const debugTxContext = {}; | ||
if (!isEmpty(txContext)) { | ||
const tx = txContext.tx || ''; | ||
const inputIndex = txContext.inputIndex || 0; | ||
if (tx) { | ||
const inputSatoshis = txContext.inputSatoshis || tx.getInputAmount(inputIndex); | ||
Object.assign(debugTxContext, { hex: tx.toString(), inputIndex, inputSatoshis }); | ||
} | ||
if (txContext.opReturn) { | ||
Object.assign(debugTxContext, { opReturn: txContext.opReturn }); | ||
} | ||
else if (txContext.opReturnHex) { | ||
Object.assign(debugTxContext, { opReturnHex: txContext.opReturnHex }); | ||
} | ||
} | ||
if (!isEmpty(asmArgs)) { | ||
Object.assign(debugConfig, { asmArgs: asmArgs }); | ||
} | ||
if (!isEmpty(debugTxContext)) { | ||
Object.assign(debugConfig, { txContext: debugTxContext }); | ||
} | ||
const launch = { | ||
version: '0.2.0', | ||
configurations: [debugConfig] | ||
}; | ||
const jsonstr = JSON.stringify(launch, null, 2); | ||
if (isNode()) { | ||
const filename = `${name}-launch.json`; | ||
const file = path_1.join(fs.mkdtempSync(`${os_1.tmpdir()}${path_1.sep}sCrypt.`), filename); | ||
fs.writeFileSync(file, jsonstr); | ||
return path2uri(file); | ||
} | ||
else { | ||
console.error(`${pubFunc}() call fail, see launch.json`, jsonstr); | ||
} | ||
} | ||
exports.genLaunchConfigFile = genLaunchConfigFile; | ||
function resolveConstValue(node) { | ||
@@ -390,90 +336,2 @@ let value = undefined; | ||
exports.resolveConstValue = resolveConstValue; | ||
function resolveType(type, originTypes, contract, statics, alias, librarys) { | ||
const typeInfo = resolveAliasType(originTypes, alias, type); | ||
if (isArrayType(typeInfo.finalType)) { | ||
return { | ||
generic: typeInfo.generic, | ||
info: typeInfo.info, | ||
finalType: resolveArrayType(contract, typeInfo.finalType, statics), | ||
symbolType: typeInfo.symbolType | ||
}; | ||
} | ||
return typeInfo; | ||
} | ||
exports.resolveType = resolveType; | ||
function resolveArrayType(contract, type, statics) { | ||
if (isArrayType(type)) { | ||
const [elemTypeName, arraySizes] = typeCheck_1.arrayTypeAndSizeStr(type); | ||
const sizes = arraySizes.map(size => { | ||
if (/^(\d)+$/.test(size)) { | ||
return parseInt(size); | ||
} | ||
else { | ||
// size as a static const | ||
const size_ = (size.indexOf('.') > 0) ? size : `${contract}.${size}`; | ||
const value = findConstStatic(statics, size_); | ||
if (!value) { | ||
// Unable to solve when the subscript of the array is a function parameter, [CTC](https://scryptdoc.readthedocs.io/en/latest/ctc.html) | ||
return size; | ||
} | ||
return value.value; | ||
} | ||
}); | ||
return _1.toLiteralArrayType(elemTypeName, sizes); | ||
} | ||
return type; | ||
} | ||
function resolveAliasType(originTypes, alias, type) { | ||
if (isArrayType(type)) { | ||
const [elemTypeName, sizes] = typeCheck_1.arrayTypeAndSizeStr(type); | ||
const elemTypeInfo = resolveAliasType(originTypes, alias, elemTypeName); | ||
if (isArrayType(elemTypeInfo.finalType)) { | ||
const [elemTypeName_, sizes_] = typeCheck_1.arrayTypeAndSizeStr(elemTypeInfo.finalType); | ||
return { | ||
info: elemTypeInfo.info, | ||
generic: elemTypeInfo.generic, | ||
finalType: _1.toLiteralArrayType(elemTypeName_, sizes.concat(sizes_)), | ||
symbolType: elemTypeInfo.symbolType | ||
}; | ||
} | ||
return { | ||
info: elemTypeInfo.info, | ||
generic: elemTypeInfo.generic, | ||
finalType: _1.toLiteralArrayType(elemTypeInfo.finalType, sizes), | ||
symbolType: elemTypeInfo.symbolType | ||
}; | ||
} | ||
else if (isGenericType(type)) { | ||
const [name, genericTypes] = parseGenericType(type); | ||
const typeInfo = resolveAliasType(originTypes, alias, name); | ||
const gts = genericTypes.map(t => resolveAliasType(originTypes, alias, t).finalType); | ||
return { | ||
info: typeInfo.info, | ||
generic: true, | ||
finalType: toGenericType(typeInfo.finalType, gts), | ||
symbolType: typeInfo.symbolType | ||
}; | ||
} | ||
const a = alias.find(a => { | ||
return a.name === type; | ||
}); | ||
if (a) { | ||
return resolveAliasType(originTypes, alias, a.type); | ||
} | ||
else if (originTypes[type]) { | ||
return originTypes[type]; | ||
} | ||
else if (internal_1.isScryptType(type)) { | ||
return { | ||
finalType: type, | ||
symbolType: _1.SymbolType.ScryptType | ||
}; | ||
} | ||
else { | ||
return { | ||
finalType: type, | ||
symbolType: _1.SymbolType.Unknown | ||
}; | ||
} | ||
} | ||
function ansiRegex({ onlyFirst = false } = {}) { | ||
@@ -494,14 +352,2 @@ const pattern = [ | ||
exports.stripAnsi = stripAnsi; | ||
function findConstStatic(statics, name) { | ||
return statics.find(s => { | ||
return s.const === true && s.name === name; | ||
}); | ||
} | ||
exports.findConstStatic = findConstStatic; | ||
function findStatic(statics, name) { | ||
return statics.find(s => { | ||
return s.name === name; | ||
}); | ||
} | ||
exports.findStatic = findStatic; | ||
function escapeRegExp(stringToGoIntoTheRegex) { | ||
@@ -525,97 +371,3 @@ return stringToGoIntoTheRegex.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); | ||
exports.buildContractCode = buildContractCode; | ||
function readBytes(br) { | ||
try { | ||
const opcodenum = br.readUInt8(); | ||
let len, data; | ||
if (opcodenum == 0) { | ||
data = ''; | ||
} | ||
else if (opcodenum > 0 && opcodenum < bsv.Opcode.OP_PUSHDATA1) { | ||
len = opcodenum; | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === bsv.Opcode.OP_PUSHDATA1) { | ||
len = br.readUInt8(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === bsv.Opcode.OP_PUSHDATA2) { | ||
len = br.readUInt16LE(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else if (opcodenum === bsv.Opcode.OP_PUSHDATA4) { | ||
len = br.readUInt32LE(); | ||
data = br.read(len).toString('hex'); | ||
} | ||
else { | ||
data = _1.num2bin(BigInt(opcodenum - 80), 1); | ||
} | ||
return { | ||
data: data, | ||
opcodenum: opcodenum | ||
}; | ||
} | ||
catch (e) { | ||
throw new Error('readBytes: ' + e); | ||
} | ||
} | ||
exports.readBytes = readBytes; | ||
/** | ||
* check if a type is generic type | ||
* @param type | ||
* @returns | ||
*/ | ||
function isGenericType(type) { | ||
return /^([\w]+)<([\w,[\]\s<>]+)>$/.test(type); | ||
} | ||
exports.isGenericType = isGenericType; | ||
/** | ||
* | ||
* @param type eg. HashedMap<int,int> | ||
* @param eg. ["HashedMap", ["int", "int"]}] An array generic types returned by @getGenericDeclaration | ||
* @returns {"K": "int", "V": "int"} | ||
*/ | ||
function parseGenericType(type) { | ||
if (isGenericType(type)) { | ||
const m = type.match(/([\w]+)<([\w,[\]<>\s]+)>$/); | ||
if (m) { | ||
const library = m[1]; | ||
const realTypes = []; | ||
const brackets = []; | ||
let tmpType = ''; | ||
for (let i = 0; i < m[2].length; i++) { | ||
const ch = m[2].charAt(i); | ||
if (ch === '<' || ch === '[') { | ||
brackets.push(ch); | ||
} | ||
else if (ch === '>' || ch === ']') { | ||
brackets.pop(); | ||
} | ||
else if (ch === ',') { | ||
if (brackets.length === 0) { | ||
realTypes.push(tmpType.trim()); | ||
tmpType = ''; | ||
continue; | ||
} | ||
} | ||
tmpType += ch; | ||
} | ||
realTypes.push(tmpType.trim()); | ||
return [library, realTypes]; | ||
} | ||
} | ||
throw new Error(`"${type}" is not generic type`); | ||
} | ||
exports.parseGenericType = parseGenericType; | ||
const LINKPATTERN = /(\[((!\[[^\]]*?\]\(\s*)([^\s()]+?)\s*\)\]|(?:\\\]|[^\]])*\])\(\s*)(([^\s()]|\([^\s()]*?\))+)\s*(".*?")?\)/g; | ||
function readLaunchJson(error) { | ||
for (const match of error.matchAll(LINKPATTERN)) { | ||
if (match[5] && match[5].startsWith('scryptlaunch')) { | ||
const file = match[5].replace(/scryptlaunch/, 'file'); | ||
return JSON.parse(fs.readFileSync(uri2path(file)).toString()); | ||
} | ||
} | ||
return undefined; | ||
} | ||
exports.readLaunchJson = readLaunchJson; | ||
/** | ||
* Parse out which public function is called through unlocking script | ||
@@ -644,17 +396,2 @@ * @param contract | ||
exports.parseAbiFromUnlockingScript = parseAbiFromUnlockingScript; | ||
function resolveGenericType(genericTypeMap, type) { | ||
if (Object.keys(genericTypeMap).length > 0) { | ||
if (isGenericType(type)) { | ||
const [name, types] = parseGenericType(type); | ||
return toGenericType(name, types.map(t => genericTypeMap[t] || t)); | ||
} | ||
if (isArrayType(type)) { | ||
const [elem, sizes] = typeCheck_1.arrayTypeAndSizeStr(type); | ||
return _1.toLiteralArrayType(elem, sizes.map(t => genericTypeMap[t] || t)); | ||
} | ||
return genericTypeMap[type] || type; | ||
} | ||
return type; | ||
} | ||
exports.resolveGenericType = resolveGenericType; | ||
function librarySign(genericEntity) { | ||
@@ -670,9 +407,2 @@ return `[${genericEntity.params.map(p => p.type).join(',')}]`; | ||
exports.structSign = structSign; | ||
// If the property is the same as the construction parameter, there may be no constructor, in which case the construction parameter can be assigned to the property. But this does not guarantee that the property is always correct, the user may have modified the value of the property in the constructor | ||
function canAssignProperty(libraryAst) { | ||
return libraryAst.params.length === libraryAst.properties.length && libraryAst.params.every((param, index) => { | ||
return param.name === libraryAst.properties[index].name && param.type === libraryAst.properties[index].type; | ||
}); | ||
} | ||
exports.canAssignProperty = canAssignProperty; | ||
async function JSONParser(file) { | ||
@@ -679,0 +409,0 @@ return new Promise((resolve, reject) => { |
{ | ||
"name": "scryptlib", | ||
"version": "2.0.0-beta.6", | ||
"version": "2.0.0", | ||
"description": "Javascript SDK for integration of Bitcoin SV Smart Contracts written in sCrypt language.", | ||
@@ -5,0 +5,0 @@ "engines": { |
105
README.md
@@ -70,3 +70,3 @@ # scryptlib | ||
# compiling contract | ||
npx scryptlib your_directory/your_scrypt.scrypt | ||
npx scryptlib compile your_directory/your_scrypt.scrypt | ||
``` | ||
@@ -81,14 +81,14 @@ | ||
| :---------: | :--------: | | ||
| `int` | `new Int(1)` or `number` or `bigint` | | ||
| `bool` | `new Bool(true)` or `boolean` | | ||
| `bytes` | `new Bytes('0001')` or `new String("hello world π")`| | ||
| `PubKey` | `new PubKey('0001')`| | ||
| `PrivKey` | `new PrivKey(1)`| | ||
| `Sig` | `new Sig('0001')`| | ||
| `Ripemd160` | `new Ripemd160('0001')`| | ||
| `Sha1` | `new Sha1('0001')`| | ||
| `Sha256` | `new Sha256('0001')`| | ||
| `SigHashType` | `new SigHashType('01')`| | ||
| `SigHashPreimage` | `new SigHashPreimage('010001')`| | ||
| `OpCodeType` | `new OpCodeType('76')`| | ||
| `int` | `Int(1)` or `number` or `bigint` | | ||
| `bool` | `Bool(true)` or `boolean` | | ||
| `bytes` | `Bytes('0001')` or `stringToBytes("hello world π")`| | ||
| `PubKey` | `PubKey('0001')`| | ||
| `PrivKey` | `PrivKey(1)`| | ||
| `Sig` | `Sig('0001')`| | ||
| `Ripemd160` | `Ripemd160('0001')`| | ||
| `Sha1` | `Sha1('0001')`| | ||
| `Sha256` | `Sha256('0001')`| | ||
| `SigHashType` | `SigHashType('01')`| | ||
| `SigHashPreimage` | `SigHashPreimage('010001')`| | ||
| `OpCodeType` | `OpCodeType('76')`| | ||
@@ -103,3 +103,3 @@ ### 2. Array Types | ||
[new Bytes("00"), new Bytes("00"), new Bytes("00")] // represent `bytes[3]` in **sCrypt** language | ||
[Bytes("00"), Bytes("00"), Bytes("00")] // represent `bytes[3]` in **sCrypt** language | ||
@@ -112,7 +112,10 @@ ``` | ||
Composite types, including structs and type aliases, are dynamically generated by `buildTypeClasses`. When creating a structure, all members must specify values. Use dot to access structure members. | ||
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: | ||
```javascript | ||
```ts | ||
/*Person is structure and Male, Female are type aliases */ | ||
struct Person { | ||
@@ -124,19 +127,11 @@ bytes addr; | ||
struct Block { | ||
bytes hash; | ||
bytes header; | ||
int time; | ||
} | ||
type Male = Person; | ||
type Female = Person; | ||
contract Main { | ||
Person person; | ||
int x; | ||
contract PersonContract { | ||
Male man; | ||
Female woman; | ||
... | ||
} | ||
``` | ||
@@ -146,3 +141,2 @@ | ||
```typescript | ||
@@ -152,27 +146,28 @@ | ||
/*Person is structure and Male, Female are type aliases */ | ||
const { Person, Male, Female } = buildTypeClasses(PersonContract); | ||
let man = new Person({ | ||
let man = { | ||
isMale: true, | ||
age: 14, | ||
addr: new Bytes("68656c6c6f20776f726c6421") | ||
}); | ||
age: 14n, | ||
addr: Bytes("68656c6c6f20776f726c6421") | ||
}; | ||
man.age = 20; | ||
man.age = 20n; | ||
let woman = new Female({ | ||
let woman = { | ||
isMale: false, | ||
age: 18, | ||
addr: new Bytes("68656c6c6f20776f726c6421") | ||
}); | ||
age: 18n, | ||
addr: Bytes("68656c6c6f20776f726c6421") | ||
}; | ||
woman.addr = new Bytes("") | ||
woman.addr = Bytes("") | ||
const instance = new PersonContract(man, woman); | ||
``` | ||
### 4. HashedMap | ||
[HashedMap](./docs/hashedmap_en.md) is a hashtable-like data structure. | ||
### 4. Library | ||
### 5. Library | ||
Library is another composite types. When the constructor parameter of the contract contains library, we need to create library through sdk. | ||
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. | ||
@@ -209,9 +204,8 @@ Library defined in sCrypt: | ||
const { L } = buildTypeClasses(Test); | ||
let l = [1n, 2n]; | ||
let test = new Test(1, new L(1, 2)); | ||
let test = new Test(1n, l); | ||
``` | ||
As you can see, creating a library instance is similar to creating a contract instance. 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. | ||
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. | ||
@@ -233,3 +227,3 @@ ## Deploy a Contract and Call Its Function | ||
```typescript | ||
const instance = new MyContract(1234, true, ...parameters); | ||
const instance = new MyContract(1234n, true, ...parameters); | ||
``` | ||
@@ -260,5 +254,10 @@ To get the locking script, use: | ||
{ | ||
tx?: any; // current transaction represented in bsv.Transaction object | ||
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 | ||
} | ||
@@ -280,3 +279,3 @@ ``` | ||
// 1) set context per verify() | ||
const funcCall = instance.someFunc(new Sig('0123456'), new Bytes('aa11ff'), ...parameters); | ||
const funcCall = instance.someFunc(Sig('0123456'), Bytes('aa11ff'), ...parameters); | ||
const result = funcCall.verify(context); | ||
@@ -307,3 +306,3 @@ // 2) alternatively, context can be set at instance level and all following verify() will use it | ||
```typescript | ||
const instance = new Counter(0); | ||
const instance = new Counter(0n); | ||
@@ -338,3 +337,3 @@ let state = instance.counter; | ||
instance.counter++; | ||
instance.person.name = new Bytes('0001'); | ||
instance.person.name = Bytes('0001'); | ||
@@ -392,7 +391,7 @@ ``` | ||
let demo = new Demo("11111111111111111111111111111111111", 1); | ||
let demo = new Demo(Int("11111111111111111111111111111111111"), 1n); | ||
let result = demo.add(new Int("11111111111111111111111111111111112")).verify(); | ||
let result = demo.add(Int("11111111111111111111111111111111112")).verify(); | ||
console.assert(result.success, result.error) | ||
``` |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
924221
120
22616
0
384
8