scrypt-ts
Advanced tools
Comparing version 0.1.6-test.10 to 0.1.6-test.11
@@ -82,8 +82,8 @@ "use strict"; | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.signTransaction(tx, options)]; | ||
case 0: return [4 /*yield*/, tx.sealAsync()]; | ||
case 1: | ||
_a.sent(); | ||
return [4 /*yield*/, this.signTransaction(tx, options)]; | ||
case 2: | ||
signedTx = _a.sent(); | ||
return [4 /*yield*/, signedTx.sealAsync()]; | ||
case 2: | ||
_a.sent(); | ||
return [4 /*yield*/, this.connectedProvider.sendTransaction(signedTx)]; | ||
@@ -90,0 +90,0 @@ case 3: |
import { Networks, Address } from "bsv"; | ||
import { bsv } from "scryptlib/dist"; | ||
import { bsv } from "scryptlib"; | ||
import { Provider, TransactionResponse, TxHash, UtxoQueryOptions } from "../abstract-provider"; | ||
@@ -4,0 +4,0 @@ import { AddressOption, UTXO } from "../types"; |
@@ -53,10 +53,7 @@ "use strict"; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.WhatsonchainProvider = void 0; | ||
var dist_1 = require("scryptlib/dist"); | ||
var scryptlib_1 = require("scryptlib"); | ||
var abstract_provider_1 = require("../abstract-provider"); | ||
var axios_1 = __importDefault(require("axios")); | ||
var superagent = require('superagent'); | ||
var WhatsonchainProvider = /** @class */ (function (_super) { | ||
@@ -72,3 +69,3 @@ __extends(WhatsonchainProvider, _super); | ||
// TODO: check all avaiable networks | ||
var networkStr = this._network.name === dist_1.bsv.Networks.mainnet.name ? 'main' : 'test'; | ||
var networkStr = this._network.name === scryptlib_1.bsv.Networks.mainnet.name ? 'main' : 'test'; | ||
return "https://api.whatsonchain.com/v1/bsv/".concat(networkStr); | ||
@@ -105,3 +102,9 @@ }, | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.post("".concat(this.apiPrefix, "/tx/raw"), { txhex: rawTxHex }, { timeout: timeout })]; | ||
return [4 /*yield*/, superagent.post("".concat(this.apiPrefix, "/tx/raw")) | ||
.timeout({ | ||
response: timeout, | ||
deadline: 60000, // but allow 1 minute for the file to finish loading. | ||
}) | ||
.set('Content-Type', 'application/json') | ||
.send({ txhex: rawTxHex })]; | ||
case 2: | ||
@@ -126,13 +129,13 @@ res = _a.sent(); | ||
return __awaiter(this, void 0, void 0, function () { | ||
var data, utxos; | ||
var res, utxos; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, axios_1.default.get("".concat(this.apiPrefix, "/address/").concat(address, "/unspent"))]; | ||
case 0: return [4 /*yield*/, superagent.get("".concat(this.apiPrefix, "/address/").concat(address, "/unspent"))]; | ||
case 1: | ||
data = (_a.sent()).data; | ||
utxos = data.map(function (item) { return ({ | ||
res = _a.sent(); | ||
utxos = res.body.map(function (item) { return ({ | ||
txId: item.tx_hash, | ||
outputIndex: item.tx_pos, | ||
satoshis: item.value, | ||
script: dist_1.bsv.Script.buildPublicKeyHashOut(address).toHex(), | ||
script: scryptlib_1.bsv.Script.buildPublicKeyHashOut(address).toHex(), | ||
}); }); | ||
@@ -139,0 +142,0 @@ if ((options === null || options === void 0 ? void 0 : options.minSatoshis) && utxos.reduce(function (s, u) { return s + u.satoshis; }, 0) < options.minSatoshis) { |
import { PublicKey, Transaction } from "bsv"; | ||
import { bsv } from "scryptlib/dist"; | ||
import { bsv } from "scryptlib"; | ||
import { Provider } from "../abstract-provider"; | ||
@@ -4,0 +4,0 @@ import { Signer, SignTransactionOptions, SignatureRequest, SignatureResponse } from "../abstract-signer"; |
@@ -55,7 +55,7 @@ "use strict"; | ||
exports.SensiletSigner = void 0; | ||
var dist_1 = require("scryptlib/dist"); | ||
var scryptlib_1 = require("scryptlib"); | ||
var abstract_signer_1 = require("../abstract-signer"); | ||
var utils_1 = require("../utils"); | ||
// TODO: export this default value from scryptlib | ||
var DEFAULT_SIGHASH_TYPE = dist_1.bsv.crypto.Signature.ALL; | ||
var DEFAULT_SIGHASH_TYPE = scryptlib_1.bsv.crypto.Signature.ALL; | ||
var SensiletSigner = /** @class */ (function (_super) { | ||
@@ -160,3 +160,3 @@ __extends(SensiletSigner, _super); | ||
address = _a.sent(); | ||
return [2 /*return*/, dist_1.bsv.Address.fromString(address)]; | ||
return [2 /*return*/, scryptlib_1.bsv.Address.fromString(address)]; | ||
} | ||
@@ -196,3 +196,3 @@ }); | ||
pubKey = _a.sent(); | ||
return [2 /*return*/, Promise.resolve(new dist_1.bsv.PublicKey(pubKey))]; | ||
return [2 /*return*/, Promise.resolve(new scryptlib_1.bsv.PublicKey(pubKey))]; | ||
} | ||
@@ -216,3 +216,3 @@ }); | ||
sigReqsByInputIndex = ((options === null || options === void 0 ? void 0 : options.sigRequests) || []).reduce(function (m, sigReq) { m.set(sigReq.inputIndex, sigReq); return m; }, new Map()); | ||
tx = new dist_1.bsv.Transaction(rawTxHex); | ||
tx = new scryptlib_1.bsv.Transaction(rawTxHex); | ||
tx.inputs.forEach(function (_, inputIndex) { | ||
@@ -223,5 +223,5 @@ var sigReq = sigReqsByInputIndex.get(inputIndex); | ||
} | ||
var script = sigReq.scriptHex ? new dist_1.bsv.Script(sigReq.scriptHex) : dist_1.bsv.Script.buildPublicKeyHashOut(sigReq.address.toString()); | ||
var script = sigReq.scriptHex ? new scryptlib_1.bsv.Script(sigReq.scriptHex) : scryptlib_1.bsv.Script.buildPublicKeyHashOut(sigReq.address.toString()); | ||
// set ref output of the input | ||
tx.inputs[inputIndex].output = new dist_1.bsv.Transaction.Output({ | ||
tx.inputs[inputIndex].output = new scryptlib_1.bsv.Transaction.Output({ | ||
script: script, | ||
@@ -272,3 +272,3 @@ satoshis: sigReq.satoshis | ||
if (sigResp && ((_a = input.output) === null || _a === void 0 ? void 0 : _a.script.isPublicKeyHashOut())) { | ||
input.setScript(dist_1.bsv.Script.buildPublicKeyHashIn(dist_1.bsv.PublicKey.fromString(sigResp.publicKey), dist_1.bsv.crypto.Signature.fromString(sigResp.sig), sigResp.sigHashType)); | ||
input.setScript(scryptlib_1.bsv.Script.buildPublicKeyHashIn(scryptlib_1.bsv.PublicKey.fromString(sigResp.publicKey), scryptlib_1.bsv.crypto.Signature.fromString(sigResp.sig), sigResp.sigHashType)); | ||
} | ||
@@ -309,3 +309,3 @@ }); | ||
inputIndex: sigReq.inputIndex, | ||
scriptHex: sigReq.scriptHex || dist_1.bsv.Script.buildPublicKeyHashOut(address).toHex(), | ||
scriptHex: sigReq.scriptHex || scryptlib_1.bsv.Script.buildPublicKeyHashOut(address).toHex(), | ||
satoshis: sigReq.satoshis, | ||
@@ -312,0 +312,0 @@ sighashType: sigReq.sigHashType || DEFAULT_SIGHASH_TYPE, |
@@ -137,11 +137,5 @@ "use strict"; | ||
var addresses; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
addresses = options === null || options === void 0 ? void 0 : options.address; | ||
this._checkAddressOption(addresses); | ||
tx.outputs.forEach(function (output, outputIndex) { | ||
_this._utxoManagers.forEach(function (mgr) { | ||
mgr.collectUtxoFrom(output, tx.id, outputIndex); | ||
}); | ||
}); | ||
// TODO: take account of SignatureRequests in options. | ||
@@ -148,0 +142,0 @@ return [2 /*return*/, Promise.resolve(tx.sign(this._getPrivateKeys(addresses)))]; |
import { prop, method } from './smart-contract/decorators'; | ||
import { SmartContract, TxOutputRef, TxInputRef } from './smart-contract/contract'; | ||
import { SmartContract, TxOutputRef, TxInputRef, MergedArtifact } from './smart-contract/contract'; | ||
import { SmartContractLib } from './smart-contract/library'; | ||
@@ -8,5 +8,7 @@ export * from './smart-contract/builtins/types'; | ||
export * from './transformation/utils'; | ||
export { prop, method, SmartContract, SmartContractLib, TxOutputRef, TxInputRef }; | ||
export { prop, method, SmartContract, SmartContractLib, TxOutputRef, TxInputRef, MergedArtifact }; | ||
export { bsv, toHex, buildPublicKeyHashScript, buildOpreturnScript, ContractArtifact, TxContext, VerifyResult, FunctionCall } from 'scryptlib'; | ||
export * from './bsv/types'; | ||
export * from './smart-contract/types/index'; | ||
export * from './smart-contract/utils/index'; | ||
export { WhatsonchainProvider } from './bsv/providers/whatsonchain-provider'; | ||
@@ -13,0 +15,0 @@ export { SensiletSigner } from './bsv/signers/sensilet-signer'; |
@@ -36,2 +36,4 @@ "use strict"; | ||
__exportStar(require("./bsv/types"), exports); | ||
__exportStar(require("./smart-contract/types/index"), exports); | ||
__exportStar(require("./smart-contract/utils/index"), exports); | ||
/* export Providers */ | ||
@@ -38,0 +40,0 @@ var whatsonchain_provider_1 = require("./bsv/providers/whatsonchain-provider"); |
import { SigHashType, Ripemd160, Sha256, Sha1 } from "scryptlib"; | ||
import { PubKey, Sig, PubKeyHash, OpCodeType, SigHashPreimage, PrivKey, ByteString } from "./types"; | ||
export { and, xor, or, invert } from "scryptlib/dist/builtins"; | ||
export { getSortedItem } from "scryptlib/dist"; | ||
export { and, xor, or, invert, getSortedItem } from "scryptlib"; | ||
/** | ||
@@ -268,3 +267,3 @@ * bigint can be converted to string with int2ByteString. | ||
static readonly PubKeyHashLen: bigint; | ||
static toLEUnsigned(n: bigint, l: bigint): string; | ||
static toLEUnsigned(n: bigint, l: bigint): ByteString; | ||
static fromLEUnsigned(bytes: ByteString): bigint; | ||
@@ -275,2 +274,9 @@ static readVarint(buf: ByteString): ByteString; | ||
static buildPublicKeyHashScript(pubKeyHash: PubKeyHash): ByteString; | ||
/** | ||
* build P2PKH output from PubKeyHash | ||
* @param pubKeyHash the address to receive change coin | ||
* @param amount satoshi amount | ||
* @returns a P2PKH output | ||
*/ | ||
static buildPublicKeyHashOutput(pubKeyHash: PubKeyHash, amount: bigint): ByteString; | ||
static buildOpreturnScript(data: ByteString): ByteString; | ||
@@ -277,0 +283,0 @@ } |
@@ -7,9 +7,8 @@ "use strict"; | ||
var types_1 = require("./types"); | ||
var builtins_1 = require("scryptlib/dist/builtins"); | ||
Object.defineProperty(exports, "and", { enumerable: true, get: function () { return builtins_1.and; } }); | ||
Object.defineProperty(exports, "xor", { enumerable: true, get: function () { return builtins_1.xor; } }); | ||
Object.defineProperty(exports, "or", { enumerable: true, get: function () { return builtins_1.or; } }); | ||
Object.defineProperty(exports, "invert", { enumerable: true, get: function () { return builtins_1.invert; } }); | ||
var dist_1 = require("scryptlib/dist"); | ||
Object.defineProperty(exports, "getSortedItem", { enumerable: true, get: function () { return dist_1.getSortedItem; } }); | ||
var scryptlib_2 = require("scryptlib"); | ||
Object.defineProperty(exports, "and", { enumerable: true, get: function () { return scryptlib_2.and; } }); | ||
Object.defineProperty(exports, "xor", { enumerable: true, get: function () { return scryptlib_2.xor; } }); | ||
Object.defineProperty(exports, "or", { enumerable: true, get: function () { return scryptlib_2.or; } }); | ||
Object.defineProperty(exports, "invert", { enumerable: true, get: function () { return scryptlib_2.invert; } }); | ||
Object.defineProperty(exports, "getSortedItem", { enumerable: true, get: function () { return scryptlib_2.getSortedItem; } }); | ||
/** | ||
@@ -449,2 +448,11 @@ * bigint can be converted to string with int2ByteString. | ||
}; | ||
/** | ||
* build P2PKH output from PubKeyHash | ||
* @param pubKeyHash the address to receive change coin | ||
* @param amount satoshi amount | ||
* @returns a P2PKH output | ||
*/ | ||
Utils.buildPublicKeyHashOutput = function (pubKeyHash, amount) { | ||
return Utils.buildOutput(Utils.buildPublicKeyHashScript(pubKeyHash), amount); | ||
}; | ||
// build false OP_RETURN script from data payload | ||
@@ -451,0 +459,0 @@ Utils.buildOpreturnScript = function (data) { |
@@ -1,5 +0,4 @@ | ||
import { Bytes, AbstractContract, Int } from "scryptlib"; | ||
import { SupportedParamType } from "scryptlib/dist/scryptTypes"; | ||
import { Flavor, AbstractContract, Int, SupportedParamType } from "scryptlib"; | ||
export { PubKey, Sig, SigHashPreimage, PrivKey, Ripemd160, PubKeyHash, Sha256, Sha1, OpCodeType, SigHashType } from "scryptlib"; | ||
export { SubBytes } from "scryptlib/dist/scryptTypes"; | ||
export { SubBytes } from "scryptlib"; | ||
/** | ||
@@ -13,3 +12,3 @@ * @ignore | ||
declare type HexType<T extends string> = T extends `${infer R1}${infer R2}${infer R3}` ? R1 extends HexChar ? R2 extends HexChar ? `${R1}${R2}${HexType<R3>}` : never : never : T extends `${infer R1}${infer R2}` ? R1 extends `${HexChar}${HexChar}` ? `${R1}${HexType<R2>}` : never : `${T}`; | ||
export declare type ByteString = Bytes; | ||
export declare type ByteString = Flavor<string, 'bytes'>; | ||
/** | ||
@@ -16,0 +15,0 @@ * Converts a literal to ByteString. |
@@ -8,2 +8,3 @@ import "reflect-metadata"; | ||
import { TransformInfo, TranspileError } from "../transformation/transpiler"; | ||
import { MethodCallTxBuilder, MethodCallResult } from "./types/contract-call"; | ||
/** | ||
@@ -73,3 +74,3 @@ * A reference to an input of a transaction | ||
/** | ||
* Compare the difference between the outputs argument and all the outputs of the transaction bound by `this.unlockFrom`, | ||
* Compare the difference between the outputs argument and all the outputs of the transaction bound by `this.to`, | ||
* which are serialized and hashed to produce `this.ctx.hashOutputs`. | ||
@@ -80,2 +81,10 @@ */ | ||
/** | ||
* ContractArtifact is the compiler output results in a JSON. It’s a representation used to build locking and unlocking scripts. | ||
* We call this file a contract artifact file. A merged contract artifact is a contract artifact that incorporates transform information. | ||
* Usually produced by the [scrypt-cli]{@link https://github.com/sCrypt-Inc/scrypt-cli} compile command. | ||
*/ | ||
export declare type MergedArtifact = ContractArtifact & { | ||
transformer: TransformInfo; | ||
}; | ||
/** | ||
* The main contract class. To write a contract, extend this class as such: | ||
@@ -91,4 +100,12 @@ * @example | ||
export declare class SmartContract { | ||
private _lockTo?; | ||
private _unlockFrom?; | ||
/** | ||
* `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. | ||
*/ | ||
from?: TxOutputRef; | ||
/** | ||
* `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. | ||
*/ | ||
to?: TxInputRef; | ||
_ctx?: ScriptContext; | ||
@@ -107,7 +124,6 @@ private static DelegateClazz; | ||
* This function is usually called on the frontend. | ||
* The contract class needs to call this function to initialize before instantiating. | ||
* @param transform a object that contains transform infos | ||
* @param artifact a contract artifact object | ||
* The contract class needs to call this function before instantiating. | ||
* @param artifact a merged contract artifact object | ||
*/ | ||
static init(transform: TransformInfo, artifact: ContractArtifact): void; | ||
static init(artifact: MergedArtifact): void; | ||
private static _getTransform; | ||
@@ -128,6 +144,9 @@ private static _getScryptFile; | ||
get codePart(): string; | ||
clone(): typeof this; | ||
next(): typeof this; | ||
clone(opt?: { | ||
refCloneProps?: string[]; | ||
}): typeof this; | ||
next(opt?: { | ||
refCloneProps?: string[]; | ||
}): typeof this; | ||
markAsGenesis(): typeof this; | ||
updateStateSigHashType(txPreimage: SigHashPreimage, amount: bigint, sigHashType: SigHashType): boolean; | ||
buildStateOutput(amount: bigint): ByteString; | ||
@@ -150,6 +169,12 @@ getStateScript(): ByteString; | ||
checkMultiSig(signatures: Sig[], publickeys: PubKey[]): boolean; | ||
updateState(preimage: SigHashPreimage, amount: bigint): boolean; | ||
/** | ||
* Get the amount of the change output for `to.tx`. | ||
* @returns amount in satoshis | ||
*/ | ||
get changeAmount(): bigint; | ||
private checkPubkeyEncoding; | ||
private checkSignatureEncoding; | ||
private callDelegatedMethod; | ||
private setCtx; | ||
private clearCtx; | ||
private entryMethodCall?; | ||
@@ -161,6 +186,3 @@ setDataPartInASM(dataPart: string): void; | ||
private buildEntryMethodCall; | ||
set unlockFrom(ref: TxInputRef | undefined); | ||
get unlockFrom(): TxInputRef | undefined; | ||
get lockTo(): TxOutputRef | undefined; | ||
set lockTo(ref: TxOutputRef | undefined); | ||
private _assertToExist; | ||
_provider?: Provider; | ||
@@ -176,2 +198,13 @@ _signer?: Signer; | ||
}): Promise<TransactionResponse>; | ||
private _prepareArgsForMethodCall; | ||
private call; | ||
private dummySignCallTx; | ||
methods(): Record<string, (...args: any) => Promise<MethodCallResult<this>>>; | ||
private getTxBuilder; | ||
static bindTxBuilder(methodName: string, txBuilder: MethodCallTxBuilder<SmartContract>): void; | ||
private static _txBuilders; | ||
static defaultCallTxBuilder(sigHashType: SigHashType): MethodCallTxBuilder<SmartContract>; | ||
isStateful(): boolean; | ||
sigTypeOfMethod(methodName: string): number; | ||
private getMethodsMeta; | ||
static findKeyIndex(collection: Map<SupportedParamType, SupportedParamType> | Set<SupportedParamType>, key: SupportedParamType, keyType?: string): bigint; | ||
@@ -178,0 +211,0 @@ private diffOutputs; |
@@ -84,3 +84,2 @@ "use strict"; | ||
var types_1 = require("./builtins/types"); | ||
var typeCheck_1 = require("scryptlib/dist/typeCheck"); | ||
var abstract_provider_1 = require("../bsv/abstract-provider"); | ||
@@ -91,2 +90,4 @@ var abstract_signer_1 = require("../bsv/abstract-signer"); | ||
var diffUtils_1 = require("./utils/diffUtils"); | ||
var decorators_1 = require("./decorators"); | ||
var utils_2 = require("./utils"); | ||
/** | ||
@@ -196,9 +197,13 @@ * The main contract class. To write a contract, extend this class as such: | ||
* This function is usually called on the frontend. | ||
* The contract class needs to call this function to initialize before instantiating. | ||
* @param transform a object that contains transform infos | ||
* @param artifact a contract artifact object | ||
* The contract class needs to call this function before instantiating. | ||
* @param artifact a merged contract artifact object | ||
*/ | ||
SmartContract.init = function (transform, artifact) { | ||
this.transformInfo = transform; | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(artifact); | ||
SmartContract.init = function (artifact) { | ||
if (typeof artifact.transformer === 'object') { | ||
this.transformInfo = artifact.transformer; | ||
this.DelegateClazz = (0, scryptlib_1.buildContractClass)(artifact); | ||
} | ||
else { | ||
throw new Error('incorrect artifact format!'); | ||
} | ||
}; | ||
@@ -280,7 +285,7 @@ SmartContract._getTransform = function () { | ||
var txContext = {}; | ||
if (this.unlockFrom) { | ||
txContext.tx = this.unlockFrom.tx; | ||
var inputIndex = this.unlockFrom.inputIndex; | ||
if (this.to) { | ||
txContext.tx = this.to.tx; | ||
var inputIndex = this.to.inputIndex; | ||
txContext.inputIndex = inputIndex; | ||
txContext.inputSatoshis = this.unlockFrom.tx.inputs[inputIndex].output.satoshis; | ||
txContext.inputSatoshis = this.to.tx.inputs[inputIndex].output.satoshis; | ||
} | ||
@@ -364,20 +369,21 @@ try { | ||
}); | ||
SmartContract.prototype.clone = function () { | ||
SmartContract.prototype.clone = function (opt) { | ||
var _this = this; | ||
this.syncStateProps(); | ||
var lockTo = this.lockTo; | ||
var unlockFrom = this.unlockFrom; | ||
// don't clone transation. | ||
this.lockTo = undefined; | ||
this.unlockFrom = undefined; | ||
// refCloneProps are properties that only references are copied, but not deep clone their values. | ||
var refClonePropNames = ['from', 'to', '_signer', '_provider'].concat((opt === null || opt === void 0 ? void 0 : opt.refCloneProps) || []); | ||
var refClonePropValues = refClonePropNames.map(function (pn) { return _this[pn]; }); | ||
// shadow property references on this before cloning | ||
refClonePropNames.forEach(function (pn) { return _this[pn] = undefined; }); | ||
var obj = (0, clone_1.default)(this); | ||
obj.lockTo = lockTo; | ||
obj.unlockFrom = unlockFrom; | ||
this.lockTo = lockTo; | ||
this.unlockFrom = unlockFrom; | ||
// copy property references to the object | ||
refClonePropNames.forEach(function (pn, idx) { return obj[pn] = refClonePropValues[idx]; }); | ||
// recover property references on this | ||
refClonePropNames.forEach(function (pn, idx) { return _this[pn] = refClonePropValues[idx]; }); | ||
return obj; | ||
}; | ||
SmartContract.prototype.next = function () { | ||
var cloned = this.clone(); | ||
cloned.lockTo = undefined; | ||
cloned.unlockFrom = undefined; | ||
SmartContract.prototype.next = function (opt) { | ||
var cloned = this.clone(opt); | ||
cloned.from = undefined; | ||
cloned.to = undefined; | ||
cloned.delegateInstance.isGenesis = false; | ||
@@ -390,7 +396,2 @@ return cloned; | ||
}; | ||
SmartContract.prototype.updateStateSigHashType = function (txPreimage, amount, sigHashType) { | ||
(0, functions_1.assert)(this.checkPreimageSigHashType(txPreimage, sigHashType)); | ||
var output = this.buildStateOutput(amount); | ||
return (0, functions_1.hash256)(output) == functions_1.SigHash.hashOutputs(txPreimage); | ||
}; | ||
SmartContract.prototype.buildStateOutput = function (amount) { | ||
@@ -411,3 +412,3 @@ var outputScript = this.getStateScript(); | ||
} | ||
(0, typeCheck_1.flatternArg)(Object.assign({}, p, { | ||
(0, scryptlib_1.flatternArg)(Object.assign({}, p, { | ||
value: value | ||
@@ -441,11 +442,9 @@ }), _this.delegateInstance.resolver, { | ||
var fSuccess = false; | ||
if (!this.unlockFrom) { | ||
throw new Error('unlockFrom should be set when checkSig executes'); | ||
} | ||
this._assertToExist(); | ||
try { | ||
var sig = scryptlib_1.bsv.crypto.Signature.fromTxFormat(Buffer.from((0, types_1.toByteString)(signature), 'hex')); | ||
var pubkey = scryptlib_1.bsv.PublicKey.fromBuffer(Buffer.from((0, types_1.toByteString)(publickey), 'hex'), false); | ||
var tx = this.unlockFrom.tx; | ||
var inputIndex = this.unlockFrom.inputIndex || 0; | ||
var inputSatoshis = this.unlockFrom.tx.inputs[inputIndex].output.satoshis; | ||
var tx = this.to.tx; | ||
var inputIndex = this.to.inputIndex || 0; | ||
var inputSatoshis = this.to.tx.inputs[inputIndex].output.satoshis; | ||
fSuccess = tx.verifySignature(sig, pubkey, inputIndex, this.delegateInstance.lockingScript, scryptlib_1.bsv.crypto.BN.fromNumber(inputSatoshis), scryptlib_1.DEFAULT_FLAGS); | ||
@@ -482,5 +481,14 @@ } | ||
}; | ||
SmartContract.prototype.updateState = function (preimage, amount) { | ||
return this.updateStateSigHashType(preimage, amount, functions_1.SigHash.ALL); | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "changeAmount", { | ||
/** | ||
* Get the amount of the change output for `to.tx`. | ||
* @returns amount in satoshis | ||
*/ | ||
get: function () { | ||
this._assertToExist(); | ||
return BigInt(this.to.tx.getChangeAmount()); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
SmartContract.prototype.checkPubkeyEncoding = function (publickey) { | ||
@@ -527,2 +535,3 @@ if ((scryptlib_1.DEFAULT_FLAGS & scryptlib_1.bsv.Script.Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !scryptlib_1.bsv.PublicKey.isValid((0, types_1.toByteString)(publickey))) { | ||
var _a; | ||
var _this = this; | ||
var args = []; | ||
@@ -535,12 +544,31 @@ for (var _i = 1; _i < arguments.length; _i++) { | ||
// only entry (public) method calls will be delegated to the target instance. | ||
// If the actual parameter is missing, but the last parameter type is `SigHashPreimage`, automatically add txPreimage | ||
if (abi.params.length === (args.length + 1) | ||
&& abi.params[abi.params.length - 1].type === "SigHashPreimage") { | ||
if (!this.unlockFrom) { | ||
throw new Error('unlockFrom should be set'); | ||
// find all params that are hidden from ts @method, which should be auto filled with proper values here. | ||
var autoFillParams = abi.params.slice(args.length); | ||
var autoFillArgBindings_1 = new Map(); | ||
var txPreimage_1; | ||
autoFillParams.forEach(function (param) { | ||
// auto fill `__scrypt_ts_txPreimage` | ||
if (param.name === "__scrypt_ts_txPreimage" && param.type === "SigHashPreimage") { | ||
_this._assertToExist(); | ||
var sighash = _this.sigTypeOfMethod(methodName); | ||
// this preiamge maybe a cached preimage | ||
txPreimage_1 = (0, types_1.SigHashPreimage)(_this.to.tx.getPreimage(_this.to.inputIndex, sighash)); | ||
autoFillArgBindings_1.set(param.name, txPreimage_1); | ||
} | ||
var txPreimage = (0, types_1.SigHashPreimage)(this.unlockFrom.tx.getPreimage(this._unlockFrom.inputIndex)); | ||
args.push(txPreimage); | ||
} | ||
return (_a = this.getDelegateClazz().prototype[methodName]).call.apply(_a, __spreadArray([this.delegateInstance], args, false)); | ||
// auto fill `__scrypt_ts_changeAmount` | ||
if (param.name === "__scrypt_ts_changeAmount" && param.type === "int") { | ||
autoFillArgBindings_1.set(param.name, _this.changeAmount); | ||
} | ||
}); | ||
args.push.apply(args, autoFillParams.map(function (p) { | ||
var val = autoFillArgBindings_1.get(p.name); | ||
if (val === undefined) { | ||
throw new Error("missing auto-filled value for argument ".concat(p.name)); | ||
} | ||
return val; | ||
})); | ||
return { | ||
publicMethodCall: (_a = this.getDelegateClazz().prototype[methodName]).call.apply(_a, __spreadArray([this.delegateInstance], args, false)), | ||
txPreimage: txPreimage_1 | ||
}; | ||
} | ||
@@ -551,2 +579,25 @@ else { | ||
}; | ||
SmartContract.prototype.setCtx = function (txPreimage) { | ||
var outpoint = functions_1.SigHash.outpoint(txPreimage); | ||
this._ctx = { | ||
version: functions_1.SigHash.nVersion(txPreimage), | ||
utxo: { | ||
value: functions_1.SigHash.value(txPreimage), | ||
script: functions_1.SigHash.scriptCode(txPreimage), | ||
outpoint: { | ||
txid: outpoint.slice(0, 32 * 2), | ||
outputIndex: functions_1.Utils.fromLEUnsigned(outpoint.slice(32 * 2)) | ||
} | ||
}, | ||
hashPrevouts: functions_1.SigHash.hashPrevouts(txPreimage), | ||
hashSequence: functions_1.SigHash.hashSequence(txPreimage), | ||
sequence: functions_1.SigHash.nSequence(txPreimage), | ||
hashOutputs: functions_1.SigHash.hashOutputs(txPreimage), | ||
locktime: functions_1.SigHash.nLocktime(txPreimage), | ||
sigHashType: functions_1.SigHash.sigHashType(txPreimage), | ||
}; | ||
}; | ||
SmartContract.prototype.clearCtx = function () { | ||
this._ctx = undefined; | ||
}; | ||
SmartContract.prototype.setDataPartInASM = function (dataPart) { | ||
@@ -587,45 +638,7 @@ this.delegateInstance.setDataPartInASM(dataPart); | ||
}; | ||
Object.defineProperty(SmartContract.prototype, "unlockFrom", { | ||
get: function () { | ||
return this._unlockFrom; | ||
}, | ||
set: function (ref) { | ||
if (typeof ref === 'undefined') { | ||
this._unlockFrom = ref; | ||
return; | ||
} | ||
this._unlockFrom = ref; | ||
var txPreimage = (0, types_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
var outpoint = functions_1.SigHash.outpoint(txPreimage); | ||
this._ctx = { | ||
version: functions_1.SigHash.nVersion(txPreimage), | ||
utxo: { | ||
value: functions_1.SigHash.value(txPreimage), | ||
script: functions_1.SigHash.scriptCode(txPreimage), | ||
outpoint: { | ||
txid: outpoint.slice(0, 32 * 2), | ||
outputIndex: functions_1.Utils.fromLEUnsigned(outpoint.slice(32 * 2)) | ||
} | ||
}, | ||
hashPrevouts: functions_1.SigHash.hashPrevouts(txPreimage), | ||
hashSequence: functions_1.SigHash.hashSequence(txPreimage), | ||
sequence: functions_1.SigHash.nSequence(txPreimage), | ||
hashOutputs: functions_1.SigHash.hashOutputs(txPreimage), | ||
locktime: functions_1.SigHash.nLocktime(txPreimage), | ||
sigHashType: functions_1.SigHash.sigHashType(txPreimage), | ||
}; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(SmartContract.prototype, "lockTo", { | ||
get: function () { | ||
return this._lockTo; | ||
}, | ||
set: function (ref) { | ||
this._lockTo = ref; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
SmartContract.prototype._assertToExist = function () { | ||
if (!this.to) { | ||
throw new Error('`this.to` is undefined, it should be set properly before calling the method'); | ||
} | ||
}; | ||
SmartContract.prototype.connect = function (providerOrSigner) { | ||
@@ -739,2 +752,3 @@ return __awaiter(this, void 0, void 0, function () { | ||
deployTx = _c.sent(); | ||
this.from = { tx: deployTx, outputIndex: 0 }; | ||
return [2 /*return*/, this.signer.signAndsendTransaction(deployTx, { address: address })]; | ||
@@ -745,2 +759,319 @@ } | ||
}; | ||
SmartContract.prototype._prepareArgsForMethodCall = function (methodName) { | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
var scryptMethod = this.getDelegateClazz().abi.find(function (func) { return func.name === methodName; }); | ||
if (!scryptMethod) { | ||
throw new Error("`".concat(this.constructor.name, ".").concat(methodName, "` no exists!")); | ||
} | ||
var methodParamLength = this.getMethodsMeta(methodName).argLength; | ||
if (methodParamLength > args.length) { | ||
throw new Error("missing arguments for calling `this.methods.".concat(methodName, "`, expected at least ").concat(methodParamLength, " but got ").concat(args.length)); | ||
} | ||
var methodArgs = args.slice(0, methodParamLength); | ||
var maybeOptArg = args[methodParamLength]; | ||
var methodCallOptions = {}; | ||
if (maybeOptArg) { | ||
// check options argument | ||
if (typeof maybeOptArg !== 'object') { | ||
throw new Error("the option should be a `MethodCallOptions` type object"); | ||
} | ||
methodCallOptions = maybeOptArg; | ||
} | ||
var sigArgs = methodArgs.reduce(function (sigsMap, arg, argIdx) { | ||
var scrParam = scryptMethod.params[argIdx]; | ||
var match = scrParam.type.match(/^Sig(\[(\d+)\])?$/); | ||
var argType = typeof arg; | ||
if (match) { | ||
var sigLen = match[2] || '1'; | ||
if (argType !== 'function') { | ||
throw new Error("a callback function of type `(sigResponses: SignatureResponse[]) => Sig | Sig[] ` should be given for the Sig type argument"); | ||
} | ||
sigsMap.set(argIdx, { callback: arg, length: parseInt(sigLen) }); | ||
} | ||
else { | ||
if (argType === 'function') { | ||
throw new Error("a callback function given for the non-Sig type argument is not allowed"); | ||
} | ||
} | ||
return sigsMap; | ||
}, new Map()); | ||
return { | ||
methodArgs: methodArgs, | ||
methodCallOptions: methodCallOptions, | ||
sigArgs: sigArgs | ||
}; | ||
}; | ||
SmartContract.prototype.call = function (methodName) { | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a, methodArgs, methodCallOptions, sigArgs, address, feePerKb, txBuilder, methodArgsWithDummySig, _b, dummyTx, atInputIndex, fee, outputValues, minSatoshis, utxos, _c, _d, tx, inputIndex, sigRequiredAddress, nexts, sigRequests, sigResponses; | ||
var _this = this; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
_a = this._prepareArgsForMethodCall.apply(this, __spreadArray([methodName], args, false)), methodArgs = _a.methodArgs, methodCallOptions = _a.methodCallOptions, sigArgs = _a.sigArgs; | ||
return [4 /*yield*/, this.signer.getDefaultAddress()]; | ||
case 1: | ||
address = _e.sent(); | ||
return [4 /*yield*/, this.provider.getFeePerKb()]; | ||
case 2: | ||
feePerKb = _e.sent(); | ||
txBuilder = this.getTxBuilder(methodName); | ||
if (!txBuilder) { | ||
throw new Error("missing bound `txBuilder` for calling `".concat(methodName, "`")); | ||
} | ||
methodArgsWithDummySig = methodArgs.map(function (arg, argIdx) { | ||
var sigArg = sigArgs.get(argIdx); | ||
if (sigArg) { | ||
// replace sig-related args with dummy values | ||
return sigArg.length > 1 ? new Array(sigArg.length).fill((0, utils_2.getDummySig)()) : (0, utils_2.getDummySig)(); | ||
} | ||
else { | ||
return arg; | ||
} | ||
}); | ||
return [4 /*yield*/, txBuilder.call.apply(txBuilder, __spreadArray([this, | ||
{ | ||
current: this, | ||
utxos: (0, utils_1.getDummyP2pkhUTXOs)(2), | ||
nexts: Array.from([methodCallOptions.next || []]).flat(), | ||
changeAddress: methodCallOptions.changeAddress | ||
}], methodArgsWithDummySig, false))]; | ||
case 3: | ||
_b = _e.sent(), dummyTx = _b.unsignedTx, atInputIndex = _b.atInputIndex; | ||
this.to = { tx: dummyTx, inputIndex: atInputIndex }; | ||
this.dummySignCallTx.apply(this, __spreadArray([dummyTx, atInputIndex, methodName], methodArgsWithDummySig, false)); | ||
if (dummyTx.getChangeOutput()) { | ||
// re-calculate change output amount bcoz the previous value was calculated without sigs. | ||
dummyTx.feePerKb(feePerKb); | ||
} | ||
return [4 /*yield*/, this.provider.getEstimateFee(dummyTx)]; | ||
case 4: | ||
fee = _e.sent(); | ||
outputValues = dummyTx.outputs.reduce(function (r, o) { return r + o.satoshis; }, 0); | ||
minSatoshis = outputValues + fee - dummyTx.inputs[atInputIndex].output.satoshis; | ||
if (!(minSatoshis < 1)) return [3 /*break*/, 5]; | ||
_c = []; | ||
return [3 /*break*/, 7]; | ||
case 5: return [4 /*yield*/, this.signer.listUnspent(address, { minSatoshis: minSatoshis })]; | ||
case 6: | ||
_c = _e.sent(); | ||
_e.label = 7; | ||
case 7: | ||
utxos = _c; | ||
return [4 /*yield*/, txBuilder.call.apply(txBuilder, __spreadArray([this, | ||
{ | ||
current: this, | ||
utxos: utxos, | ||
nexts: Array.from([methodCallOptions.next || []]).flat(), | ||
changeAddress: methodCallOptions.changeAddress | ||
}], methodArgsWithDummySig, false))]; | ||
case 8: | ||
_d = _e.sent(), tx = _d.unsignedTx, inputIndex = _d.atInputIndex, sigRequiredAddress = _d.sigRequiredAddress, nexts = _d.nexts; | ||
if (tx.getChangeOutput()) { | ||
// make a dummy sign before calling `tx.feePerKb`, which will modify the change output. | ||
this.dummySignCallTx.apply(this, __spreadArray([tx, inputIndex, methodName], methodArgsWithDummySig, false)); | ||
tx.feePerKb(feePerKb); | ||
} | ||
if (methodCallOptions.lockTime) { | ||
tx.setLockTime(methodCallOptions.lockTime); | ||
} | ||
// console.log('dummy', tx.verifyInputScript(0)) | ||
// bind relations | ||
this.to = { tx: tx, inputIndex: inputIndex }; | ||
if (nexts) { | ||
nexts.forEach(function (n) { | ||
n.instance.from = { tx: tx, outputIndex: n.atOutputIndex }; | ||
}); | ||
} | ||
sigRequests = tx.inputs.flatMap(function (input, idx) { | ||
var addresses = [address.toString()]; | ||
if (idx === inputIndex) { | ||
addresses = (0, utils_1.addressesToList)(sigRequiredAddress || []) | ||
.concat((0, utils_1.addressesToList)(methodCallOptions.sigRequiredAddress || [])); | ||
addresses = addresses.length > 0 ? addresses : [address.toString()]; | ||
} | ||
return addresses | ||
.map(function (addr) { | ||
return { | ||
inputIndex: idx, | ||
satoshis: input.output.satoshis, | ||
scriptHex: input.output.script.toHex(), | ||
address: addr | ||
}; | ||
}); | ||
}); | ||
return [4 /*yield*/, this.signer.getSignatures(tx.toString(), sigRequests)]; | ||
case 9: | ||
sigResponses = _e.sent(); | ||
sigResponses | ||
// group by inputIndex | ||
.reduce(function (group, sigResp) { | ||
var inputIdx = sigResp.inputIndex; | ||
var sigs = group.get(inputIdx) || []; | ||
sigs.push(sigResp); | ||
group.set(inputIdx, sigs); | ||
return group; | ||
}, new Map()) | ||
// apply signatures | ||
.forEach(function (sigResponses, idx) { | ||
if (idx === inputIndex) { | ||
var methodArgs_1 = methodArgs.map(function (arg, argIdx) { | ||
var sigArg = sigArgs.get(argIdx); | ||
if (!sigArg) { | ||
return arg; | ||
} | ||
var validateSig = function (sig) { | ||
if (typeof sig !== 'string') { | ||
throw new Error("the ".concat(argIdx + 1, "th argument calback function should returns a valid `Sig`")); | ||
} | ||
}; | ||
var sigs = sigArg.callback.call(_this, sigResponses) || ''; | ||
if (sigs instanceof Array) { | ||
if (sigs.length !== sigArg.length) { | ||
throw new Error("the ".concat(argIdx + 1, "th argument calback function should returns a valid `Sig` array whose length is expected to be ").concat(sigArg.length, ", but got ").concat(sigs.length)); | ||
} | ||
sigs.forEach(function (sig) { return validateSig(sig); }); | ||
} | ||
else { | ||
validateSig(sigs); | ||
} | ||
return sigs; | ||
}); | ||
var script = _this.getUnlockingScript(function (self) { | ||
self[methodName].apply(self, methodArgs_1); | ||
}); | ||
tx.inputs[inputIndex].setScript(script); | ||
// console.log(`verify tx.input[${inputIndex}] result`, tx.verifyInputScript(inputIndex)); | ||
} | ||
else { | ||
sigResponses.forEach(function (sigResp) { | ||
tx.applySignature({ | ||
inputIndex: sigResp.inputIndex, | ||
sigtype: sigResp.sigHashType || scryptlib_1.DEFAULT_SIGHASH_TYPE, | ||
publicKey: scryptlib_1.bsv.PublicKey.fromString(sigResp.publicKey), | ||
signature: scryptlib_1.bsv.crypto.Signature.fromTxFormat(Buffer.from(sigResp.sig, 'hex')) | ||
}); | ||
}); | ||
} | ||
}); | ||
return [4 /*yield*/, this.provider.sendTransaction(tx)]; | ||
case 10: | ||
_e.sent(); | ||
return [2 /*return*/, { | ||
tx: tx, | ||
nexts: nexts, | ||
next: (nexts === null || nexts === void 0 ? void 0 : nexts.length) === 1 ? nexts[0] : undefined, | ||
}]; | ||
} | ||
}); | ||
}); | ||
}; | ||
SmartContract.prototype.dummySignCallTx = function (tx, inputIndex, methodName) { | ||
var _this = this; | ||
var args = []; | ||
for (var _i = 3; _i < arguments.length; _i++) { | ||
args[_i - 3] = arguments[_i]; | ||
} | ||
tx.inputs.forEach(function (input, idx) { | ||
if (idx === inputIndex) { | ||
var publicMethodCall = _this.callDelegatedMethod.apply(_this, __spreadArray([methodName], args, false)).publicMethodCall; | ||
input.setScript(publicMethodCall.toScript()); | ||
} | ||
else { | ||
input.setScript(scryptlib_1.bsv.Script.buildPublicKeyHashIn(scryptlib_1.bsv.Transaction.DUMMY_PRIVATEKEY.publicKey, Buffer.from((0, utils_2.getDummySig)(), 'hex'), scryptlib_1.DEFAULT_SIGHASH_TYPE)); | ||
} | ||
}); | ||
}; | ||
SmartContract.prototype.methods = function () { | ||
var self = this; | ||
var scryptMethods = this.getDelegateClazz().abi.filter(function (func) { return func.type === 'function'; }).map(function (func) { return func.name; }); | ||
return scryptMethods.reduce(function (ms, m) { | ||
ms[m] = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
return self.call.apply(self, __spreadArray([m], args, false)); | ||
}; | ||
return ms; | ||
}, {}); | ||
}; | ||
SmartContract.prototype.getTxBuilder = function (methodName) { | ||
var scryptMethods = this.getDelegateClazz().abi.filter(function (func) { return func.type === 'function'; }).map(function (func) { return func.name; }); | ||
if (!scryptMethods.includes(methodName)) { | ||
throw new Error("`".concat(methodName, "` is not a @method and do not have any bounded `txBuilder`")); | ||
} | ||
var txBuilders = Object.getPrototypeOf(this).constructor._txBuilders; | ||
return txBuilders.get(methodName) || SmartContract.defaultCallTxBuilder(this.getMethodsMeta(methodName).sigHashType); | ||
}; | ||
SmartContract.bindTxBuilder = function (methodName, txBuilder) { | ||
if (!this.DelegateClazz) { | ||
throw new Error("'".concat(this.name, ".compile' or '").concat(this.name, ".loadArtifact' should be called before calling `bindTxBuilder`!")); | ||
} | ||
var scryptMethods = this.DelegateClazz.abi.filter(function (func) { return func.type === 'function'; }).map(function (func) { return func.name; }); | ||
if (!scryptMethods.includes(methodName)) { | ||
throw new Error("`".concat(methodName, "` is not a @method and cat not set bounded `txBuilder`")); | ||
} | ||
this._txBuilders.set(methodName, txBuilder); | ||
}; | ||
SmartContract.defaultCallTxBuilder = function (sigHashType) { | ||
return function (options) { | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
return __awaiter(this, void 0, void 0, function () { | ||
var stateful, defaultChangeAddr, tx, nexts, nextOpts; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
stateful = this.isStateful(); | ||
return [4 /*yield*/, this.signer.getDefaultAddress()]; | ||
case 1: | ||
defaultChangeAddr = _a.sent(); | ||
tx = new scryptlib_1.bsv.Transaction() | ||
.addInputFromPrevTx(this.from.tx, this.from.outputIndex) | ||
.from(options.utxos); | ||
nexts = undefined; | ||
if (stateful) { | ||
nextOpts = Array.from([options.nexts || []]).flat(); | ||
nexts = nextOpts.map(function (n, idx) { | ||
tx.addOutput(new scryptlib_1.bsv.Transaction.Output({ | ||
script: n.instance.lockingScript, | ||
satoshis: n.balance | ||
})); | ||
return Object.assign({}, n, { atOutputIndex: idx }); | ||
}); | ||
} | ||
tx.change(options.changeAddress || defaultChangeAddr); | ||
return [2 /*return*/, Promise.resolve({ | ||
unsignedTx: tx, | ||
atInputIndex: 0, | ||
nexts: nexts | ||
})]; | ||
} | ||
}); | ||
}); | ||
}; | ||
}; | ||
SmartContract.prototype.isStateful = function () { | ||
return Reflect.getOwnMetadata(decorators_1.StatePropsMetaKey, this.constructor.prototype) !== undefined; | ||
}; | ||
SmartContract.prototype.sigTypeOfMethod = function (methodName) { | ||
var methodMeta = this.getMethodsMeta(methodName); | ||
if (!methodMeta) { | ||
throw new Error("".concat(methodName, " is not a public @method of ").concat(this.constructor.name)); | ||
} | ||
return (0, utils_2.toNumber)(methodMeta.sigHashType); | ||
}; | ||
SmartContract.prototype.getMethodsMeta = function (methodName) { | ||
return Reflect.getOwnMetadata(decorators_1.MethodsMetaKey, this.constructor.prototype).get(methodName); | ||
}; | ||
SmartContract.findKeyIndex = function (collection, key, keyType) { | ||
@@ -765,7 +1096,5 @@ if (!keyType) { | ||
SmartContract.prototype.diffOutputs = function (outputs) { | ||
if (!this.unlockFrom) { | ||
throw new Error('unlockFrom should be set'); | ||
} | ||
this._assertToExist(); | ||
try { | ||
var info = (0, diffUtils_1.diffOutputs)(this.delegateInstance, outputs, this.unlockFrom.tx); | ||
var info = (0, diffUtils_1.diffOutputs)(this.delegateInstance, outputs, this.to.tx); | ||
console.info(info); | ||
@@ -793,3 +1122,3 @@ } | ||
if (!this._ctx) { | ||
throw new Error('`this.ctx` is undefined, `unlockFrom` should be called before to access its value!'); | ||
throw new Error('`this.ctx` is undefined, `to` should be called before to access its value!'); | ||
} | ||
@@ -810,2 +1139,3 @@ return this._ctx; | ||
}; | ||
SmartContract._txBuilders = new Map(); | ||
return SmartContract; | ||
@@ -812,0 +1142,0 @@ }()); |
@@ -0,1 +1,7 @@ | ||
import { SigHashType } from "scryptlib"; | ||
export declare const MethodsMetaKey = "scrypt:methods"; | ||
export interface MethodsMetaValue { | ||
argLength: number; | ||
sigHashType: SigHashType; | ||
} | ||
/** | ||
@@ -5,3 +11,4 @@ * Indicates whether the method is a contract method, and ordinary methods do not affect the execution of the contract | ||
*/ | ||
export declare function method(sigHashType?: import("scryptlib/dist").SigHashType): (target: any, methodName: string, descriptor: PropertyDescriptor) => PropertyDescriptor; | ||
export declare function method(sigHashType?: SigHashType): (target: any, methodName: string, descriptor: PropertyDescriptor) => PropertyDescriptor; | ||
export declare const StatePropsMetaKey = "scrypt:stateProps"; | ||
/** | ||
@@ -8,0 +15,0 @@ * Indicates whether the property is an property of a contract, and ordinary class properties cannot be accessed in contract methods |
@@ -12,5 +12,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.prop = exports.method = void 0; | ||
var dist_1 = require("scryptlib/dist"); | ||
exports.prop = exports.StatePropsMetaKey = exports.method = exports.MethodsMetaKey = void 0; | ||
var functions_1 = require("./builtins/functions"); | ||
exports.MethodsMetaKey = "scrypt:methods"; | ||
/** | ||
@@ -24,2 +24,5 @@ * Indicates whether the method is a contract method, and ordinary methods do not affect the execution of the contract | ||
var originalMethod = descriptor.value; | ||
var methods = Reflect.getOwnMetadata(exports.MethodsMetaKey, target) || new Map(); | ||
methods.set(methodName, { argLength: originalMethod.length, sigHashType: sigHashType }); | ||
Reflect.defineMetadata(exports.MethodsMetaKey, methods, target); | ||
var newDescriptor = { | ||
@@ -51,18 +54,26 @@ configurable: true, | ||
if (isSmartContractStatic || isSmartContractMethod) { | ||
// update `this.entryMethodCall` iff the update flag is true & its value is undefined. | ||
if (_this.enableUpdateEMC && !_this.entryMethodCall) { | ||
_this.entryMethodCall = _this.callDelegatedMethod.apply(_this, __spreadArray([methodName], args, false)); | ||
var pubCallRet = _this.callDelegatedMethod.apply(_this, __spreadArray([methodName], args, false)); | ||
// if public @method is called | ||
if (pubCallRet) { | ||
var publicMethodCall = pubCallRet.publicMethodCall, txPreimage = pubCallRet.txPreimage; | ||
if (txPreimage) { | ||
_this.setCtx(txPreimage); | ||
} | ||
var ctxMethods = _this.getCtxMethods(); | ||
// check preimage before run the method | ||
if (ctxMethods.includes(methodName)) { | ||
if (!_this.unlockFrom) { | ||
throw new Error('unlockFrom should be set'); | ||
} | ||
var ref = _this.unlockFrom; | ||
var txPreimage = (0, dist_1.SigHashPreimage)(ref.tx.getPreimage(ref.inputIndex)); | ||
(0, functions_1.assert)(_this.checkPreimageSigHashType(txPreimage, sigHashType)); | ||
(0, functions_1.assert)(_this.checkPreimageSigHashType(txPreimage, sigHashType), "checkPreimage failed!"); | ||
} | ||
if (_this.entryMethodCall) { | ||
args = _this.entryMethodCall.args.map(function (a) { return a.value; }); | ||
args = publicMethodCall.args.map(function (a) { return a.value; }); | ||
// apply js method | ||
var ret = originalMethod.apply(_this, args); | ||
// clear this.ctx after the public @method call | ||
if (txPreimage) { | ||
_this.clearCtx(); | ||
} | ||
// update `this.entryMethodCall` iff the update flag is true & its value is undefined. | ||
if (_this.enableUpdateEMC && !_this.entryMethodCall) { | ||
_this.entryMethodCall = publicMethodCall; | ||
} | ||
return ret; | ||
} | ||
@@ -80,2 +91,3 @@ return originalMethod.apply(_this, args); | ||
exports.method = method; | ||
exports.StatePropsMetaKey = "scrypt:stateProps"; | ||
/** | ||
@@ -90,5 +102,4 @@ * Indicates whether the property is an property of a contract, and ordinary class properties cannot be accessed in contract methods | ||
if (state) { | ||
var statePropsMetaKey = "scrypt:stateProps"; | ||
var stateProps = (Reflect.getMetadata(statePropsMetaKey, target) || []).concat(propertyName); | ||
Reflect.defineMetadata(statePropsMetaKey, stateProps, target); | ||
var stateProps = (Reflect.getMetadata(exports.StatePropsMetaKey, target) || []).concat(propertyName); | ||
Reflect.defineMetadata(exports.StatePropsMetaKey, stateProps, target); | ||
} | ||
@@ -95,0 +106,0 @@ }; |
@@ -29,3 +29,3 @@ "use strict"; | ||
var transpiler_1 = require("./transpiler"); | ||
var dist_1 = require("scryptlib/dist"); | ||
var scryptlib_1 = require("scryptlib"); | ||
/*** | ||
@@ -104,3 +104,3 @@ * @ignore | ||
var newFile = tsInstance.createSourceFile(fileName, updatedText, languageVersion, true); | ||
newFile.version = (0, dist_1.md5)(updatedText); // patch for making `tsc --watch` work | ||
newFile.version = (0, scryptlib_1.md5)(updatedText); // patch for making `tsc --watch` work | ||
return newFile; | ||
@@ -107,0 +107,0 @@ } |
@@ -37,2 +37,4 @@ import * as ts from 'typescript'; | ||
}; | ||
export declare const InjectedParamTxPreimage = "__scrypt_ts_txPreimage"; | ||
export declare const InjectedParamChangeAmountVar = "__scrypt_ts_changeAmount"; | ||
export declare class Transpiler { | ||
@@ -80,4 +82,7 @@ scComponents: ts.ClassDeclaration[]; | ||
private verifyLastAssertStatement; | ||
private hasPropertyAccessExpression; | ||
private hasAccessCtx; | ||
private hasAccessStateProperty; | ||
private hasAccessChangeAmt; | ||
private shouldAutoAppendChangeAmount; | ||
private shouldAutoAppendSighashPreimage; | ||
@@ -84,0 +89,0 @@ private transformParameter; |
{ | ||
"name": "scrypt-ts", | ||
"version": "0.1.6-test.10", | ||
"version": "0.1.6-test.11", | ||
"description": "A toolset for building sCrypt smart contract applications on Bitcoin SV network written in typescript.", | ||
@@ -14,4 +14,4 @@ "main": "dist/index.js", | ||
"test": "cd test && mocha 'out/test/local/**/*.test.js' --timeout 1200000", | ||
"pretestnet": "cross-env TS_NODE_PROJECT=test/tsconfig.json tsc test/testnet/hashpuzzle.ts", | ||
"testnet": "cd test && node out/test/testnet/hashpuzzle.js", | ||
"pretestnet": "cross-env TS_NODE_PROJECT=test/tsconfig.json tsc test/testnet/counter.ts", | ||
"testnet": "cd test && node out/test/testnet/counter.js", | ||
"publish:beta": "npm run build && npm publish --tag beta", | ||
@@ -39,4 +39,4 @@ "publish:test": "npm run build && npm publish --tag test", | ||
"chai": "^4.3.6", | ||
"chai-as-promised": "^7.1.1", | ||
"chai-exclude": "^2.1.0", | ||
"chai-as-promised": "^7.1.1", | ||
"cross-env": "^7.0.3", | ||
@@ -49,3 +49,2 @@ "dotenv": "^16.0.3", | ||
"ts-node": "^10.9.1", | ||
"tsconfig-paths": "^4.1.0", | ||
"typedoc": "^0.23.21", | ||
@@ -56,8 +55,8 @@ "typedoc-plugin-markdown": "^3.13.6" | ||
"@phenomnomnominal/tsquery": "^5.0.0", | ||
"clone": "^2.1.2", | ||
"fast-diff": "^1.2.0", | ||
"clone": "^2.1.2", | ||
"axios": "=1.1.3", | ||
"reflect-metadata": "^0.1.13", | ||
"scryptlib": "=2.1.1", | ||
"scryptlib": "^2.1.5", | ||
"sourcemap-codec": "^1.4.8", | ||
"superagent": "^8.0.9", | ||
"ts-patch": "^2.0.2", | ||
@@ -64,0 +63,0 @@ "typescript": "=4.8.4" |
Sorry, the diff of this file is too big to display
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
379478
19
47
7729
+ Addedsuperagent@^8.0.9
+ Added@discoveryjs/json-ext@0.5.7(transitive)
+ Added@jridgewell/sourcemap-codec@1.5.0(transitive)
+ Added@scrypt-inc/bsv@1.0.4(transitive)
+ Addedaes-js@3.1.2(transitive)
+ Addedagent-base@7.1.1(transitive)
+ Addedansi-styles@3.2.1(transitive)
+ Addedasap@2.0.6(transitive)
+ Addedassert@2.1.0(transitive)
+ Addedasynckit@0.4.0(transitive)
+ Addedavailable-typed-arrays@1.0.7(transitive)
+ Addedbase64-js@1.5.1(transitive)
+ Addedbignumber.js@9.1.2(transitive)
+ Addedbraces@3.0.3(transitive)
+ Addedbrorand@1.1.0(transitive)
+ Addedbuffer@6.0.3(transitive)
+ Addedcall-bind@1.0.7(transitive)
+ Addedchalk@2.4.2(transitive)
+ Addedcliui@8.0.1(transitive)
+ Addedclone-deep@4.0.1(transitive)
+ Addedcolor-convert@1.9.3(transitive)
+ Addedcolor-name@1.1.3(transitive)
+ Addedcombined-stream@1.0.8(transitive)
+ Addedcomponent-emitter@1.3.1(transitive)
+ Addedconfig-chain@1.1.13(transitive)
+ Addedcookiejar@2.1.4(transitive)
+ Addeddata-uri-to-buffer@4.0.1(transitive)
+ Addeddebug@4.3.7(transitive)
+ Addeddefine-data-property@1.1.4(transitive)
+ Addeddefine-properties@1.2.1(transitive)
+ Addeddelayed-stream@1.0.0(transitive)
+ Addeddetect-file@1.0.0(transitive)
+ Addeddezalgo@1.0.4(transitive)
+ Addedelliptic@6.5.4(transitive)
+ Addedemoji-regex@8.0.0(transitive)
+ Addedes-define-property@1.0.0(transitive)
+ Addedes-errors@1.3.0(transitive)
+ Addedescalade@3.2.0(transitive)
+ Addedescape-string-regexp@1.0.5(transitive)
+ Addedexpand-tilde@2.0.2(transitive)
+ Addedfast-safe-stringify@2.1.1(transitive)
+ Addedfetch-blob@3.2.0(transitive)
+ Addedfill-range@7.1.1(transitive)
+ Addedfind-node-modules@2.1.3(transitive)
+ Addedfindup-sync@4.0.0(transitive)
+ Addedfor-each@0.3.3(transitive)
+ Addedform-data@4.0.1(transitive)
+ Addedformdata-polyfill@4.0.10(transitive)
+ Addedformidable@2.1.2(transitive)
+ Addedget-caller-file@2.0.5(transitive)
+ Addedget-intrinsic@1.2.4(transitive)
+ Addedget-proxy-settings@0.1.13(transitive)
+ Addedglobal-modules@1.0.0(transitive)
+ Addedglobal-prefix@1.0.2(transitive)
+ Addedgopd@1.1.0(transitive)
+ Addedhas-flag@3.0.0(transitive)
+ Addedhas-property-descriptors@1.0.2(transitive)
+ Addedhas-proto@1.1.0(transitive)
+ Addedhas-symbols@1.1.0(transitive)
+ Addedhas-tostringtag@1.0.2(transitive)
+ Addedhash.js@1.1.7(transitive)
+ Addedhexoid@1.0.0(transitive)
+ Addedhmac-drbg@1.0.1(transitive)
+ Addedhomedir-polyfill@1.0.3(transitive)
+ Addedhttps-proxy-agent@7.0.5(transitive)
+ Addedieee754@1.2.1(transitive)
+ Addedinherits@2.0.3(transitive)
+ Addedis-arguments@1.1.1(transitive)
+ Addedis-callable@1.2.7(transitive)
+ Addedis-extglob@2.1.1(transitive)
+ Addedis-fullwidth-code-point@3.0.0(transitive)
+ Addedis-generator-function@1.0.10(transitive)
+ Addedis-glob@4.0.3(transitive)
+ Addedis-nan@1.3.2(transitive)
+ Addedis-number@7.0.0(transitive)
+ Addedis-plain-object@2.0.4(transitive)
+ Addedis-typed-array@1.1.13(transitive)
+ Addedis-windows@1.0.2(transitive)
+ Addedisobject@3.0.1(transitive)
+ Addedjson-bigint@1.0.0(transitive)
+ Addedmerge@2.1.1(transitive)
+ Addedmethods@1.1.2(transitive)
+ Addedmicromatch@4.0.8(transitive)
+ Addedmime@2.6.0(transitive)
+ Addedmime-db@1.52.0(transitive)
+ Addedmime-types@2.1.35(transitive)
+ Addedminimalistic-assert@1.0.1(transitive)
+ Addedminimalistic-crypto-utils@1.0.1(transitive)
+ Addedms@2.1.3(transitive)
+ Addednode-domexception@1.0.0(transitive)
+ Addednode-fetch@3.3.2(transitive)
+ Addednpm-conf@1.1.3(transitive)
+ Addedobject-inspect@1.13.3(transitive)
+ Addedobject-is@1.1.6(transitive)
+ Addedobject-keys@1.1.1(transitive)
+ Addedobject.assign@4.1.5(transitive)
+ Addedparse-passwd@1.0.0(transitive)
+ Addedpicomatch@2.3.1(transitive)
+ Addedpify@3.0.0(transitive)
+ Addedpossible-typed-array-names@1.0.0(transitive)
+ Addedproto-list@1.2.4(transitive)
+ Addedqs@6.13.1(transitive)
+ Addedrequire-directory@2.1.1(transitive)
+ Addedresolve-dir@1.0.1(transitive)
+ Addedrimraf@3.0.2(transitive)
+ Addedscryptlib@2.2.4(transitive)
+ Addedsemver@7.6.3(transitive)
+ Addedset-function-length@1.2.2(transitive)
+ Addedshallow-clone@3.0.1(transitive)
+ Addedside-channel@1.0.6(transitive)
+ Addedstring-width@4.2.3(transitive)
+ Addedsuperagent@8.1.2(transitive)
+ Addedsupports-color@5.5.0(transitive)
+ Addedto-regex-range@5.0.1(transitive)
+ Addedunorm@1.4.1(transitive)
+ Addedutil@0.12.5(transitive)
+ Addedweb-streams-polyfill@3.3.3(transitive)
+ Addedwhich-typed-array@1.1.16(transitive)
+ Addedwrap-ansi@7.0.0(transitive)
+ Addedy18n@5.0.8(transitive)
+ Addedyargs@17.7.2(transitive)
+ Addedyargs-parser@21.1.1(transitive)
- Removedaxios@=1.1.3
Updatedscryptlib@^2.1.5