UNPKG

@roochnetwork/sdk

Version:
1,665 lines (1,636 loc) 60.8 kB
var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // src/constants/address.ts var ROOCH_ADDRESS_LENGTH = 64; // src/constants/gas.ts var DEFAULT_MAX_GAS_AMOUNT = 1e6; // src/constants/chain.ts var LocalNetworkURL = "http://127.0.0.1:50051"; var DevNetworkURL = "https://dev-seed.rooch.network"; var TestNetworkURL = "https://test-seed.rooch.network"; var LOCAL_CHAIN_ID = 20230104; var DEV_CHAIN_ID = 20230103; var TEST_CHAIN_ID = 20230102; var Chain = class { constructor(id, name, options) { this.id = id; this.name = name; this.options = options; } get url() { return this.options.url; } get websocket() { return this.options.websocket || this.options.url; } get info() { return { chainId: `0x${this.id.toString(16)}`, chainName: this.name, iconUrls: [ "https://github.com/rooch-network/rooch/blob/main/docs/website/public/logo/rooch_black_text.png" ], nativeCurrency: { name: "ROH", symbol: "ROH", decimals: 18 }, rpcUrls: [this.options.url] }; } }; var LocalChain = new Chain(LOCAL_CHAIN_ID, "local", { url: LocalNetworkURL }); var DevChain = new Chain(DEV_CHAIN_ID, "dev", { url: DevNetworkURL }); var TestChain = new Chain(TEST_CHAIN_ID, "test", { url: TestNetworkURL }); var AllChain = [LocalChain, DevChain, TestChain]; // src/types/hex.ts import { bytesToHex, hexToBytes } from "@noble/hashes/utils"; var HexString = class { /** * Creates new hex string from Buffer * @param buffer A buffer to convert * @returns New HexString */ static fromBuffer(buffer) { return HexString.fromUint8Array(buffer); } /** * Creates new hex string from Uint8Array * @param arr Uint8Array to convert * @returns New HexString */ static fromUint8Array(arr) { return new HexString(bytesToHex(arr)); } /** * Ensures `hexString` is instance of `HexString` class * @param hexString String to check * @returns New HexString if `hexString` is regular string or `hexString` if it is HexString instance * @example * ``` * const regularString = "string"; * const hexString = new HexString("string"); // "0xstring" * HexString.ensure(regularString); // "0xstring" * HexString.ensure(hexString); // "0xstring" * ``` */ static ensure(hexString) { if (typeof hexString === "string") { return new HexString(hexString); } return hexString; } /** * Creates new HexString instance from regular string. If specified string already starts with "0x" prefix, * it will not add another one * @param hexString String to convert * @example * ``` * const string = "string"; * new HexString(string); // "0xstring" * ``` */ constructor(hexString) { if (hexString.startsWith("0x")) { this.hexString = hexString; } else { this.hexString = `0x${hexString}`; } } /** * Getter for inner hexString * @returns Inner hex string */ hex() { return this.hexString; } /** * Getter for inner hexString without prefix * @returns Inner hex string without prefix * @example * ``` * const hexString = new HexString("string"); // "0xstring" * hexString.noPrefix(); // "string" * ``` */ noPrefix() { return this.hexString.slice(2); } /** * Overrides default `toString` method * @returns Inner hex string */ toString() { return this.hex(); } /** * Trimmes extra zeroes in the begining of a string * @returns Inner hexString without leading zeroes * @example * ``` * new HexString("0x000000string").toShortString(); // result = "0xstring" * ``` */ toShortString() { const trimmed = this.hexString.replace(/^0x0*/, ""); return `0x${trimmed}`; } /** * Converts hex string to a Uint8Array * @returns Uint8Array from inner hexString without prefix */ toUint8Array() { return Uint8Array.from(hexToBytes(this.noPrefix())); } }; // src/types/bcs/index.ts var bcs_exports = {}; __export(bcs_exports, { AccountAddress: () => AccountAddress, Authenticator: () => Authenticator, BcsDeserializer: () => BcsDeserializer, BcsSerializer: () => BcsSerializer, BinaryDeserializer: () => BinaryDeserializer, BinarySerializer: () => BinarySerializer, FunctionCall: () => FunctionCall, FunctionId: () => FunctionId, Helpers: () => Helpers, Identifier: () => Identifier, ModuleId: () => ModuleId, MoveAction: () => MoveAction, MoveActionVariantFunction: () => MoveActionVariantFunction, MoveActionVariantModuleBundle: () => MoveActionVariantModuleBundle, MoveActionVariantScript: () => MoveActionVariantScript, MoveAsciiString: () => MoveAsciiString, MoveString: () => MoveString, RoochTransaction: () => RoochTransaction, RoochTransactionData: () => RoochTransactionData, ScriptCall: () => ScriptCall, StructTag: () => StructTag, TypeTag: () => TypeTag, TypeTagVariantaddress: () => TypeTagVariantaddress, TypeTagVariantbool: () => TypeTagVariantbool, TypeTagVariantsigner: () => TypeTagVariantsigner, TypeTagVariantstruct: () => TypeTagVariantstruct, TypeTagVariantu128: () => TypeTagVariantu128, TypeTagVariantu16: () => TypeTagVariantu16, TypeTagVariantu256: () => TypeTagVariantu256, TypeTagVariantu32: () => TypeTagVariantu32, TypeTagVariantu64: () => TypeTagVariantu64, TypeTagVariantu8: () => TypeTagVariantu8, TypeTagVariantvector: () => TypeTagVariantvector, fromB64: () => fromB64, serializeU256: () => serializeU256, toB64: () => toB64 }); // src/utils/b64.ts function b64ToUint6(nChr) { return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0; } function fromB64(sBase64, nBlocksSize) { var sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { nMod4 = nInIdx & 3; nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 6 * (3 - nMod4); if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; } nUint24 = 0; } } return taBytes; } function uint6ToB64(nUint6) { return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65; } function toB64(aBytes) { var nMod3 = 2, sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { sB64Enc += String.fromCodePoint( uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63) ); nUint24 = 0; } } return sB64Enc.slice(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "=="); } // src/generated/runtime/serde/binarySerializer.ts import * as util from "@kayahr/text-encoding"; var _BinarySerializer = class { constructor() { this.buffer = new ArrayBuffer(64); this.offset = 0; } ensureBufferWillHandleSize(bytes) { while (this.buffer.byteLength < this.offset + bytes) { const newBuffer = new ArrayBuffer(this.buffer.byteLength * 2); new Uint8Array(newBuffer).set(new Uint8Array(this.buffer)); this.buffer = newBuffer; } } serialize(values) { this.ensureBufferWillHandleSize(values.length); new Uint8Array(this.buffer, this.offset).set(values); this.offset += values.length; } serializeStr(value) { this.serializeBytes(_BinarySerializer.textEncoder.encode(value)); } serializeBytes(value) { this.serializeLen(value.length); this.serialize(value); } serializeBool(value) { const byteValue = value ? 1 : 0; this.serialize(new Uint8Array([byteValue])); } // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/explicit-module-boundary-types serializeUnit(_value) { return; } serializeWithFunction(fn, bytesLength, value) { this.ensureBufferWillHandleSize(bytesLength); const dv = new DataView(this.buffer, this.offset); fn.apply(dv, [0, value, true]); this.offset += bytesLength; } serializeU8(value) { this.serialize(new Uint8Array([value])); } serializeU16(value) { this.serializeWithFunction(DataView.prototype.setUint16, 2, value); } serializeU32(value) { this.serializeWithFunction(DataView.prototype.setUint32, 4, value); } serializeU64(value) { const low = BigInt(value.toString()) & _BinarySerializer.BIG_32Fs; const high = BigInt(value.toString()) >> _BinarySerializer.BIG_32; this.serializeU32(Number(low)); this.serializeU32(Number(high)); } serializeU128(value) { const low = BigInt(value.toString()) & _BinarySerializer.BIG_64Fs; const high = BigInt(value.toString()) >> _BinarySerializer.BIG_64; this.serializeU64(low); this.serializeU64(high); } serializeI8(value) { const bytes = 1; this.ensureBufferWillHandleSize(bytes); new DataView(this.buffer, this.offset).setInt8(0, value); this.offset += bytes; } serializeI16(value) { const bytes = 2; this.ensureBufferWillHandleSize(bytes); new DataView(this.buffer, this.offset).setInt16(0, value, true); this.offset += bytes; } serializeI32(value) { const bytes = 4; this.ensureBufferWillHandleSize(bytes); new DataView(this.buffer, this.offset).setInt32(0, value, true); this.offset += bytes; } serializeI64(value) { const low = BigInt(value) & _BinarySerializer.BIG_32Fs; const high = BigInt(value) >> _BinarySerializer.BIG_32; this.serializeI32(Number(low)); this.serializeI32(Number(high)); } serializeI128(value) { const low = BigInt(value) & _BinarySerializer.BIG_64Fs; const high = BigInt(value) >> _BinarySerializer.BIG_64; this.serializeI64(low); this.serializeI64(high); } serializeOptionTag(value) { this.serializeBool(value); } getBufferOffset() { return this.offset; } getBytes() { return new Uint8Array(this.buffer).slice(0, this.offset); } serializeChar(_value) { throw new Error("Method serializeChar not implemented."); } serializeF32(value) { const bytes = 4; this.ensureBufferWillHandleSize(bytes); new DataView(this.buffer, this.offset).setFloat32(0, value, true); this.offset += bytes; } serializeF64(value) { const bytes = 8; this.ensureBufferWillHandleSize(bytes); new DataView(this.buffer, this.offset).setFloat64(0, value, true); this.offset += bytes; } }; var BinarySerializer = _BinarySerializer; BinarySerializer.BIG_32 = BigInt(32); BinarySerializer.BIG_64 = BigInt(64); BinarySerializer.BIG_32Fs = BigInt("4294967295"); BinarySerializer.BIG_64Fs = BigInt("18446744073709551615"); BinarySerializer.textEncoder = typeof window === "undefined" ? new util.TextEncoder() : new TextEncoder(); // src/generated/runtime/bcs/bcsSerializer.ts var BcsSerializer = class extends BinarySerializer { serializeU32AsUleb128(value) { const valueArray = []; while (value >>> 7 != 0) { valueArray.push(value & 127 | 128); value = value >>> 7; } valueArray.push(value); this.serialize(new Uint8Array(valueArray)); } serializeLen(value) { this.serializeU32AsUleb128(value); } serializeVariantIndex(value) { this.serializeU32AsUleb128(value); } sortMapEntries(_offsets) { } }; // src/generated/runtime/serde/binaryDeserializer.ts import * as util2 from "@kayahr/text-encoding"; var _BinaryDeserializer = class { constructor(data) { this.buffer = new ArrayBuffer(data.length); new Uint8Array(this.buffer).set(data, 0); this.offset = 0; } read(length) { const bytes = this.buffer.slice(this.offset, this.offset + length); this.offset += length; return bytes; } deserializeStr() { const value = this.deserializeBytes(); return _BinaryDeserializer.textDecoder.decode(value); } deserializeBytes() { const len = this.deserializeLen(); if (len < 0) { throw new Error("Length of a bytes array can't be negative"); } return new Uint8Array(this.read(len)); } deserializeBool() { const bool = new Uint8Array(this.read(1))[0]; return bool == 1; } deserializeUnit() { return null; } deserializeU8() { return new DataView(this.read(1)).getUint8(0); } deserializeU16() { return new DataView(this.read(2)).getUint16(0, true); } deserializeU32() { return new DataView(this.read(4)).getUint32(0, true); } deserializeU64() { const low = this.deserializeU32(); const high = this.deserializeU32(); return BigInt( BigInt(high.toString()) << _BinaryDeserializer.BIG_32 | BigInt(low.toString()) ); } deserializeU128() { const low = this.deserializeU64(); const high = this.deserializeU64(); return BigInt( BigInt(high.toString()) << _BinaryDeserializer.BIG_64 | BigInt(low.toString()) ); } deserializeI8() { return new DataView(this.read(1)).getInt8(0); } deserializeI16() { return new DataView(this.read(2)).getInt16(0, true); } deserializeI32() { return new DataView(this.read(4)).getInt32(0, true); } deserializeI64() { const low = this.deserializeI32(); const high = this.deserializeI32(); return BigInt(high.toString()) << _BinaryDeserializer.BIG_32 | BigInt(low.toString()); } deserializeI128() { const low = this.deserializeI64(); const high = this.deserializeI64(); return BigInt(high.toString()) << _BinaryDeserializer.BIG_64 | BigInt(low.toString()); } deserializeOptionTag() { return this.deserializeBool(); } getBufferOffset() { return this.offset; } deserializeChar() { throw new Error("Method deserializeChar not implemented."); } deserializeF32() { return new DataView(this.read(4)).getFloat32(0, true); } deserializeF64() { return new DataView(this.read(8)).getFloat64(0, true); } }; var BinaryDeserializer = _BinaryDeserializer; BinaryDeserializer.BIG_32 = BigInt(32); BinaryDeserializer.BIG_64 = BigInt(64); BinaryDeserializer.textDecoder = typeof window === "undefined" ? new util2.TextDecoder() : new TextDecoder(); // src/generated/runtime/bcs/bcsDeserializer.ts var _BcsDeserializer = class extends BinaryDeserializer { deserializeUleb128AsU32() { let value = 0; for (let shift = 0; shift < 32; shift += 7) { const x = this.deserializeU8(); const digit = x & 127; value = value | digit << shift; if (value < 0 || value > _BcsDeserializer.MAX_UINT_32) { throw new Error("Overflow while parsing uleb128-encoded uint32 value"); } if (digit == x) { if (shift > 0 && digit == 0) { throw new Error("Invalid uleb128 number (unexpected zero digit)"); } return value; } } throw new Error("Overflow while parsing uleb128-encoded uint32 value"); } deserializeLen() { return this.deserializeUleb128AsU32(); } deserializeVariantIndex() { return this.deserializeUleb128AsU32(); } checkThatKeySlicesAreIncreasing(_key1, _key2) { return; } }; var BcsDeserializer = _BcsDeserializer; BcsDeserializer.MAX_UINT_32 = 2 ** 32 - 1; // src/generated/runtime/rooch_types/mod.ts var AccountAddress = class { constructor(value) { this.value = value; } serialize(serializer) { Helpers.serializeArray32U8Array(this.value, serializer); } static deserialize(deserializer) { const value = Helpers.deserializeArray32U8Array(deserializer); return new AccountAddress(value); } }; var Authenticator = class { constructor(auth_validator_id, payload) { this.auth_validator_id = auth_validator_id; this.payload = payload; } serialize(serializer) { serializer.serializeU64(this.auth_validator_id); Helpers.serializeVectorU8(this.payload, serializer); } static deserialize(deserializer) { const auth_validator_id = deserializer.deserializeU64(); const payload = Helpers.deserializeVectorU8(deserializer); return new Authenticator(auth_validator_id, payload); } }; var FunctionCall = class { constructor(function_id, ty_args, args) { this.function_id = function_id; this.ty_args = ty_args; this.args = args; } serialize(serializer) { this.function_id.serialize(serializer); Helpers.serializeVectorTypeTag(this.ty_args, serializer); Helpers.serializeVectorVectorU8(this.args, serializer); } static deserialize(deserializer) { const function_id = FunctionId.deserialize(deserializer); const ty_args = Helpers.deserializeVectorTypeTag(deserializer); const args = Helpers.deserializeVectorVectorU8(deserializer); return new FunctionCall(function_id, ty_args, args); } }; var FunctionId = class { constructor(module_id, function_name) { this.module_id = module_id; this.function_name = function_name; } serialize(serializer) { this.module_id.serialize(serializer); this.function_name.serialize(serializer); } static deserialize(deserializer) { const module_id = ModuleId.deserialize(deserializer); const function_name = Identifier.deserialize(deserializer); return new FunctionId(module_id, function_name); } }; var Identifier = class { constructor(value) { this.value = value; } serialize(serializer) { serializer.serializeStr(this.value); } static deserialize(deserializer) { const value = deserializer.deserializeStr(); return new Identifier(value); } }; var ModuleId = class { constructor(address, name) { this.address = address; this.name = name; } serialize(serializer) { this.address.serialize(serializer); this.name.serialize(serializer); } static deserialize(deserializer) { const address = AccountAddress.deserialize(deserializer); const name = Identifier.deserialize(deserializer); return new ModuleId(address, name); } }; var MoveAction = class { static deserialize(deserializer) { const index = deserializer.deserializeVariantIndex(); switch (index) { case 0: return MoveActionVariantScript.load(deserializer); case 1: return MoveActionVariantFunction.load(deserializer); case 2: return MoveActionVariantModuleBundle.load(deserializer); default: throw new Error("Unknown variant index for MoveAction: " + index); } } }; var MoveActionVariantScript = class extends MoveAction { constructor(value) { super(); this.value = value; } serialize(serializer) { serializer.serializeVariantIndex(0); this.value.serialize(serializer); } static load(deserializer) { const value = ScriptCall.deserialize(deserializer); return new MoveActionVariantScript(value); } }; var MoveActionVariantFunction = class extends MoveAction { constructor(value) { super(); this.value = value; } serialize(serializer) { serializer.serializeVariantIndex(1); this.value.serialize(serializer); } static load(deserializer) { const value = FunctionCall.deserialize(deserializer); return new MoveActionVariantFunction(value); } }; var MoveActionVariantModuleBundle = class extends MoveAction { constructor(value) { super(); this.value = value; } serialize(serializer) { serializer.serializeVariantIndex(2); Helpers.serializeVectorVectorU8(this.value, serializer); } static load(deserializer) { const value = Helpers.deserializeVectorVectorU8(deserializer); return new MoveActionVariantModuleBundle(value); } }; var RoochTransaction = class { constructor(data, authenticator) { this.data = data; this.authenticator = authenticator; } serialize(serializer) { this.data.serialize(serializer); this.authenticator.serialize(serializer); } static deserialize(deserializer) { const data = RoochTransactionData.deserialize(deserializer); const authenticator = Authenticator.deserialize(deserializer); return new RoochTransaction(data, authenticator); } }; var RoochTransactionData = class { constructor(sender, sequence_number, chain_id, max_gas_amount, action) { this.sender = sender; this.sequence_number = sequence_number; this.chain_id = chain_id; this.max_gas_amount = max_gas_amount; this.action = action; } serialize(serializer) { this.sender.serialize(serializer); serializer.serializeU64(this.sequence_number); serializer.serializeU64(this.chain_id); serializer.serializeU64(this.max_gas_amount); this.action.serialize(serializer); } static deserialize(deserializer) { const sender = AccountAddress.deserialize(deserializer); const sequence_number = deserializer.deserializeU64(); const chain_id = deserializer.deserializeU64(); const max_gas_amount = deserializer.deserializeU64(); const action = MoveAction.deserialize(deserializer); return new RoochTransactionData(sender, sequence_number, chain_id, max_gas_amount, action); } }; var ScriptCall = class { constructor(code, ty_args, args) { this.code = code; this.ty_args = ty_args; this.args = args; } serialize(serializer) { serializer.serializeBytes(this.code); Helpers.serializeVectorTypeTag(this.ty_args, serializer); Helpers.serializeVectorVectorU8(this.args, serializer); } static deserialize(deserializer) { const code = deserializer.deserializeBytes(); const ty_args = Helpers.deserializeVectorTypeTag(deserializer); const args = Helpers.deserializeVectorVectorU8(deserializer); return new ScriptCall(code, ty_args, args); } }; var StructTag = class { constructor(address, module, name, type_args) { this.address = address; this.module = module; this.name = name; this.type_args = type_args; } serialize(serializer) { this.address.serialize(serializer); this.module.serialize(serializer); this.name.serialize(serializer); Helpers.serializeVectorTypeTag(this.type_args, serializer); } static deserialize(deserializer) { const address = AccountAddress.deserialize(deserializer); const module = Identifier.deserialize(deserializer); const name = Identifier.deserialize(deserializer); const type_args = Helpers.deserializeVectorTypeTag(deserializer); return new StructTag(address, module, name, type_args); } }; var TypeTag = class { static deserialize(deserializer) { const index = deserializer.deserializeVariantIndex(); switch (index) { case 0: return TypeTagVariantbool.load(deserializer); case 1: return TypeTagVariantu8.load(deserializer); case 2: return TypeTagVariantu64.load(deserializer); case 3: return TypeTagVariantu128.load(deserializer); case 4: return TypeTagVariantaddress.load(deserializer); case 5: return TypeTagVariantsigner.load(deserializer); case 6: return TypeTagVariantvector.load(deserializer); case 7: return TypeTagVariantstruct.load(deserializer); case 8: return TypeTagVariantu16.load(deserializer); case 9: return TypeTagVariantu32.load(deserializer); case 10: return TypeTagVariantu256.load(deserializer); default: throw new Error("Unknown variant index for TypeTag: " + index); } } }; var TypeTagVariantbool = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(0); } static load(deserializer) { return new TypeTagVariantbool(); } }; var TypeTagVariantu8 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(1); } static load(deserializer) { return new TypeTagVariantu8(); } }; var TypeTagVariantu64 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(2); } static load(deserializer) { return new TypeTagVariantu64(); } }; var TypeTagVariantu128 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(3); } static load(deserializer) { return new TypeTagVariantu128(); } }; var TypeTagVariantaddress = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(4); } static load(deserializer) { return new TypeTagVariantaddress(); } }; var TypeTagVariantsigner = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(5); } static load(deserializer) { return new TypeTagVariantsigner(); } }; var TypeTagVariantvector = class extends TypeTag { constructor(value) { super(); this.value = value; } serialize(serializer) { serializer.serializeVariantIndex(6); this.value.serialize(serializer); } static load(deserializer) { const value = TypeTag.deserialize(deserializer); return new TypeTagVariantvector(value); } }; var TypeTagVariantstruct = class extends TypeTag { constructor(value) { super(); this.value = value; } serialize(serializer) { serializer.serializeVariantIndex(7); this.value.serialize(serializer); } static load(deserializer) { const value = StructTag.deserialize(deserializer); return new TypeTagVariantstruct(value); } }; var TypeTagVariantu16 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(8); } static load(deserializer) { return new TypeTagVariantu16(); } }; var TypeTagVariantu32 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(9); } static load(deserializer) { return new TypeTagVariantu32(); } }; var TypeTagVariantu256 = class extends TypeTag { constructor() { super(); } serialize(serializer) { serializer.serializeVariantIndex(10); } static load(deserializer) { return new TypeTagVariantu256(); } }; var Helpers = class { static serializeArray32U8Array(value, serializer) { value.forEach((item) => { serializer.serializeU8(item[0]); }); } static deserializeArray32U8Array(deserializer) { const list = []; for (let i = 0; i < 32; i++) { list.push([deserializer.deserializeU8()]); } return list; } static serializeVectorTypeTag(value, serializer) { serializer.serializeLen(value.length); value.forEach((item) => { item.serialize(serializer); }); } static deserializeVectorTypeTag(deserializer) { const length = deserializer.deserializeLen(); const list = []; for (let i = 0; i < length; i++) { list.push(TypeTag.deserialize(deserializer)); } return list; } static serializeVectorU8(value, serializer) { serializer.serializeLen(value.length); value.forEach((item) => { serializer.serializeU8(item); }); } static deserializeVectorU8(deserializer) { const length = deserializer.deserializeLen(); const list = []; for (let i = 0; i < length; i++) { list.push(deserializer.deserializeU8()); } return list; } static serializeVectorVectorU8(value, serializer) { serializer.serializeLen(value.length); value.forEach((item) => { Helpers.serializeVectorU8(item, serializer); }); } static deserializeVectorVectorU8(deserializer) { const length = deserializer.deserializeLen(); const list = []; for (let i = 0; i < length; i++) { list.push(Helpers.deserializeVectorU8(deserializer)); } return list; } }; // src/types/bcs/move_string.ts var MoveString = class { constructor(bytes) { this.bytes = bytes; } serialize(serializer) { Helpers.serializeVectorU8(this.bytes, serializer); } static deserialize(deserializer) { const bytes = Helpers.deserializeVectorU8(deserializer); return new MoveString(bytes); } }; // src/types/bcs/move_ascii_string.ts var MoveAsciiString = class { constructor(bytes) { this.bytes = bytes; } serialize(serializer) { Helpers.serializeVectorU8(this.bytes, serializer); } static deserialize(deserializer) { const bytes = Helpers.deserializeVectorU8(deserializer); return new MoveAsciiString(bytes); } }; // src/types/bcs/u256.ts var BIG_128Fs = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); var BIG_128 = BigInt(128); function serializeU256(se, value) { const low = BigInt(value.toString()) & BIG_128Fs; const high = BigInt(value.toString()) >> BIG_128; se.serializeU128(low); se.serializeU128(high); } // src/utils/mixin.ts function applyMixin(targetClass, baseClass, baseClassProp) { Object.getOwnPropertyNames(baseClass.prototype).forEach((propertyName) => { const propertyDescriptor = Object.getOwnPropertyDescriptor(baseClass.prototype, propertyName); if (!propertyDescriptor) return; propertyDescriptor.value = function(...args) { return this[baseClassProp][propertyName](...args); }; Object.defineProperty(targetClass.prototype, propertyName, propertyDescriptor); }); Object.getOwnPropertyNames(baseClass).forEach((propertyName) => { const propertyDescriptor = Object.getOwnPropertyDescriptor(baseClass, propertyName); if (!propertyDescriptor) return; propertyDescriptor.value = function(...args) { return this[baseClassProp][propertyName](...args); }; if (targetClass.hasOwnProperty.call(targetClass, propertyName)) { return; } Object.defineProperty(targetClass, propertyName, propertyDescriptor); }); } // src/utils/hex.ts import { Buffer as Buffer2 } from "buffer"; function toHexString(byteArray) { return `0x${Buffer2.from(new Uint8Array(byteArray)).toString("hex")}`; } function fromHexString(hex, padding) { let hexWithoutPrefix = hex.startsWith("0x") ? hex.substring(2) : hex; if (padding && hexWithoutPrefix.length < padding) { hexWithoutPrefix = padLeft(hexWithoutPrefix, padding); } else if (!padding && hexWithoutPrefix.length % 2 !== 0) { hexWithoutPrefix = `0${hexWithoutPrefix}`; } const buf = Buffer2.from(hexWithoutPrefix, "hex"); return new Uint8Array(buf); } function padLeft(str, chars, sign = "0") { return new Array(chars - str.length + 1).join(sign) + str; } function padRight(str, chars, sign = "0") { return str + new Array(chars - str.length + 1).join(sign); } // src/utils/encode.ts function functionIdToStirng(functionId) { if (typeof functionId !== "string") { if (functionId instanceof Object) { return `${functionId.address}::${functionId.module}::${functionId.functionName}`; } } return functionId; } function parseFunctionId(functionId) { if (typeof functionId !== "string") { return functionId; } const parts = functionId.split("::", 3); if (parts.length !== 3) { throw new Error(`cannot parse ${functionId} into FunctionId`); } return { address: normalizeRoochAddress(parts[0]), module: parts[1], functionName: parts[2] }; } function normalizeRoochAddress(value, forceAdd0x = false) { let address = value.toLowerCase(); if (!forceAdd0x && address.startsWith("0x")) { address = address.slice(2); } return `0x${address.padStart(ROOCH_ADDRESS_LENGTH, "0")}`; } function typeTagToString(type_tag) { if (typeof type_tag === "string") { return type_tag; } if ("Vector" in type_tag) { return `Vector<${typeTagToString(type_tag.Vector)}>`; } if ("Struct" in type_tag) { const struct = type_tag.Struct; let result = `${struct.address}::${struct.module}::${struct.name}`; if (struct.type_params) { const params = struct.type_params.map(typeTagToString).join(", "); result += `<${params}>`; } return result; } throw new Error(`Unknown type tag: ${JSON.stringify(type_tag)}`); } // src/utils/tx.ts function encodeFunctionCall(functionId, tyArgs, args) { const funcId = parseFunctionId(functionId); const functionCall = new FunctionCall( new FunctionId( new ModuleId( addressToSCS(funcId.address), new Identifier(funcId.module) ), new Identifier(funcId.functionName) ), tyArgs.map((t) => typeTagToSCS(t)), bytesArrayToSeqSeq(args) ); return new MoveActionVariantFunction(functionCall); } function typeTagToSCS(ty) { if (ty === "Bool") { return new TypeTagVariantbool(); } if (ty === "U8") { return new TypeTagVariantu8(); } if (ty === "U16") { return new TypeTagVariantu16(); } if (ty === "U32") { return new TypeTagVariantu32(); } if (ty === "U64") { return new TypeTagVariantu64(); } if (ty === "U128") { return new TypeTagVariantu128(); } if (ty === "U256") { return new TypeTagVariantu256(); } if (ty === "Address") { return new TypeTagVariantaddress(); } if (ty === "Signer") { return new TypeTagVariantsigner(); } if (ty.Vector) { return new TypeTagVariantvector(typeTagToSCS(ty.Vector)); } if (ty.Struct) { return new TypeTagVariantstruct( structTagToSCS(ty.Struct) ); } throw new Error(`invalid type tag: ${ty}`); } function structTagToSCS(data) { return new StructTag( addressToSCS(data.address), new Identifier(data.module), new Identifier(data.name), data.type_params ? data.type_params.map((t) => typeTagToSCS(t)) : [] ); } function addressToSCS(addr) { const bytes = fromHexString(addr, 16 * 2); const data = []; for (let i = 0; i < bytes.length; i++) { data.push([bytes[i]]); } return new AccountAddress(data); } function encodeStructTypeTags(typeArgsString) { return typeArgsString.map((str) => encodeStructTypeTag(str)); } function encodeStructTypeTag(str) { const arr = str.split("<"); const arr1 = arr[0].split("::"); const address = arr1[0]; const module = arr1[1]; const name = arr1[2]; const params = arr[1] ? arr[1].replace(">", "").split(",") : []; const type_params = []; if (params.length > 0) { params.forEach((param) => { type_params.push(encodeStructTypeTag(param.trim())); }); } const result = { Struct: { address, module, name, type_params } }; return result; } function bytesToSeq(byteArray) { return Array.from(byteArray); } function stringToSeq(str) { const seq = new Array(); for (let i = 0; i < str.length; i++) { seq.push(str.charCodeAt(i)); } return seq; } function bytesArrayToSeqSeq(input) { return input.map((byteArray) => bytesToSeq(byteArray)); } function addressToListTuple(ethAddress) { const cleanedEthAddress = ethAddress.startsWith("0x") ? ethAddress.slice(2) : ethAddress; if (cleanedEthAddress.length !== ROOCH_ADDRESS_LENGTH) { throw new Error("Invalid Rooch address"); } const listTuple = []; for (let i = 0; i < cleanedEthAddress.length; i += 2) { const byte = parseInt(cleanedEthAddress.slice(i, i + 2), 16); listTuple.push([byte]); } return listTuple; } function addressToSeqNumber(ethAddress) { const cleanedEthAddress = ethAddress.startsWith("0x") ? ethAddress.slice(2) : ethAddress; if (cleanedEthAddress.length !== ROOCH_ADDRESS_LENGTH) { throw new Error("Invalid Ethereum address"); } const seqNumber = []; for (let i = 0; i < cleanedEthAddress.length; i += 2) { const byte = parseInt(cleanedEthAddress.slice(i, i + 2), 16); seqNumber.push(byte); } return seqNumber; } function serializeValue(value, type, se) { if (type === "Bool") { se.serializeBool(value); } else if (type === "U8") { se.serializeU8(value); } else if (type === "U16") { se.serializeU16(value); } else if (type === "U32") { se.serializeU32(value); } else if (type === "U64") { se.serializeU64(value); } else if (type === "U128") { se.serializeU128(value); } else if (type === "U256") { serializeU256(se, value); } else if (type === "Address") { const list = addressToListTuple(normalizeRoochAddress(value)); const accountAddress = new AccountAddress(list); accountAddress.serialize(se); } else if (type === "Ascii") { const bytes = stringToSeq(value); const moveAsciiString = new MoveAsciiString(bytes); moveAsciiString.serialize(se); } else if (type === "String") { const bytes = stringToSeq(value); const moveString = new MoveString(bytes); moveString.serialize(se); } else if (type.Vector) { const vectorValues = value; se.serializeLen(vectorValues.length); for (let item of vectorValues) { serializeValue(item, type.Vector, se); } } } function encodeArg(arg) { const se = new BcsSerializer(); serializeValue(arg.value, arg.type, se); return se.getBytes(); } var encodeMoveCallData = (funcId, tyArgs, args) => { const bcsArgs = args?.map((arg) => encodeArg(arg)); const scriptFunction = encodeFunctionCall(funcId, tyArgs, bcsArgs); const payloadInHex = (() => { const se = new BcsSerializer(); scriptFunction.serialize(se); return se.getBytes(); })(); return payloadInHex; }; // src/utils/bytes.ts function uint8Array2SeqNumber(bytes) { return Array.from(bytes, (byte) => byte); } // src/utils/crypto/signature.ts var SIGNATURE_SCHEME_TO_FLAG = { ED25519: 0 }; var SIGNATURE_FLAG_TO_SCHEME = { 0: "ED25519" }; function toSerializedSignature({ signature, signatureScheme, pubKey }) { const pubKeyBytes = pubKey.toBytes(); const serializedSignature = new Uint8Array(1 + signature.length + pubKeyBytes.length); serializedSignature.set([SIGNATURE_SCHEME_TO_FLAG[signatureScheme]]); serializedSignature.set(signature, 1); serializedSignature.set(pubKeyBytes, 1 + signature.length); return serializedSignature; } // src/utils/crypto/mnemonics.ts import { mnemonicToSeedSync as bip39MnemonicToSeedSync } from "@scure/bip39"; function isValidHardenedPath(path) { if (!/^m\/44'\/784'\/[0-9]+'\/[0-9]+'\/[0-9]+'+$/.test(path)) { return false; } return true; } function isValidBIP32Path(path) { if (!/^m\/(54|74)'\/784'\/[0-9]+'\/[0-9]+\/[0-9]+$/.test(path)) { return false; } return true; } function mnemonicToSeed(mnemonics) { return bip39MnemonicToSeedSync(mnemonics, ""); } function mnemonicToSeedHex(mnemonics) { return toHexString(mnemonicToSeed(mnemonics)); } // src/utils/crypto/publickey.ts function bytesEqual(a, b) { if (a === b) return true; if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } var PublicKey = class { /** * Checks if two public keys are equal */ equals(publicKey) { return bytesEqual(this.toBytes(), publicKey.toBytes()); } /** * Return the base-64 representation of the public key */ toBase64() { return toB64(this.toBytes()); } /** * Return the Rooch representation of the public key encoded in * base-64. A Rooch public key is formed by the concatenation * of the scheme flag with the raw bytes of the public key */ toRoochPublicKey() { const bytes = this.toBytes(); const roochPublicKey = new Uint8Array(bytes.length + 1); roochPublicKey.set([this.flag()]); roochPublicKey.set(bytes, 1); return toB64(roochPublicKey); } }; // src/utils/crypto/keypair.ts import { sha3_256 } from "@noble/hashes/sha3"; var PRIVATE_KEY_SIZE = 32; var BaseSigner = class { async signMessage(bytes) { const digest = sha3_256(bytes); return this.signMessageWithHashed(digest); } async signMessageWithHashed(bytes) { const signature = toSerializedSignature({ signature: await this.sign(bytes), signatureScheme: this.getKeyScheme(), pubKey: this.getPublicKey() }); return { signature, bytes }; } toRoochAddress() { return this.getPublicKey().toRoochAddress(); } }; var Keypair = class extends BaseSigner { }; // src/utils/keypairs/ed25519/keypair.ts import nacl2 from "tweetnacl"; // src/utils/keypairs/ed25519/publickey.ts import { blake2b } from "@noble/hashes/blake2b"; import { bytesToHex as bytesToHex2 } from "@noble/hashes/utils"; var PUBLIC_KEY_SIZE = 32; var Ed25519PublicKey = class extends PublicKey { /** * Create a new Ed25519PublicKey object * @param value ed25519 public key as buffer or base-64 encoded string */ constructor(value) { super(); if (typeof value === "string") { this.data = fromB64(value); } else if (value instanceof Uint8Array) { this.data = value; } else { this.data = Uint8Array.from(value); } if (this.data.length !== PUBLIC_KEY_SIZE) { throw new Error( `Invalid public key input. Expected ${PUBLIC_KEY_SIZE} bytes, got ${this.data.length}` ); } } /** * Checks if two Ed25519 public keys are equal */ equals(publicKey) { return super.equals(publicKey); } /** * Return the byte array representation of the Ed25519 public key */ toBytes() { return this.data; } /** * Return the Rooch address associated with this Ed25519 public key */ toRoochAddress() { const tmp = new Uint8Array(PUBLIC_KEY_SIZE + 1); tmp.set([SIGNATURE_SCHEME_TO_FLAG.ED25519]); tmp.set(this.toBytes(), 1); return normalizeRoochAddress( bytesToHex2(blake2b(tmp, { dkLen: 32 })).slice(0, ROOCH_ADDRESS_LENGTH) ); } /** * Return the Rooch address associated with this Ed25519 public key */ // eslint-disable-next-line class-methods-use-this flag() { return SIGNATURE_SCHEME_TO_FLAG.ED25519; } }; Ed25519PublicKey.SIZE = PUBLIC_KEY_SIZE; // src/utils/keypairs/ed25519/ed25519-hd-key.ts import { sha512 } from "@noble/hashes/sha512"; import { hmac } from "@noble/hashes/hmac"; import nacl from "tweetnacl"; var ED25519_CURVE = "ed25519 seed"; var HARDENED_OFFSET = 2147483648; var pathRegex = /^m(\/[0-9]+')+$/; var replaceDerive = (val) => val.replace("'", ""); var getMasterKeyFromSeed = (seed) => { const h = hmac.create(sha512, ED25519_CURVE); const I = h.update(fromHexString(seed)).digest(); const IL = I.slice(0, 32); const IR = I.slice(32); return { key: IL, chainCode: IR }; }; var CKDPriv = ({ key, chainCode }, index) => { const indexBuffer = new ArrayBuffer(4); const cv = new DataView(indexBuffer); cv.setUint32(0, index); const data = new Uint8Array(1 + key.length + indexBuffer.byteLength); data.set(new Uint8Array(1).fill(0)); data.set(key, 1); data.set(new Uint8Array(indexBuffer, 0, indexBuffer.byteLength), key.length + 1); const I = hmac.create(sha512, chainCode).update(data).digest(); const IL = I.slice(0, 32); const IR = I.slice(32); return { key: IL, chainCode: IR }; }; var isValidPath = (path) => { if (!pathRegex.test(path)) { return false; } return !path.split("/").slice(1).map(replaceDerive).some( Number.isNaN /* ts T_T */ ); }; var derivePath = (path, seed, offset = HARDENED_OFFSET) => { if (!isValidPath(path)) { throw new Error("Invalid derivation path"); } const { key, chainCode } = getMasterKeyFromSeed(seed); const segments = path.split("/").slice(1).map(replaceDerive).map((el) => parseInt(el, 10)); return segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), { key, chainCode }); }; // src/utils/keypairs/ed25519/keypair.ts var DEFAULT_ED25519_DERIVATION_PATH = "m/44'/784'/0'/0'/0'"; var DEFAULT_ED25519_SCHEMAS = "ED25519"; var Ed25519Keypair = class extends Keypair { /** * Create a new Ed25519 keypair instance. * Generate random keypair if no {@link Ed25519Keypair} is provided. * * @param keypair Ed25519 keypair */ constructor(keypair) { super(); if (keypair) { this.keypair = keypair; } else { this.keypair = nacl2.sign.keyPair(); } this.scheme = "ED25519"; } /** * Get the key scheme of the keypair ED25519 */ getKeyScheme() { return this.scheme; } /** * Generate a new random Ed25519 keypair */ static generate() { return new Ed25519Keypair(nacl2.sign.keyPair()); } /** * Create a Ed25519 keypair from a raw secret key byte array, also known as seed. * This is NOT the private scalar which is result of hashing and bit clamping of * the raw secret key. * * The rooch.keystore key is a list of Base64 encoded `flag || privkey`. To import * a key from rooch.keystore to typescript, decode from base64 and remove the first * flag byte after checking it is indeed the Ed25519 scheme flag 0x00 (See more * on flag for signature scheme: https://github.com/rooch-network/rooch/blob/main/crates/rooch-types/src/crypto.rs): * ``` * import { Ed25519Keypair, fromB64 } from 'rooch' * const raw = fromB64(t[1]) * if (raw[0] !== 0 || raw.length !== PRIVATE_KEY_SIZE + 1) { * throw new Error('invalid key') * } * const imported = Ed25519Keypair.fromSecretKey(raw.slice(1)) * ``` * @throws error if the provided secret key is invalid and validation is not skipped. * * @param secretKey secret key byte array * @param options: skip secret key validation */ static fromSecretKey(secretKey, options) { const secretKeyLength = secretKey.length; if (secretKeyLength !== PRIVATE_KEY_SIZE) { throw new Error( `Wrong secretKey size. Expected ${PRIVATE_KEY_SIZE} bytes, got ${secretKeyLength}.` ); } const keypair = nacl2.sign.keyPair.fromSeed(secretKey); if (!options || !options.skipValidation) { const encoder = new TextEncoder(); const signData = encoder.encode("rooch validation"); const signature = nacl2.sign.detached(signData, keypair.secretKey); if (!nacl2.sign.detached.verify(signData, signature, keypair.publicKey)) { throw new Error("provided secretKey is invalid"); } } return new Ed25519Keypair(keypair); } /** * The public key for this Ed25519 keypair */ getPublicKey() { return new Ed25519PublicKey(this.keypair.publicKey); } async sign(data) { return this.signData(data); } /** * Return the signature for the provided data using Ed25519. */ signData(data) { return nacl2.sign.detached(data, this.keypair.secretKey); } /** * Derive Ed25519 keypair from mnemonics and path. The mnemonics must be normalized * and validated against the english wordlist. * * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'. */ static deriveKeypair(mnemonics, path) { const newPath = path ?? DEFAULT_ED25519_DERIVATION_PATH; if (!isValidHardenedPath(newPath)) { throw new Error("Invalid derivation path"); } const { key } = derivePath(newPath, mnemonicToSeedHex(mnemonics)); return Ed25519Keypair.fromSecretKey(key); } /** * Derive Ed25519 keypair from mnemonicSeed and path. * * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'. */ static deriveKeypairFromSeed(seedHex, path) { const newPath = path ?? DEFAULT_ED25519_DERIVATION_PATH; if (!isValidHardenedPath(newPath)) { throw new Error("Invalid derivation path"); } const { key } = derivePath(newPath, seedHex); return Ed25519Keypair.fromSecretKey(key); } /** * This returns an exported keypair object, the private key field is the pure 32-byte seed. */ export() { return { schema: "ED25519", privateKey: toB64(this.keypair.secretKey.slice(0, PRIVATE_KEY_SIZE)) }; } }; // src/provider/json-rpc-provider.ts import { HTTPTransport, RequestManager as RequestManager2 } from "@open-rpc/client-js"; // src/generated/client/client.ts import { Client } from "@open-rpc/client-js"; var JsonRpcClient = class extends Client { constructor(requestManager) { super(requestManager); } async getRpcApiVersion() { const resp = await this.request({ method: "rpc.discover", params: [] }); return resp.info.version; } // Send the signed transaction in bcs hex format This method blocks waiting for the transaction to be executed. async rooch_executeRawTransaction(tx_bcs_hex) { const tx_bcs_hex_hex = `0x${Buffer.from(tx_bcs_hex).toString("hex")}`; const resp = await this.request({ method: "rooch_executeRawTransaction", params: [tx_bcs_hex_hex] }); return resp; } // Execute a read-only function call The function do not change the state of Application async rooch_executeViewFunction(function_call) { const resp = await this.request({ method: "rooch_executeViewFunction", params: [function_call] }); return resp; } // Get the annotated states by access_path The annotated states include the decoded move value of the state async rooch_getAnnotatedStates(access_path) { const resp = await this.request({ method: "rooch_getAnnotatedStates", params: [access_path] }); return resp; } // get account balances by AccountAddress async rooch_getBalances(account_addr, coin_type, cursor, limit) { const cursor_hex = `0x${Buffer.from(cursor).toString("hex")}`; const resp = await this.request