@concordium/common-sdk
Advanced tools
Comparing version
import { AccountAddress } from './types/accountAddress'; | ||
import { ReduceStakePendingChange, RemovalPendingChange, StakePendingChange, StakePendingChangeV1, AccountInfo, AccountInfoBaker, AccountInfoBakerV0, AccountInfoBakerV1, AccountInfoDelegator, StakePendingChangeV0, GenerateBakerKeysOutput } from './types'; | ||
import { ReduceStakePendingChange, RemovalPendingChange, AccountInfo, AccountInfoBaker, AccountInfoDelegator, GenerateBakerKeysOutput } from './types'; | ||
/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoDelegator}, i.e. the account is a delegator */ | ||
export declare const isDelegatorAccount: (ai: AccountInfo) => ai is AccountInfoDelegator; | ||
/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoBaker}, i.e. the account is a baker. */ | ||
export declare const isBakerAccount: (ai: AccountInfo) => ai is AccountInfoBaker; | ||
export declare const isBakerAccountV1: (ai: AccountInfo) => ai is AccountInfoBakerV1; | ||
export declare const isBakerAccountV0: (ai: AccountInfo) => ai is AccountInfoBakerV0; | ||
export declare const isStakePendingChangeV1: (spc: StakePendingChange) => spc is StakePendingChangeV1; | ||
export declare const isStakePendingChangeV0: (spc: StakePendingChange) => spc is StakePendingChangeV0; | ||
/** Whether the pending change given is of type {@link ReduceStakePendingChange} */ | ||
export declare const isReduceStakePendingChange: (spc: ReduceStakePendingChange | RemovalPendingChange) => spc is ReduceStakePendingChange; | ||
/** Whether the pending change given is of type {@link RemovalPendingChange} */ | ||
export declare const isRemovalPendingChange: (spc: ReduceStakePendingChange | RemovalPendingChange) => spc is RemovalPendingChange; | ||
@@ -11,0 +11,0 @@ /** |
@@ -26,18 +26,14 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateBakerKeys = exports.isRemovalPendingChange = exports.isReduceStakePendingChange = exports.isStakePendingChangeV0 = exports.isStakePendingChangeV1 = exports.isBakerAccountV0 = exports.isBakerAccountV1 = exports.isBakerAccount = exports.isDelegatorAccount = void 0; | ||
exports.generateBakerKeys = exports.isRemovalPendingChange = exports.isReduceStakePendingChange = exports.isBakerAccount = exports.isDelegatorAccount = void 0; | ||
const wasm = __importStar(require("@concordium/rust-bindings")); | ||
/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoDelegator}, i.e. the account is a delegator */ | ||
const isDelegatorAccount = (ai) => ai.accountDelegation !== undefined; | ||
exports.isDelegatorAccount = isDelegatorAccount; | ||
/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoBaker}, i.e. the account is a baker. */ | ||
const isBakerAccount = (ai) => ai.accountBaker !== undefined; | ||
exports.isBakerAccount = isBakerAccount; | ||
const isBakerAccountV1 = (ai) => ai.accountBaker?.bakerPoolInfo !== undefined; | ||
exports.isBakerAccountV1 = isBakerAccountV1; | ||
const isBakerAccountV0 = (ai) => ai.accountBaker?.bakerPoolInfo === undefined; | ||
exports.isBakerAccountV0 = isBakerAccountV0; | ||
const isStakePendingChangeV1 = (spc) => spc.effectiveTime !== undefined; | ||
exports.isStakePendingChangeV1 = isStakePendingChangeV1; | ||
const isStakePendingChangeV0 = (spc) => spc.epoch !== undefined; | ||
exports.isStakePendingChangeV0 = isStakePendingChangeV0; | ||
/** Whether the pending change given is of type {@link ReduceStakePendingChange} */ | ||
const isReduceStakePendingChange = (spc) => spc.newStake !== undefined; | ||
exports.isReduceStakePendingChange = isReduceStakePendingChange; | ||
/** Whether the pending change given is of type {@link RemovalPendingChange} */ | ||
const isRemovalPendingChange = (spc) => !(0, exports.isReduceStakePendingChange)(spc); | ||
@@ -44,0 +40,0 @@ exports.isRemovalPendingChange = isRemovalPendingChange; |
@@ -1,12 +0,13 @@ | ||
import { Authorizations, AuthorizationsV1, BlockSummary, BlockSummaryV0, BlockSummaryV1, ChainParameters, ChainParametersV0, ChainParametersV1, Keys, KeysV0, KeysV1, UpdateQueues, UpdateQueuesV0, UpdateQueuesV1, Updates, UpdatesV0, UpdatesV1 } from './types'; | ||
export declare const isAuthorizationsV1: (a: Authorizations) => a is AuthorizationsV1; | ||
export declare const isChainParametersV1: (cp: ChainParameters) => cp is ChainParametersV1; | ||
export declare const isChainParametersV0: (cp: ChainParameters) => cp is ChainParametersV0; | ||
export declare const isKeysV1: (k: Keys) => k is KeysV1; | ||
export declare const isKeysV0: (k: Keys) => k is KeysV0; | ||
import { BlockSummary, BlockSummaryV0, BlockSummaryV1, BlockSummaryV2, UpdateQueues, UpdateQueuesV0, UpdateQueuesV1, UpdateQueuesV2, Updates, UpdatesV0, UpdatesV1, UpdatesV2 } from './types'; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV0} */ | ||
export declare const isUpdateQueuesV0: (uq: UpdateQueues) => uq is UpdateQueuesV0; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV1} */ | ||
export declare const isUpdateQueuesV1: (uq: UpdateQueues) => uq is UpdateQueuesV1; | ||
export declare const isUpdateQueuesV0: (uq: UpdateQueues) => uq is UpdateQueuesV0; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV2} */ | ||
export declare const isUpdateQueuesV2: (uq: UpdateQueues) => uq is UpdateQueuesV2; | ||
export declare const isUpdatesV0: (u: Updates) => u is UpdatesV0; | ||
export declare const isUpdatesV1: (u: Updates) => u is UpdatesV1; | ||
export declare const isUpdatesV0: (u: Updates) => u is UpdatesV0; | ||
export declare const isUpdatesV2: (u: Updates) => u is UpdatesV2; | ||
export declare const isBlockSummaryV0: (bs: BlockSummary) => bs is BlockSummaryV0; | ||
export declare const isBlockSummaryV1: (bs: BlockSummary) => bs is BlockSummaryV1; | ||
export declare const isBlockSummaryV0: (bs: BlockSummary) => bs is BlockSummaryV0; | ||
export declare const isBlockSummaryV2: (bs: BlockSummary) => bs is BlockSummaryV2; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isBlockSummaryV0 = exports.isBlockSummaryV1 = exports.isUpdatesV0 = exports.isUpdatesV1 = exports.isUpdateQueuesV0 = exports.isUpdateQueuesV1 = exports.isKeysV0 = exports.isKeysV1 = exports.isChainParametersV0 = exports.isChainParametersV1 = exports.isAuthorizationsV1 = void 0; | ||
const isAuthorizationsV1 = (a) => a.timeParameters !== undefined; | ||
exports.isAuthorizationsV1 = isAuthorizationsV1; | ||
const isChainParametersV1 = (cp) => cp.mintPerPayday !== undefined; | ||
exports.isChainParametersV1 = isChainParametersV1; | ||
const isChainParametersV0 = (cp) => cp.minimumThresholdForBaking !== undefined; | ||
exports.isChainParametersV0 = isChainParametersV0; | ||
const isKeysV1 = (k) => (0, exports.isAuthorizationsV1)(k.level2Keys); | ||
exports.isKeysV1 = isKeysV1; | ||
const isKeysV0 = (k) => !(0, exports.isAuthorizationsV1)(k.level2Keys); | ||
exports.isKeysV0 = isKeysV0; | ||
exports.isBlockSummaryV2 = exports.isBlockSummaryV1 = exports.isBlockSummaryV0 = exports.isUpdatesV2 = exports.isUpdatesV1 = exports.isUpdatesV0 = exports.isUpdateQueuesV2 = exports.isUpdateQueuesV1 = exports.isUpdateQueuesV0 = void 0; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV0} */ | ||
const isUpdateQueuesV0 = (uq) => uq.bakerStakeThreshold !== undefined; | ||
exports.isUpdateQueuesV0 = isUpdateQueuesV0; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV1} */ | ||
const isUpdateQueuesV1 = (uq) => uq.timeParameters !== undefined; | ||
exports.isUpdateQueuesV1 = isUpdateQueuesV1; | ||
const isUpdateQueuesV0 = (uq) => uq.bakerStakeThreshold !== undefined; | ||
exports.isUpdateQueuesV0 = isUpdateQueuesV0; | ||
/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV2} */ | ||
const isUpdateQueuesV2 = (uq) => uq.consensus2TimingParameters !== undefined; | ||
exports.isUpdateQueuesV2 = isUpdateQueuesV2; | ||
const isUpdatesV0 = (u) => (0, exports.isUpdateQueuesV0)(u.updateQueues); | ||
exports.isUpdatesV0 = isUpdatesV0; | ||
const isUpdatesV1 = (u) => (0, exports.isUpdateQueuesV1)(u.updateQueues); | ||
exports.isUpdatesV1 = isUpdatesV1; | ||
const isUpdatesV0 = (u) => (0, exports.isUpdateQueuesV0)(u.updateQueues); | ||
exports.isUpdatesV0 = isUpdatesV0; | ||
const isBlockSummaryV1 = (bs) => bs.protocolVersion !== undefined && bs.protocolVersion > 3n; | ||
exports.isBlockSummaryV1 = isBlockSummaryV1; | ||
const isUpdatesV2 = (u) => (0, exports.isUpdateQueuesV2)(u.updateQueues); | ||
exports.isUpdatesV2 = isUpdatesV2; | ||
const isBlockSummaryV0 = (bs) => bs.protocolVersion === undefined || bs.protocolVersion <= 3n; | ||
exports.isBlockSummaryV0 = isBlockSummaryV0; | ||
const isBlockSummaryV1 = (bs) => bs.protocolVersion !== undefined && | ||
bs.protocolVersion > 3n && | ||
bs.protocolVersion <= 5n; | ||
exports.isBlockSummaryV1 = isBlockSummaryV1; | ||
const isBlockSummaryV2 = (bs) => bs.protocolVersion !== undefined && bs.protocolVersion > 5n; | ||
exports.isBlockSummaryV2 = isBlockSummaryV2; |
import { ContractAddress, HexString } from './types'; | ||
import ConcordiumNodeClient from './GRPCClient'; | ||
/** Namespace with types for CIS-0 standard contracts */ | ||
import { ConcordiumGRPCClient } from './GRPCClient'; | ||
/** | ||
* Namespace with types for CIS-0 standard contracts | ||
*/ | ||
export declare namespace CIS0 { | ||
@@ -36,3 +38,3 @@ /** Identifier to query for support, f.x. 'CIS-2' */ | ||
* | ||
* @param {ConcordiumNodeClient} grpcClient - The client to be used for the query. | ||
* @param {ConcordiumGRPCClient} grpcClient - The client to be used for the query. | ||
* @param {ContractAddress} contractAddress - The address of the contract to query. | ||
@@ -46,7 +48,7 @@ * @param {CIS0.StandardIdentifier} standardId - The standard identifier to query for support in contract. | ||
*/ | ||
export declare function cis0Supports(grpcClient: ConcordiumNodeClient, contractAddress: ContractAddress, standardId: CIS0.StandardIdentifier, blockHash?: HexString): Promise<CIS0.SupportResult | undefined>; | ||
export declare function cis0Supports(grpcClient: ConcordiumGRPCClient, contractAddress: ContractAddress, standardId: CIS0.StandardIdentifier, blockHash?: HexString): Promise<CIS0.SupportResult | undefined>; | ||
/** | ||
* Queries a CIS-0 contract for support for a {@link CIS0.StandardIdentifier}. | ||
* | ||
* @param {ConcordiumNodeClient} grpcClient - The client to be used for the query. | ||
* @param {ConcordiumGRPCClient} grpcClient - The client to be used for the query. | ||
* @param {ContractAddress} contractAddress - The address of the contract to query. | ||
@@ -60,2 +62,2 @@ * @param {CIS0.StandardIdentifier[]} standardIds - The standard identifiers to query for support in contract. | ||
*/ | ||
export declare function cis0Supports(grpcClient: ConcordiumNodeClient, contractAddress: ContractAddress, standardIds: CIS0.StandardIdentifier[], blockHash?: HexString): Promise<CIS0.SupportResult[] | undefined>; | ||
export declare function cis0Supports(grpcClient: ConcordiumGRPCClient, contractAddress: ContractAddress, standardIds: CIS0.StandardIdentifier[], blockHash?: HexString): Promise<CIS0.SupportResult[] | undefined>; |
@@ -9,3 +9,5 @@ "use strict"; | ||
const util_1 = require("./util"); | ||
/** Namespace with types for CIS-0 standard contracts */ | ||
/** | ||
* Namespace with types for CIS-0 standard contracts | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
@@ -12,0 +14,0 @@ var CIS0; |
import { ContractAddress, HexString, InvokeContractResult } from '../types'; | ||
import ConcordiumNodeClient from '../GRPCClient'; | ||
import { ConcordiumGRPCClient } from '../GRPCClient'; | ||
import { AccountSigner } from '../signHelpers'; | ||
@@ -12,3 +12,3 @@ import type { CIS2 } from './util'; | ||
private contractName; | ||
constructor(grpcClient: ConcordiumNodeClient, contractAddress: ContractAddress, contractName: string); | ||
constructor(grpcClient: ConcordiumGRPCClient, contractAddress: ContractAddress, contractName: string); | ||
/** | ||
@@ -57,7 +57,7 @@ * Performs a dry-run invocation of "transfer" on a corresponding {@link CIS2Contract} instance | ||
private dryRunInstance; | ||
constructor(grpcClient: ConcordiumNodeClient, contractAddress: ContractAddress, contractName: string); | ||
constructor(grpcClient: ConcordiumGRPCClient, contractAddress: ContractAddress, contractName: string); | ||
/** | ||
* Creates a new `CIS2Contract` instance by querying the node for the necessary information through the supplied `grpcClient`. | ||
* | ||
* @param {ConcordiumNodeClient} grpcClient - The client used for contract invocations and updates. | ||
* @param {ConcordiumGRPCClient} grpcClient - The client used for contract invocations and updates. | ||
* @param {ContractAddress} contractAddress - Address of the contract instance. | ||
@@ -68,3 +68,3 @@ * | ||
*/ | ||
static create(grpcClient: ConcordiumNodeClient, contractAddress: ContractAddress): Promise<CIS2Contract>; | ||
static create(grpcClient: ConcordiumGRPCClient, contractAddress: ContractAddress): Promise<CIS2Contract>; | ||
/** | ||
@@ -71,0 +71,0 @@ * Creates a CIS-2 "transfer" update transaction containing a single transfer. |
@@ -75,3 +75,3 @@ "use strict"; | ||
* | ||
* @param {ConcordiumNodeClient} grpcClient - The client used for contract invocations and updates. | ||
* @param {ConcordiumGRPCClient} grpcClient - The client used for contract invocations and updates. | ||
* @param {ContractAddress} contractAddress - Address of the contract instance. | ||
@@ -78,0 +78,0 @@ * |
export type { CIS2 } from './util'; | ||
export { tokenAddressFromBase58, tokenAddressToBase58 } from './util'; | ||
export * from './CIS2Contract'; |
@@ -17,2 +17,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.tokenAddressToBase58 = exports.tokenAddressFromBase58 = void 0; | ||
var util_1 = require("./util"); | ||
Object.defineProperty(exports, "tokenAddressFromBase58", { enumerable: true, get: function () { return util_1.tokenAddressFromBase58; } }); | ||
Object.defineProperty(exports, "tokenAddressToBase58", { enumerable: true, get: function () { return util_1.tokenAddressToBase58; } }); | ||
__exportStar(require("./CIS2Contract"), exports); |
@@ -9,2 +9,14 @@ import { AccountTransactionType, Base58String, Base64String, ContractAddress, HexString, SmartContractTypeValues, UpdateContractPayload } from '../types'; | ||
/** | ||
* A Token ID that uniquely identifies the CIS-2 Token | ||
*/ | ||
type TokenId = HexString; | ||
/** | ||
* A Token Address, that contains both a Contract Address and the unique | ||
* CIS-2 Token ID. | ||
*/ | ||
type TokenAddress = { | ||
contract: ContractAddress; | ||
id: TokenId; | ||
}; | ||
/** | ||
* A contract address along with the name of the hook to be triggered when receiving a CIS-2 transfer. | ||
@@ -225,2 +237,17 @@ */ | ||
/** | ||
* Parses a token address from a Base58-string. Will throw if the Base58 | ||
* encoding is not a valid token address. | ||
* | ||
* @param str A Base58 encoded token address | ||
* @returns A parsed token address | ||
*/ | ||
export declare function tokenAddressFromBase58(str: Base58String): CIS2.TokenAddress; | ||
/** | ||
* Returns the Base58-encoding of the given CIS2 Token Address. | ||
* | ||
* @param tokenAddress A token address to convert into the base58-string format | ||
* @returns The base58-formatted string | ||
*/ | ||
export declare function tokenAddressToBase58(tokenAddress: CIS2.TokenAddress): Base58String; | ||
/** | ||
* Serializes a list of {@link CIS2.OperatorOfQuery} queries according to the CIS-2 standard. | ||
@@ -227,0 +254,0 @@ * |
"use strict"; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.formatCIS2Transfer = exports.formatCIS2UpdateOperator = exports.deserializeCIS2OperatorOfResponse = exports.serializeCIS2OperatorOfQueries = exports.deserializeCIS2TokenMetadataResponse = exports.serializeCIS2TokenIds = exports.deserializeCIS2BalanceOfResponse = exports.serializeCIS2BalanceOfQueries = exports.serializeCIS2UpdateOperators = exports.serializeCIS2Transfers = exports.isContractAddress = void 0; | ||
exports.formatCIS2Transfer = exports.formatCIS2UpdateOperator = exports.deserializeCIS2OperatorOfResponse = exports.serializeCIS2OperatorOfQueries = exports.tokenAddressToBase58 = exports.tokenAddressFromBase58 = exports.deserializeCIS2TokenMetadataResponse = exports.serializeCIS2TokenIds = exports.deserializeCIS2BalanceOfResponse = exports.serializeCIS2BalanceOfQueries = exports.serializeCIS2UpdateOperators = exports.serializeCIS2Transfers = exports.isContractAddress = void 0; | ||
const bs58check_1 = __importDefault(require("bs58check")); | ||
const serializationHelpers_1 = require("../serializationHelpers"); | ||
@@ -8,3 +12,3 @@ const buffer_1 = require("buffer/"); | ||
const uleb128_1 = require("../uleb128"); | ||
const TOKEN_ID_MAX_LENGTH = 256; | ||
const TOKEN_ID_MAX_LENGTH = 255; | ||
const TOKEN_AMOUNT_MAX_LENGTH = 37; | ||
@@ -24,2 +28,8 @@ const TOKEN_RECEIVE_HOOK_MAX_LENGTH = 100; | ||
} | ||
function deserializeCIS2TokenId(buffer) { | ||
if (buffer.length > TOKEN_ID_MAX_LENGTH) { | ||
throw Error(`Token ID exceeds maximum size of ${TOKEN_ID_MAX_LENGTH} bytes`); | ||
} | ||
return buffer.toString('hex'); | ||
} | ||
function serializeTokenAmount(amount) { | ||
@@ -203,2 +213,49 @@ if (amount < 0) { | ||
/** | ||
* Parses a token address from a Base58-string. Will throw if the Base58 | ||
* encoding is not a valid token address. | ||
* | ||
* @param str A Base58 encoded token address | ||
* @returns A parsed token address | ||
*/ | ||
function tokenAddressFromBase58(str) { | ||
const bytes = new buffer_1.Buffer(bs58check_1.default.decode(str)); | ||
const firstByte = bytes[0]; | ||
const [index, i] = (0, uleb128_1.uleb128DecodeWithIndex)(bytes, 1); | ||
const [subindex, j] = (0, uleb128_1.uleb128DecodeWithIndex)(bytes, i); | ||
const tokenIdBytes = new buffer_1.Buffer(bytes.subarray(j)); | ||
if (firstByte !== 2) { | ||
throw Error('Invalid token address: The Base58Check version byte is expected to be 2'); | ||
} | ||
const contract = { | ||
index, | ||
subindex, | ||
}; | ||
const id = deserializeCIS2TokenId(tokenIdBytes); | ||
return { | ||
contract, | ||
id, | ||
}; | ||
} | ||
exports.tokenAddressFromBase58 = tokenAddressFromBase58; | ||
/** | ||
* Returns the Base58-encoding of the given CIS2 Token Address. | ||
* | ||
* @param tokenAddress A token address to convert into the base58-string format | ||
* @returns The base58-formatted string | ||
*/ | ||
function tokenAddressToBase58(tokenAddress) { | ||
const firstByte = buffer_1.Buffer.from('02', 'hex'); | ||
const indexBytes = (0, uleb128_1.uleb128Encode)(tokenAddress.contract.index); | ||
const subindexBytes = (0, uleb128_1.uleb128Encode)(tokenAddress.contract.subindex); | ||
const tokenBytes = buffer_1.Buffer.from(tokenAddress.id, 'hex'); | ||
const bytes = buffer_1.Buffer.concat([ | ||
firstByte, | ||
indexBytes, | ||
subindexBytes, | ||
tokenBytes, | ||
]); | ||
return bs58check_1.default.encode(bytes); | ||
} | ||
exports.tokenAddressToBase58 = tokenAddressToBase58; | ||
/** | ||
* Serializes a list of {@link CIS2.OperatorOfQuery} queries according to the CIS-2 standard. | ||
@@ -205,0 +262,0 @@ * |
@@ -19,2 +19,5 @@ import { Buffer } from 'buffer/'; | ||
export declare const checkParameterLength: (buffer: Buffer) => void; | ||
/** | ||
* Whether two {@link ContractAddress} contract addresses are equal. | ||
*/ | ||
export declare const isEqualContractAddress: (a: ContractAddress) => (b: ContractAddress) => boolean; |
@@ -32,3 +32,6 @@ "use strict"; | ||
exports.checkParameterLength = checkParameterLength; | ||
/** | ||
* Whether two {@link ContractAddress} contract addresses are equal. | ||
*/ | ||
const isEqualContractAddress = (a) => (b) => a.index === b.index && a.subindex === b.subindex; | ||
exports.isEqualContractAddress = isEqualContractAddress; |
@@ -16,3 +16,3 @@ /// <reference types="node" /> | ||
*/ | ||
export declare function deserializeContractState(contractName: string, schema: Buffer, state: Buffer): any; | ||
export declare function deserializeContractState(contractName: string, schema: Buffer, state: Buffer, verboseErrorMessage?: boolean): any; | ||
export declare type BlockItem = { | ||
@@ -43,6 +43,6 @@ kind: BlockItemKind.AccountTransactionKind; | ||
* @param functionName The name of the receive function which return value you want to deserialize. | ||
* @param schemaVersion The schema version as a number. This parameter is optional, | ||
* if you provide a serialized versioned schema this argument won't be needed. | ||
* @param schemaVersion The schema version as a number. This parameter is optional, if you provide a serialized versioned schema this argument won't be needed. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
export declare function deserializeReceiveReturnValue(returnValueBytes: Buffer, moduleSchema: Buffer, contractName: string, functionName: string, schemaVersion?: number): any; | ||
export declare function deserializeReceiveReturnValue(returnValueBytes: Buffer, moduleSchema: Buffer, contractName: string, functionName: string, schemaVersion?: number, verboseErrorMessage?: boolean): any; | ||
/** | ||
@@ -54,11 +54,13 @@ * Deserializes a receive function's error from a sequence of bytes into a json object. | ||
* @param functionName The name of the receive function which error you want to deserialize. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
export declare function deserializeReceiveError(errorBytes: Buffer, moduleSchema: Buffer, contractName: string, functionName: string): any; | ||
export declare function deserializeReceiveError(errorBytes: Buffer, moduleSchema: Buffer, contractName: string, functionName: string, verboseErrorMessage?: boolean): any; | ||
/** | ||
* Deserializes an init function's error from a sequence of bytes into a json object. | ||
* @param returnValueBytes A buffer containing the error as raw bytes. | ||
* @param errorBytes A buffer containing the error as raw bytes. | ||
* @param moduleSchema The raw module schema as a buffer. | ||
* @param contractName The name of the init function which error you want to deserialize. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
export declare function deserializeInitError(errorBytes: Buffer, moduleSchema: Buffer, contractName: string): any; | ||
export declare function deserializeInitError(errorBytes: Buffer, moduleSchema: Buffer, contractName: string, verboseErrorMessage?: boolean): any; | ||
/** | ||
@@ -68,4 +70,5 @@ * Given a binary value for a smart contract type, and the raw schema for that type, deserialize the value into the JSON representation. | ||
* @param rawSchema the schema for the type that the given value should be deserialized as | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns the deserialized value | ||
*/ | ||
export declare function deserializeTypeValue(value: Buffer, rawSchema: Buffer): SmartContractTypeValues; | ||
export declare function deserializeTypeValue(value: Buffer, rawSchema: Buffer, verboseErrorMessage?: boolean): SmartContractTypeValues; |
@@ -48,6 +48,6 @@ "use strict"; | ||
*/ | ||
function deserializeContractState(contractName, schema, state | ||
function deserializeContractState(contractName, schema, state, verboseErrorMessage = false | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
) { | ||
const serializedState = wasm.deserializeState(contractName, state.toString('hex'), schema.toString('hex')); | ||
const serializedState = wasm.deserializeState(contractName, state.toString('hex'), schema.toString('hex'), verboseErrorMessage); | ||
try { | ||
@@ -165,9 +165,9 @@ return JSON.parse(serializedState); | ||
* @param functionName The name of the receive function which return value you want to deserialize. | ||
* @param schemaVersion The schema version as a number. This parameter is optional, | ||
* if you provide a serialized versioned schema this argument won't be needed. | ||
* @param schemaVersion The schema version as a number. This parameter is optional, if you provide a serialized versioned schema this argument won't be needed. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
function deserializeReceiveReturnValue(returnValueBytes, moduleSchema, contractName, functionName, schemaVersion | ||
function deserializeReceiveReturnValue(returnValueBytes, moduleSchema, contractName, functionName, schemaVersion, verboseErrorMessage = false | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
) { | ||
const deserializedReturnValue = wasm.deserializeReceiveReturnValue(returnValueBytes.toString('hex'), moduleSchema.toString('hex'), contractName, functionName, schemaVersion); | ||
const deserializedReturnValue = wasm.deserializeReceiveReturnValue(returnValueBytes.toString('hex'), moduleSchema.toString('hex'), contractName, functionName, schemaVersion, verboseErrorMessage); | ||
try { | ||
@@ -188,7 +188,8 @@ return JSON.parse(deserializedReturnValue); | ||
* @param functionName The name of the receive function which error you want to deserialize. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
function deserializeReceiveError(errorBytes, moduleSchema, contractName, functionName | ||
function deserializeReceiveError(errorBytes, moduleSchema, contractName, functionName, verboseErrorMessage = false | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
) { | ||
const deserializedError = wasm.deserializeReceiveError(errorBytes.toString('hex'), moduleSchema.toString('hex'), contractName, functionName); | ||
const deserializedError = wasm.deserializeReceiveError(errorBytes.toString('hex'), moduleSchema.toString('hex'), contractName, functionName, verboseErrorMessage); | ||
try { | ||
@@ -205,10 +206,11 @@ return JSON.parse(deserializedError); | ||
* Deserializes an init function's error from a sequence of bytes into a json object. | ||
* @param returnValueBytes A buffer containing the error as raw bytes. | ||
* @param errorBytes A buffer containing the error as raw bytes. | ||
* @param moduleSchema The raw module schema as a buffer. | ||
* @param contractName The name of the init function which error you want to deserialize. | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
*/ | ||
function deserializeInitError(errorBytes, moduleSchema, contractName | ||
function deserializeInitError(errorBytes, moduleSchema, contractName, verboseErrorMessage = false | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
) { | ||
const deserializedError = wasm.deserializeInitError(errorBytes.toString('hex'), moduleSchema.toString('hex'), contractName); | ||
const deserializedError = wasm.deserializeInitError(errorBytes.toString('hex'), moduleSchema.toString('hex'), contractName, verboseErrorMessage); | ||
try { | ||
@@ -227,8 +229,9 @@ return JSON.parse(deserializedError); | ||
* @param rawSchema the schema for the type that the given value should be deserialized as | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns the deserialized value | ||
*/ | ||
function deserializeTypeValue(value, rawSchema) { | ||
const deserializedValue = wasm.deserializeTypeValue(value.toString('hex'), rawSchema.toString('hex')); | ||
function deserializeTypeValue(value, rawSchema, verboseErrorMessage = false) { | ||
const deserializedValue = wasm.deserializeTypeValue(value.toString('hex'), rawSchema.toString('hex'), verboseErrorMessage); | ||
return JSON.parse(deserializedValue); | ||
} | ||
exports.deserializeTypeValue = deserializeTypeValue; |
@@ -0,1 +1,7 @@ | ||
/** | ||
* This is the GRPC-Client used by both the Web-SDK and the NodeJS-SDK. Check | ||
* out the {@link ConcordiumGRPCClient} | ||
* | ||
* @module Common GRPC-Client | ||
*/ | ||
import { Buffer } from 'buffer/'; | ||
@@ -10,2 +16,5 @@ import * as v1 from './types'; | ||
import { ModuleReference } from './types/moduleReference'; | ||
/** | ||
* @hidden | ||
*/ | ||
export declare type FindInstanceCreationReponse = { | ||
@@ -20,6 +29,6 @@ hash: HexString; | ||
* @example | ||
* import ConcordiumNodeClient from "..." | ||
* const client = new ConcordiumNodeClient('127.0.0.1', 20000, credentials, metadata, 15000); | ||
* import { ConcordiumGRPCClient } from "..." | ||
* const client = new ConcordiumGRPCClient('127.0.0.1', 20000, credentials, metadata, 15000); | ||
*/ | ||
export default class ConcordiumNodeClient { | ||
export declare class ConcordiumGRPCClient { | ||
client: QueriesClient; | ||
@@ -35,2 +44,4 @@ /** | ||
* | ||
* {@codeblock ~~:client/getNextAccountSequenceNumber.ts#documentation-snippet} | ||
* | ||
* @param accountAddress base58 account address to get the next account nonce for. | ||
@@ -45,2 +56,5 @@ * | ||
* enough data yet. | ||
* | ||
* {@codeblock ~~:client/getCryptographicParameters.ts#documentation-snippet} | ||
* | ||
* @param blockHash optional block hash to get the cryptographic parameters at, otherwise retrieves from last finalized block. | ||
@@ -58,2 +72,4 @@ * @returns the global cryptographic parameters at the given block, or undefined it the block does not exist. | ||
* | ||
* {@codeblock ~~:client/getAccountInfo.ts#documentation-snippet} | ||
* | ||
* @param accountIdentifier base58 account address, or a credential registration id or account index to get the account info for | ||
@@ -69,2 +85,4 @@ * @param blockHash optional block hash to get the account info at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getBlockItemStatus.ts#documentation-snippet} | ||
* | ||
* @param transactionHash the transaction/block item to get a status for. | ||
@@ -79,2 +97,4 @@ * | ||
* enough data yet. | ||
* | ||
* {@codeblock ~~:client/getConsensusStatus.ts#documentation-snippet} | ||
*/ | ||
@@ -85,2 +105,4 @@ getConsensusStatus(): Promise<v1.ConsensusStatus>; | ||
* | ||
* {@codeblock ~~:client/getModuleSource.ts#documentation-snippet} | ||
* | ||
* @param moduleRef the module's reference, represented by the ModuleReference class. | ||
@@ -96,2 +118,4 @@ * @param blockHash optional block hash to get the module source at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getEmbeddedSchema.ts#documentation-snippet} | ||
* | ||
* @param moduleRef the module's reference, represented by the ModuleReference class. | ||
@@ -107,2 +131,4 @@ * @param blockHash optional block hash to get the module embedded schema at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getInstanceInfo.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the address of the smart contract. | ||
@@ -118,2 +144,4 @@ * @param blockHash optional block hash to get the smart contact instances at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/invokeContract.ts#documentation-snippet} | ||
* | ||
* @param context.contract The address of the smart contract that shall be evoked. | ||
@@ -142,2 +170,5 @@ * @param context.amount The amount of microCCD to invoke the contract with. | ||
* To keep track of the transaction use getTransactionStatus. | ||
* | ||
* {@codeblock ~~:common/simpleTransfer.ts#documentation-snippet} | ||
* | ||
* @param transaction the transaction to send to the node | ||
@@ -154,2 +185,5 @@ * @param signature the signatures on the signing digest of the transaction | ||
* To keep track of the transaction use getTransactionStatus. | ||
* | ||
* See [this](git:docs/account-creation.md) document for how this function can be used. | ||
* | ||
* @param credentialDeploymentTransaction the credential deployment transaction to send to the node | ||
@@ -162,2 +196,5 @@ * @param signatures the signatures on the hash of the serialized unsigned credential deployment information, in order | ||
* Retrieves the status of the block chain parameters at the given blockHash. | ||
* | ||
* {@codeblock ~~:client/getBlockChainParameters.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -169,2 +206,5 @@ * @returns Info on all of the block chain parameters. | ||
* Retrieves information on the baker pool of the given bakerId. | ||
* | ||
* {@codeblock ~~:client/getPoolInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -177,2 +217,5 @@ * @param bakerId the ID of the baker to get the status for. | ||
* Retrieves information on the passive delegators. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegationInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -184,2 +227,5 @@ * @returns The status of the passive delegators. | ||
* Retrieves the reward status at the given blockHash | ||
* | ||
* {@codeblock ~~:client/getTokenomicsInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash optional block hash to get the reward status at, otherwise retrieves from last finalized block | ||
@@ -192,2 +238,4 @@ * @returns the reward status at the given block, or undefined it the block does not exist. | ||
* | ||
* {@codeblock ~~:client/getFinalizedBlocks.ts#documentation-snippet} | ||
* | ||
* @param abortSignal an AbortSignal to close the stream. Note that the | ||
@@ -203,2 +251,4 @@ * stream does not close itself as it is infinite, so usually you'd want | ||
* | ||
* {@codeblock ~~:client/getBlocks.ts#documentation-snippet} | ||
* | ||
* @param abortSignal an AbortSignal to close the stream. Note that the | ||
@@ -213,2 +263,4 @@ * stream does not close itself as it is infinite, so usually you'd want | ||
* | ||
* {@codeblock ~~:common/simpleTransfer.ts#documentation-snippet} | ||
* | ||
* @param transactionHash a transaction hash as a bytearray. | ||
@@ -222,2 +274,4 @@ * @param timeoutTime the number of milliseconds until the function throws error. | ||
* | ||
* {@codeblock ~~:client/getAccountList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the accounts at, otherwise retrieves from last finalized block. | ||
@@ -233,2 +287,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getModuleList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the contract modules at, otherwise retrieves from last finalized block. | ||
@@ -244,2 +300,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getAncestors.ts#documentation-snippet} | ||
* | ||
* @param maxAmountOfAncestors the maximum amount of ancestors as a bigint. | ||
@@ -255,2 +313,4 @@ * @param blockHash a optional block hash to get the ancestors at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getInstanceState.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the contract to get the state of. | ||
@@ -267,2 +327,4 @@ * @param blockHash a optional block hash to get the instance states at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/instanceStateLookup.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the contract to get the state of. | ||
@@ -279,2 +341,4 @@ * @param key the key of the desired contract state. | ||
* | ||
* {@codeblock ~~:client/getIdentityProviders.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the providers at, otherwise retrieves from last finalized block. | ||
@@ -290,2 +354,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getAnonymityRevokers.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the anonymity revokers at, otherwise retrieves from last finalized block. | ||
@@ -299,2 +365,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlocksAtHeightAbsolute.ts#documentation-snippet} | ||
* | ||
* @param blockHeightRequest Either an absolute block height request or a relative block height request | ||
@@ -307,2 +375,4 @@ * @returns A list of block hashes as hex strings | ||
* | ||
* {@codeblock ~~:client/getBlockInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the info from, otherwise retrieves from last finalized block. | ||
@@ -315,2 +385,4 @@ * @returns information on a block. | ||
* | ||
* {@codeblock ~~:client/getBakerList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the baker list at, otherwise retrieves from last finalized block. | ||
@@ -329,2 +401,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getPoolDelegators.ts#documentation-snippet} | ||
* | ||
* @param baker The BakerId of the pool owner | ||
@@ -343,2 +417,4 @@ * @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getPoolDelegatorsRewardPeriod.ts#documentation-snippet} | ||
* | ||
* @param baker The BakerId of the pool owner | ||
@@ -358,2 +434,4 @@ * @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegators.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
@@ -371,2 +449,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegatorsRewardPeriod.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
@@ -380,2 +460,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBranches.ts#documentation-snippet} | ||
* | ||
* @returns a branch with a block hash and a list of branch-children | ||
@@ -397,2 +479,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getAccountNonFinalizedTransactions.ts#documentation-snippet} | ||
* | ||
* @param accountAddress The address of the account that you wish to query. | ||
@@ -406,2 +490,4 @@ * @returns a stream of transaction hashes as hex strings. | ||
* | ||
* {@codeblock ~~:client/getBlockTransactionEvents.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the transaction events at, otherwise retrieves from last finalized block. | ||
@@ -415,2 +501,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getNextUpdateSequenceNumbers.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the sequence numbers at, otherwise retrieves from last finalized block. | ||
@@ -423,2 +511,4 @@ * @return a NextUpdateSequenceNumbers object | ||
* Return a GRPC error if the shutdown failed. | ||
* | ||
* {@codeblock ~~:client/shutdown.ts#documentation-snippet} | ||
*/ | ||
@@ -434,2 +524,4 @@ shutdown(): Promise<void>; | ||
* | ||
* {@codeblock ~~:client/peerConnect.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address to connect to. Must be a valid ip address. | ||
@@ -444,2 +536,4 @@ * @param port The port to connect to. Must be between 0 and 65535. | ||
* | ||
* {@codeblock ~~:client/peerDisconnect.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address to connect to. Must be a valid ip address. | ||
@@ -452,2 +546,4 @@ * @param port The port to connect to. Must be between 0 and 65535. | ||
* | ||
* {@codeblock ~~:client/getBannedPeers.ts#documentation-snippet} | ||
* | ||
* @return A list of the ip's of banned peers. | ||
@@ -460,2 +556,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/banPeer.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address of the peer to ban. Must be a valid ip address. | ||
@@ -468,2 +566,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/unbanPeer.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address of the peer to unban. Must be a valid ip address. | ||
@@ -477,2 +577,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/dumpStart.ts#documentation-snippet} | ||
* | ||
* @param filePath Which file to dump the packages into. Requires a valid path. | ||
@@ -486,2 +588,4 @@ * @param raw Whether the node should dump raw packages. | ||
* Rejects if the network dump failed to be stopped. | ||
* | ||
* {@codeblock ~~:client/dumpStop.ts#documentation-snippet} | ||
*/ | ||
@@ -498,2 +602,4 @@ dumpStop(): Promise<void>; | ||
* | ||
* {@codeblock ~~:client/getNodeInfo.ts#documentation-snippet} | ||
* | ||
* @returns Info about the node | ||
@@ -506,2 +612,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getPeersInfo.ts#documentation-snippet} | ||
* | ||
* @returns a list containing info on each peer of the node. | ||
@@ -516,2 +624,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getBlockSpecialEvents.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the special events at, otherwise retrieves from last finalized block. | ||
@@ -526,2 +636,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlockPendingUpdates.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the pending updates at, otherwise retrieves from last finalized block. | ||
@@ -535,2 +647,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlockFinalizationSummary.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the finalization summaries at, otherwise retrieves from last finalized block. | ||
@@ -592,4 +706,13 @@ * @returns a finalization summary | ||
} | ||
/** | ||
* @hidden | ||
*/ | ||
export declare function getBlockHashInput(blockHash?: HexString): v2.BlockHashInput; | ||
/** | ||
* @hidden | ||
*/ | ||
export declare function getAccountIdentifierInput(accountIdentifier: v1.AccountIdentifierInput): v2.AccountIdentifierInput; | ||
/** | ||
* @hidden | ||
*/ | ||
export declare function getInvokerInput(invoker?: AccountAddress | v1.ContractAddress): v2.Address | undefined; |
@@ -26,3 +26,9 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getInvokerInput = exports.getAccountIdentifierInput = exports.getBlockHashInput = void 0; | ||
exports.getInvokerInput = exports.getAccountIdentifierInput = exports.getBlockHashInput = exports.ConcordiumGRPCClient = void 0; | ||
/** | ||
* This is the GRPC-Client used by both the Web-SDK and the NodeJS-SDK. Check | ||
* out the {@link ConcordiumGRPCClient} | ||
* | ||
* @module Common GRPC-Client | ||
*/ | ||
const buffer_1 = require("buffer/"); | ||
@@ -42,6 +48,6 @@ const v2 = __importStar(require("../grpc/v2/concordium/types")); | ||
* @example | ||
* import ConcordiumNodeClient from "..." | ||
* const client = new ConcordiumNodeClient('127.0.0.1', 20000, credentials, metadata, 15000); | ||
* import { ConcordiumGRPCClient } from "..." | ||
* const client = new ConcordiumGRPCClient('127.0.0.1', 20000, credentials, metadata, 15000); | ||
*/ | ||
class ConcordiumNodeClient { | ||
class ConcordiumGRPCClient { | ||
/** | ||
@@ -58,2 +64,4 @@ * Initialize a gRPC client for a specific concordium node. | ||
* | ||
* {@codeblock ~~:client/getNextAccountSequenceNumber.ts#documentation-snippet} | ||
* | ||
* @param accountAddress base58 account address to get the next account nonce for. | ||
@@ -75,2 +83,5 @@ * | ||
* enough data yet. | ||
* | ||
* {@codeblock ~~:client/getCryptographicParameters.ts#documentation-snippet} | ||
* | ||
* @param blockHash optional block hash to get the cryptographic parameters at, otherwise retrieves from last finalized block. | ||
@@ -92,2 +103,4 @@ * @returns the global cryptographic parameters at the given block, or undefined it the block does not exist. | ||
* | ||
* {@codeblock ~~:client/getAccountInfo.ts#documentation-snippet} | ||
* | ||
* @param accountIdentifier base58 account address, or a credential registration id or account index to get the account info for | ||
@@ -111,2 +124,4 @@ * @param blockHash optional block hash to get the account info at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getBlockItemStatus.ts#documentation-snippet} | ||
* | ||
* @param transactionHash the transaction/block item to get a status for. | ||
@@ -129,2 +144,4 @@ * | ||
* enough data yet. | ||
* | ||
* {@codeblock ~~:client/getConsensusStatus.ts#documentation-snippet} | ||
*/ | ||
@@ -138,2 +155,4 @@ async getConsensusStatus() { | ||
* | ||
* {@codeblock ~~:client/getModuleSource.ts#documentation-snippet} | ||
* | ||
* @param moduleRef the module's reference, represented by the ModuleReference class. | ||
@@ -171,2 +190,4 @@ * @param blockHash optional block hash to get the module source at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getEmbeddedSchema.ts#documentation-snippet} | ||
* | ||
* @param moduleRef the module's reference, represented by the ModuleReference class. | ||
@@ -185,2 +206,4 @@ * @param blockHash optional block hash to get the module embedded schema at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/getInstanceInfo.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the address of the smart contract. | ||
@@ -204,2 +227,4 @@ * @param blockHash optional block hash to get the smart contact instances at, otherwise retrieves from last finalized block | ||
* | ||
* {@codeblock ~~:client/invokeContract.ts#documentation-snippet} | ||
* | ||
* @param context.contract The address of the smart contract that shall be evoked. | ||
@@ -242,2 +267,5 @@ * @param context.amount The amount of microCCD to invoke the contract with. | ||
* To keep track of the transaction use getTransactionStatus. | ||
* | ||
* {@codeblock ~~:common/simpleTransfer.ts#documentation-snippet} | ||
* | ||
* @param transaction the transaction to send to the node | ||
@@ -284,2 +312,5 @@ * @param signature the signatures on the signing digest of the transaction | ||
* To keep track of the transaction use getTransactionStatus. | ||
* | ||
* See [this](git:docs/account-creation.md) document for how this function can be used. | ||
* | ||
* @param credentialDeploymentTransaction the credential deployment transaction to send to the node | ||
@@ -313,2 +344,5 @@ * @param signatures the signatures on the hash of the serialized unsigned credential deployment information, in order | ||
* Retrieves the status of the block chain parameters at the given blockHash. | ||
* | ||
* {@codeblock ~~:client/getBlockChainParameters.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -324,2 +358,5 @@ * @returns Info on all of the block chain parameters. | ||
* Retrieves information on the baker pool of the given bakerId. | ||
* | ||
* {@codeblock ~~:client/getPoolInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -341,2 +378,5 @@ * @param bakerId the ID of the baker to get the status for. | ||
* Retrieves information on the passive delegators. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegationInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash the block hash of the block to get the information from. | ||
@@ -353,2 +393,5 @@ * @returns The status of the passive delegators. | ||
* Retrieves the reward status at the given blockHash | ||
* | ||
* {@codeblock ~~:client/getTokenomicsInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash optional block hash to get the reward status at, otherwise retrieves from last finalized block | ||
@@ -366,2 +409,4 @@ * @returns the reward status at the given block, or undefined it the block does not exist. | ||
* | ||
* {@codeblock ~~:client/getFinalizedBlocks.ts#documentation-snippet} | ||
* | ||
* @param abortSignal an AbortSignal to close the stream. Note that the | ||
@@ -381,2 +426,4 @@ * stream does not close itself as it is infinite, so usually you'd want | ||
* | ||
* {@codeblock ~~:client/getBlocks.ts#documentation-snippet} | ||
* | ||
* @param abortSignal an AbortSignal to close the stream. Note that the | ||
@@ -395,2 +442,4 @@ * stream does not close itself as it is infinite, so usually you'd want | ||
* | ||
* {@codeblock ~~:common/simpleTransfer.ts#documentation-snippet} | ||
* | ||
* @param transactionHash a transaction hash as a bytearray. | ||
@@ -439,2 +488,4 @@ * @param timeoutTime the number of milliseconds until the function throws error. | ||
* | ||
* {@codeblock ~~:client/getAccountList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the accounts at, otherwise retrieves from last finalized block. | ||
@@ -455,2 +506,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getModuleList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the contract modules at, otherwise retrieves from last finalized block. | ||
@@ -471,2 +524,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getAncestors.ts#documentation-snippet} | ||
* | ||
* @param maxAmountOfAncestors the maximum amount of ancestors as a bigint. | ||
@@ -490,2 +545,4 @@ * @param blockHash a optional block hash to get the ancestors at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getInstanceState.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the contract to get the state of. | ||
@@ -510,2 +567,4 @@ * @param blockHash a optional block hash to get the instance states at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/instanceStateLookup.ts#documentation-snippet} | ||
* | ||
* @param contractAddress the contract to get the state of. | ||
@@ -532,2 +591,4 @@ * @param key the key of the desired contract state. | ||
* | ||
* {@codeblock ~~:client/getIdentityProviders.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the providers at, otherwise retrieves from last finalized block. | ||
@@ -548,2 +609,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getAnonymityRevokers.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the anonymity revokers at, otherwise retrieves from last finalized block. | ||
@@ -562,2 +625,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlocksAtHeightAbsolute.ts#documentation-snippet} | ||
* | ||
* @param blockHeightRequest Either an absolute block height request or a relative block height request | ||
@@ -574,2 +639,4 @@ * @returns A list of block hashes as hex strings | ||
* | ||
* {@codeblock ~~:client/getBlockInfo.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the info from, otherwise retrieves from last finalized block. | ||
@@ -586,2 +653,4 @@ * @returns information on a block. | ||
* | ||
* {@codeblock ~~:client/getBakerList.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the baker list at, otherwise retrieves from last finalized block. | ||
@@ -605,2 +674,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getPoolDelegators.ts#documentation-snippet} | ||
* | ||
* @param baker The BakerId of the pool owner | ||
@@ -628,2 +699,4 @@ * @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getPoolDelegatorsRewardPeriod.ts#documentation-snippet} | ||
* | ||
* @param baker The BakerId of the pool owner | ||
@@ -650,2 +723,4 @@ * @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegators.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
@@ -666,2 +741,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getPassiveDelegatorsRewardPeriod.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the delegators at, otherwise retrieves from last finalized block. | ||
@@ -678,2 +755,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBranches.ts#documentation-snippet} | ||
* | ||
* @returns a branch with a block hash and a list of branch-children | ||
@@ -703,2 +782,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getAccountNonFinalizedTransactions.ts#documentation-snippet} | ||
* | ||
* @param accountAddress The address of the account that you wish to query. | ||
@@ -715,2 +796,4 @@ * @returns a stream of transaction hashes as hex strings. | ||
* | ||
* {@codeblock ~~:client/getBlockTransactionEvents.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the transaction events at, otherwise retrieves from last finalized block. | ||
@@ -727,2 +810,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getNextUpdateSequenceNumbers.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the sequence numbers at, otherwise retrieves from last finalized block. | ||
@@ -738,2 +823,4 @@ * @return a NextUpdateSequenceNumbers object | ||
* Return a GRPC error if the shutdown failed. | ||
* | ||
* {@codeblock ~~:client/shutdown.ts#documentation-snippet} | ||
*/ | ||
@@ -751,2 +838,4 @@ async shutdown() { | ||
* | ||
* {@codeblock ~~:client/peerConnect.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address to connect to. Must be a valid ip address. | ||
@@ -769,2 +858,4 @@ * @param port The port to connect to. Must be between 0 and 65535. | ||
* | ||
* {@codeblock ~~:client/peerDisconnect.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address to connect to. Must be a valid ip address. | ||
@@ -785,2 +876,4 @@ * @param port The port to connect to. Must be between 0 and 65535. | ||
* | ||
* {@codeblock ~~:client/getBannedPeers.ts#documentation-snippet} | ||
* | ||
* @return A list of the ip's of banned peers. | ||
@@ -796,2 +889,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/banPeer.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address of the peer to ban. Must be a valid ip address. | ||
@@ -810,2 +905,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/unbanPeer.ts#documentation-snippet} | ||
* | ||
* @param ip The ip address of the peer to unban. Must be a valid ip address. | ||
@@ -825,2 +922,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/dumpStart.ts#documentation-snippet} | ||
* | ||
* @param filePath Which file to dump the packages into. Requires a valid path. | ||
@@ -840,2 +939,4 @@ * @param raw Whether the node should dump raw packages. | ||
* Rejects if the network dump failed to be stopped. | ||
* | ||
* {@codeblock ~~:client/dumpStop.ts#documentation-snippet} | ||
*/ | ||
@@ -854,2 +955,4 @@ async dumpStop() { | ||
* | ||
* {@codeblock ~~:client/getNodeInfo.ts#documentation-snippet} | ||
* | ||
* @returns Info about the node | ||
@@ -865,2 +968,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getPeersInfo.ts#documentation-snippet} | ||
* | ||
* @returns a list containing info on each peer of the node. | ||
@@ -878,2 +983,4 @@ */ | ||
* | ||
* {@codeblock ~~:client/getBlockSpecialEvents.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the special events at, otherwise retrieves from last finalized block. | ||
@@ -891,2 +998,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlockPendingUpdates.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the pending updates at, otherwise retrieves from last finalized block. | ||
@@ -903,2 +1012,4 @@ * @param abortSignal an optional AbortSignal to close the stream. | ||
* | ||
* {@codeblock ~~:client/getBlockFinalizationSummary.ts#documentation-snippet} | ||
* | ||
* @param blockHash an optional block hash to get the finalization summaries at, otherwise retrieves from last finalized block. | ||
@@ -1056,3 +1167,6 @@ * @returns a finalization summary | ||
} | ||
exports.default = ConcordiumNodeClient; | ||
exports.ConcordiumGRPCClient = ConcordiumGRPCClient; | ||
/** | ||
* @hidden | ||
*/ | ||
function getBlockHashInput(blockHash) { | ||
@@ -1077,2 +1191,5 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
exports.getBlockHashInput = getBlockHashInput; | ||
/** | ||
* @hidden | ||
*/ | ||
function getAccountIdentifierInput(accountIdentifier) { | ||
@@ -1099,2 +1216,5 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
exports.getAccountIdentifierInput = getAccountIdentifierInput; | ||
/** | ||
* @hidden | ||
*/ | ||
function getInvokerInput(invoker) { | ||
@@ -1101,0 +1221,0 @@ if (!invoker) { |
@@ -17,2 +17,3 @@ import { sha256 } from './hash'; | ||
export * from './signHelpers'; | ||
export * from './versionedTypeHelpers'; | ||
export * from './accountHelpers'; | ||
@@ -28,3 +29,3 @@ export * from './blockSummaryHelpers'; | ||
export * from './identity'; | ||
export { default as ConcordiumGRPCClient } from './GRPCClient'; | ||
export { ConcordiumGRPCClient } from './GRPCClient'; | ||
export { getAccountTransactionHandler } from './accountTransactions'; | ||
@@ -31,0 +32,0 @@ export * from './energyCost'; |
@@ -16,5 +16,2 @@ "use strict"; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -65,2 +62,3 @@ exports.getAccountTransactionHandler = exports.ConcordiumGRPCClient = exports.JsonRpcClient = exports.HttpProvider = exports.unwrap = exports.wasmToSchema = exports.streamToList = exports.isHex = exports.getContractName = exports.deserializeTypeValue = exports.deserializeInitError = exports.deserializeReceiveError = exports.deserializeReceiveReturnValue = exports.deserializeTransaction = exports.deserializeContractState = exports.getAlias = exports.isAlias = exports.ModuleReference = exports.DataBlob = exports.TransactionExpiry = exports.CcdAmount = exports.AccountAddress = exports.CredentialRegistrationId = exports.sha256 = exports.serializeCredentialDeploymentPayload = exports.serializeAccountTransactionPayload = exports.serializeTypeValue = exports.getSignedCredentialDeploymentTransactionHash = exports.serializeCredentialDeploymentTransactionForSubmission = exports.serializeAccountTransactionForSubmission = exports.serializeUpdateContractParameters = exports.serializeInitContractParameters = exports.getCredentialForExistingAccountSignDigest = exports.getCredentialDeploymentTransactionHash = exports.getCredentialDeploymentSignDigest = exports.getAccountTransactionSignDigest = exports.getAccountTransactionHash = void 0; | ||
__exportStar(require("./signHelpers"), exports); | ||
__exportStar(require("./versionedTypeHelpers"), exports); | ||
__exportStar(require("./accountHelpers"), exports); | ||
@@ -84,3 +82,3 @@ __exportStar(require("./blockSummaryHelpers"), exports); | ||
var GRPCClient_1 = require("./GRPCClient"); | ||
Object.defineProperty(exports, "ConcordiumGRPCClient", { enumerable: true, get: function () { return __importDefault(GRPCClient_1).default; } }); | ||
Object.defineProperty(exports, "ConcordiumGRPCClient", { enumerable: true, get: function () { return GRPCClient_1.ConcordiumGRPCClient; } }); | ||
var accountTransactions_1 = require("./accountTransactions"); | ||
@@ -87,0 +85,0 @@ Object.defineProperty(exports, "getAccountTransactionHandler", { enumerable: true, get: function () { return accountTransactions_1.getAccountTransactionHandler; } }); |
@@ -8,3 +8,3 @@ import { Buffer } from 'buffer/'; | ||
/** | ||
* @deprecated This has been deprecated in favor of the {@link ConcordiumNodeClient} that uses version 2 of the concordium gRPC API | ||
* @deprecated This has been deprecated in favor of the {@link ConcordiumGRPCClient} that uses version 2 of the concordium gRPC API | ||
*/ | ||
@@ -11,0 +11,0 @@ export declare class JsonRpcClient { |
@@ -19,3 +19,3 @@ "use strict"; | ||
/** | ||
* @deprecated This has been deprecated in favor of the {@link ConcordiumNodeClient} that uses version 2 of the concordium gRPC API | ||
* @deprecated This has been deprecated in favor of the {@link ConcordiumGRPCClient} that uses version 2 of the concordium gRPC API | ||
*/ | ||
@@ -73,2 +73,4 @@ class JsonRpcClient { | ||
'lastFinalizedTime', | ||
// v1 | ||
'triggerBlockTime', | ||
]; | ||
@@ -84,2 +86,6 @@ const bigIntPropertyKeys = [ | ||
'protocolVersion', | ||
// v1 | ||
'currentTimeoutDuration', | ||
'currentRound', | ||
'currentEpoch', | ||
]; | ||
@@ -86,0 +92,0 @@ const res = transformJsonResponse(response, (0, util_1.buildJsonResponseReviver)(datePropertyKeys, bigIntPropertyKeys), (0, util_1.intToStringTransformer)(bigIntPropertyKeys)); |
@@ -88,5 +88,6 @@ import { Buffer } from 'buffer/'; | ||
* @param schemaVersion the version of the schema provided | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of init contract parameters | ||
*/ | ||
export declare function serializeInitContractParameters(contractName: string, parameters: any, rawSchema: Buffer, schemaVersion?: SchemaVersion): Buffer; | ||
export declare function serializeInitContractParameters(contractName: string, parameters: any, rawSchema: Buffer, schemaVersion?: SchemaVersion, verboseErrorMessage?: boolean): Buffer; | ||
/** | ||
@@ -98,5 +99,6 @@ * @param contractName name of the contract that the update contract transaction will update | ||
* @param schemaVersion the version of the schema provided | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of update contract parameters | ||
*/ | ||
export declare function serializeUpdateContractParameters(contractName: string, receiveFunctionName: string, parameters: any, rawSchema: Buffer, schemaVersion?: SchemaVersion): Buffer; | ||
export declare function serializeUpdateContractParameters(contractName: string, receiveFunctionName: string, parameters: any, rawSchema: Buffer, schemaVersion?: SchemaVersion, verboseErrorMessage?: boolean): Buffer; | ||
/** | ||
@@ -106,5 +108,6 @@ * Given a value for a smart contract type, and the raw schema for that type, serialize the value into binary format. | ||
* @param rawSchema the schema for the type that the given value should be serialized as | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of the value | ||
*/ | ||
export declare function serializeTypeValue(value: any, rawSchema: Buffer): Buffer; | ||
export declare function serializeTypeValue(value: any, rawSchema: Buffer, verboseErrorMessage?: boolean): Buffer; | ||
/** | ||
@@ -111,0 +114,0 @@ * @deprecated the SignedCredentialDeploymentDetails is only used with JSON-RPC |
@@ -301,2 +301,3 @@ "use strict"; | ||
* @param schemaVersion the version of the schema provided | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of init contract parameters | ||
@@ -306,4 +307,4 @@ */ | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types | ||
parameters, rawSchema, schemaVersion) { | ||
const serializedParameters = wasm.serializeInitContractParameters(JSON.stringify(parameters), rawSchema.toString('hex'), contractName, schemaVersion); | ||
parameters, rawSchema, schemaVersion, verboseErrorMessage = false) { | ||
const serializedParameters = wasm.serializeInitContractParameters(JSON.stringify(parameters), rawSchema.toString('hex'), contractName, schemaVersion, verboseErrorMessage); | ||
return buffer_1.Buffer.from(serializedParameters, 'hex'); | ||
@@ -318,2 +319,3 @@ } | ||
* @param schemaVersion the version of the schema provided | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of update contract parameters | ||
@@ -323,4 +325,4 @@ */ | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types | ||
parameters, rawSchema, schemaVersion) { | ||
const serializedParameters = wasm.serializeReceiveContractParameters(JSON.stringify(parameters), rawSchema.toString('hex'), contractName, receiveFunctionName, schemaVersion); | ||
parameters, rawSchema, schemaVersion, verboseErrorMessage = false) { | ||
const serializedParameters = wasm.serializeReceiveContractParameters(JSON.stringify(parameters), rawSchema.toString('hex'), contractName, receiveFunctionName, schemaVersion, verboseErrorMessage); | ||
return buffer_1.Buffer.from(serializedParameters, 'hex'); | ||
@@ -333,2 +335,3 @@ } | ||
* @param rawSchema the schema for the type that the given value should be serialized as | ||
* @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`. | ||
* @returns serialized buffer of the value | ||
@@ -338,4 +341,4 @@ */ | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types | ||
value, rawSchema) { | ||
const serializedValue = wasm.serializeTypeValue(JSON.stringify(value), rawSchema.toString('hex')); | ||
value, rawSchema, verboseErrorMessage = false) { | ||
const serializedValue = wasm.serializeTypeValue(JSON.stringify(value), rawSchema.toString('hex'), verboseErrorMessage); | ||
return buffer_1.Buffer.from(serializedValue, 'hex'); | ||
@@ -342,0 +345,0 @@ } |
@@ -0,1 +1,4 @@ | ||
/** | ||
* @module Common GRPC-Client | ||
*/ | ||
import { AccountAddress } from './types/accountAddress'; | ||
@@ -24,5 +27,12 @@ import { CredentialRegistrationId } from './types/CredentialRegistrationId'; | ||
export declare type IpAddressString = string; | ||
export declare type JsonString = string; | ||
export declare type ModuleRef = HexString; | ||
/** A number of milliseconds */ | ||
export declare type Duration = bigint; | ||
/** Unix timestamp in milliseconds */ | ||
export declare type Timestamp = bigint; | ||
/** A consensus round */ | ||
export declare type Round = bigint; | ||
/** An amount of energy */ | ||
export declare type Energy = bigint; | ||
/** | ||
@@ -216,74 +226,163 @@ * Returns a union of all keys of type T with values matching type V. | ||
export declare type MintDistribution = MintDistributionV0 | MintDistributionV1; | ||
export interface GasRewards { | ||
/** Common gas rewards properties across all protocol versions */ | ||
export interface GasRewardsCommon { | ||
/** The fractional amount paid to the baker */ | ||
baker: number; | ||
finalizationProof: number; | ||
/** The fractional amount paid for an account creation */ | ||
accountCreation: number; | ||
/** The fractional amount paid for a chain update */ | ||
chainUpdate: number; | ||
} | ||
/** Gas rewards properties for protocol version 1-5 ({@link ChainParametersV0} and {@link ChainParametersV1}). */ | ||
export interface GasRewardsV0 extends GasRewardsCommon { | ||
/** The fractional amount paid for including a finalization proof */ | ||
finalizationProof: number; | ||
} | ||
/** Gas rewards properties from protocol version 6 ({@link ChainParametersV2}). */ | ||
export declare type GasRewardsV1 = GasRewardsCommon; | ||
/** Common reward parameters used across all protocol versions */ | ||
export interface RewardParametersCommon { | ||
/** The current transaction fee distribution */ | ||
transactionFeeDistribution: TransactionFeeDistribution; | ||
gASRewards: GasRewards; | ||
} | ||
/** | ||
* Used from protocol version 1-3 | ||
*/ | ||
/** Reward parameters used from protocol version 1-3 ({@link ChainParametersV0}). */ | ||
export interface RewardParametersV0 extends RewardParametersCommon { | ||
/** The current mint distribution */ | ||
mintDistribution: MintDistributionV0; | ||
/** The current gas rewards parameters */ | ||
gASRewards: GasRewardsV0; | ||
} | ||
/** | ||
* Used from protocol version 4 | ||
*/ | ||
/** Reward parameters used in protocol versions 4 and 5 ({@link ChainParametersV1}). */ | ||
export interface RewardParametersV1 extends RewardParametersCommon { | ||
/** The current mint distribution */ | ||
mintDistribution: MintDistributionV1; | ||
/** The current gas rewards parameters */ | ||
gASRewards: GasRewardsV0; | ||
} | ||
export declare type RewardParameters = RewardParametersV0 | RewardParametersV1; | ||
/** Reward parameters used from protocol version 6 ({@link ChainParametersV2}). */ | ||
export interface RewardParametersV2 extends RewardParametersCommon { | ||
/** The current mint distribution */ | ||
mintDistribution: MintDistributionV1; | ||
/** The current gas rewards parameters */ | ||
gASRewards: GasRewardsV1; | ||
} | ||
/** Cooldown parameters used from protocol version 1-3 */ | ||
export interface CooldownParametersV0 { | ||
/** The baker cooldown period in {@link Epoch} epochs */ | ||
bakerCooldownEpochs: Epoch; | ||
} | ||
/** Cooldown parameters used from protocol version 4 */ | ||
export interface CooldownParametersV1 { | ||
/** The pool owner (baker) cooldown period in seconds */ | ||
poolOwnerCooldown: DurationSeconds; | ||
/** The delegator cooldown period in seconds */ | ||
delegatorCooldown: DurationSeconds; | ||
} | ||
/** Pool parameters used from protocol version 1-3 */ | ||
export interface PoolParametersV0 { | ||
/** The minimum threshold to stake to become a baker. */ | ||
minimumThresholdForBaking: Amount; | ||
} | ||
/** Pool parameters used from protocol version 4 */ | ||
export interface PoolParametersV1 { | ||
/** Fraction of finalization rewards charged by the passive delegation. */ | ||
passiveFinalizationCommission: number; | ||
/** Fraction of baking rewards charged by the passive delegation.*/ | ||
passiveBakingCommission: number; | ||
passiveTransactionCommission: number; | ||
/** Fraction of finalization rewards charged by the pool owner. */ | ||
finalizationCommissionRange: InclusiveRange<number>; | ||
/** Fraction of baking rewards charged by the pool owner. */ | ||
bakingCommissionRange: InclusiveRange<number>; | ||
/** Fraction of transaction rewards charged by the pool owner. */ | ||
transactionCommissionRange: InclusiveRange<number>; | ||
/** Minimum equity capital required for a new baker.*/ | ||
minimumEquityCapital: Amount; | ||
/** | ||
* Maximum fraction of the total staked capital of that a new baker can | ||
* have. | ||
*/ | ||
capitalBound: number; | ||
/** | ||
* The maximum leverage that a baker can have as a ratio of total stake | ||
* to equity capital. | ||
*/ | ||
leverageBound: Ratio; | ||
} | ||
/** | ||
* Time parameters used from protocol version 4 | ||
* These consist of the reward period length and the mint rate per payday. These are coupled as | ||
* a change to either affects the overall rate of minting. | ||
*/ | ||
export interface TimeParametersV1 { | ||
/** | ||
* In epochs | ||
*/ | ||
/** The length of a reward period, in {@link Epoch} epochs. */ | ||
rewardPeriodLength: Epoch; | ||
/** The rate at which CCD is minted per payday. */ | ||
mintPerPayday: number; | ||
} | ||
/** Parameters that determine timeouts in the consensus protocol used from protocol version 6. */ | ||
export interface TimeoutParameters { | ||
/** The base value for triggering a timeout, in milliseconds. */ | ||
timeoutBase: Duration; | ||
/** Factor for increasing the timeout. Must be greater than 1. */ | ||
timeoutIncrease: Ratio; | ||
/** Factor for decreasing the timeout. Must be between 0 and 1. */ | ||
timeoutDecrease: Ratio; | ||
} | ||
/** Consensus parameters, used from protocol version 6 */ | ||
export interface ConsensusParameters { | ||
/** Minimum time interval between blocks. */ | ||
minBlockTime: Duration; | ||
/** Maximum energy allowed per block. */ | ||
blockEnergyLimit: Energy; | ||
} | ||
/** | ||
* Finalization committee parameters, used from protocol version 6 | ||
*/ | ||
export interface FinalizationCommitteeParameters { | ||
/** The minimum size of a finalization committee before `finalizerRelativeStakeThreshold` takes effect. */ | ||
minimumFinalizers: number; | ||
/** The maximum size of a finalization committee. */ | ||
maximumFinalizers: number; | ||
/** | ||
* The threshold for determining the stake required for being eligible the finalization committee. | ||
* The amount is given by `total stake in pools * finalizerRelativeStakeThreshold`. | ||
* Subsequently, this will alwas be a number between 0 and 1. | ||
*/ | ||
finalizerRelativeStakeThreshold: number; | ||
} | ||
/** Common chain parameters across all protocol versions */ | ||
export interface ChainParametersCommon { | ||
electionDifficulty: number; | ||
/** Rate of euros per energy */ | ||
euroPerEnergy: ExchangeRate; | ||
/** Rate of micro CCD per euro */ | ||
microGTUPerEuro: ExchangeRate; | ||
/** Limit for the number of account creations in a block */ | ||
accountCreationLimit: number; | ||
/** The chain foundation account */ | ||
foundationAccount: Base58String; | ||
/** The chain foundation account index */ | ||
foundationAccountIndex?: bigint; | ||
foundationAccount?: string; | ||
} | ||
/** | ||
* Used from protocol version 1-3 | ||
*/ | ||
export interface ChainParametersV0 extends ChainParametersCommon, CooldownParametersV0, PoolParametersV0 { | ||
/** Chain parameters used from protocol version 1-3 */ | ||
export declare type ChainParametersV0 = ChainParametersCommon & CooldownParametersV0 & PoolParametersV0 & { | ||
/** The election difficulty for consensus lottery */ | ||
electionDifficulty: number; | ||
/** The election difficulty for consensus lottery */ | ||
rewardParameters: RewardParametersV0; | ||
} | ||
/** | ||
* Used from protocol version 4 | ||
*/ | ||
export interface ChainParametersV1 extends ChainParametersCommon, CooldownParametersV1, PoolParametersV1, TimeParametersV1 { | ||
}; | ||
/** Chain parameters used in protocol versions 4 and 5 */ | ||
export declare type ChainParametersV1 = ChainParametersCommon & CooldownParametersV1 & TimeParametersV1 & PoolParametersV1 & { | ||
/** The election difficulty for consensus lottery */ | ||
electionDifficulty: number; | ||
/** The election difficulty for consensus lottery */ | ||
rewardParameters: RewardParametersV1; | ||
} | ||
export declare type ChainParameters = ChainParametersV0 | ChainParametersV1; | ||
}; | ||
/** Chain parameters used from protocol version 6 */ | ||
export declare type ChainParametersV2 = ChainParametersCommon & CooldownParametersV1 & TimeParametersV1 & PoolParametersV1 & FinalizationCommitteeParameters & TimeoutParameters & ConsensusParameters & { | ||
/** The election difficulty for consensus lottery */ | ||
rewardParameters: RewardParametersV2; | ||
}; | ||
/** Union of all chain parameters across all protocol versions */ | ||
export declare type ChainParameters = ChainParametersV0 | ChainParametersV1 | ChainParametersV2; | ||
export interface Authorization { | ||
@@ -306,2 +405,5 @@ threshold: number; | ||
poolParameters: Authorization; | ||
/** | ||
* For protocol version 6 and later, this controls the authorization of consensus related updates. | ||
*/ | ||
electionDifficulty: Authorization; | ||
@@ -352,3 +454,3 @@ addAnonymityRevoker: Authorization; | ||
nextSequenceNumber: bigint; | ||
queue: UpdateQueueQueue; | ||
queue: UpdateQueueQueue[]; | ||
} | ||
@@ -360,3 +462,2 @@ interface UpdateQueuesCommon { | ||
foundationAccount: UpdateQueue; | ||
electionDifficulty: UpdateQueue; | ||
mintDistribution: UpdateQueue; | ||
@@ -375,8 +476,10 @@ protocol: UpdateQueue; | ||
export interface UpdateQueuesV0 extends UpdateQueuesCommon { | ||
electionDifficulty: UpdateQueue; | ||
bakerStakeThreshold: UpdateQueue; | ||
} | ||
/** | ||
* Used from protocol version 4 | ||
* Used in protocol version 4 and 5 | ||
*/ | ||
export interface UpdateQueuesV1 extends UpdateQueuesCommon { | ||
electionDifficulty: UpdateQueue; | ||
cooldownParameters: UpdateQueue; | ||
@@ -386,3 +489,9 @@ timeParameters: UpdateQueue; | ||
} | ||
export declare type UpdateQueues = UpdateQueuesV0 | UpdateQueuesV1; | ||
/** | ||
* Used from protocol version 6 | ||
*/ | ||
export interface UpdateQueuesV2 extends UpdateQueuesV1 { | ||
consensus2TimingParameters: UpdateQueue; | ||
} | ||
export declare type UpdateQueues = UpdateQueuesV0 | UpdateQueuesV1 | UpdateQueuesV2; | ||
interface ProtocolUpdate { | ||
@@ -407,3 +516,3 @@ message: string; | ||
/** | ||
* Used from protocol version 4 | ||
* Used in protocol version 4 and 5 | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
@@ -417,8 +526,17 @@ */ | ||
/** | ||
* Used from protocol version 6 | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
*/ | ||
export declare type Updates = UpdatesV0 | UpdatesV1; | ||
export interface UpdatesV2 extends UpdatesCommon { | ||
chainParameters: ChainParametersV2; | ||
updateQueues: UpdateQueuesV2; | ||
keys: KeysV1; | ||
} | ||
/** | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
*/ | ||
export declare type Updates = UpdatesV0 | UpdatesV1 | UpdatesV2; | ||
/** | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
*/ | ||
interface BlockSummaryCommon { | ||
@@ -437,3 +555,3 @@ protocolVersion?: bigint; | ||
/** | ||
* Used from protocol version 4 | ||
* Used in protocol version 4 and 5 | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
@@ -446,5 +564,13 @@ */ | ||
/** | ||
* Used from protocol version 6 | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
*/ | ||
export declare type BlockSummary = BlockSummaryV0 | BlockSummaryV1; | ||
export interface BlockSummaryV2 extends BlockSummaryCommon { | ||
updates: UpdatesV2; | ||
protocolVersion: bigint; | ||
} | ||
/** | ||
* @deprecated This is type describing return types from the JSON-RPC client and the V1 gRPC client, both of which have been deprecated | ||
*/ | ||
export declare type BlockSummary = BlockSummaryV0 | BlockSummaryV1 | BlockSummaryV2; | ||
interface RewardStatusCommon { | ||
@@ -468,20 +594,57 @@ protocolVersion?: bigint; | ||
export declare type TokenomicsInfo = RewardStatus; | ||
export interface BlockInfo { | ||
/** Common properties for block info across all protocol versions */ | ||
export interface BlockInfoCommon { | ||
/** | ||
* Hash of parent block. For the initial genesis block (i.e. not re-genesis) | ||
* this will be the hash of the block itself | ||
*/ | ||
blockParent: HexString; | ||
/** Hash of block */ | ||
blockHash: HexString; | ||
/** Hash of block state */ | ||
blockStateHash: HexString; | ||
/** Hash of last finalized block when this block was baked */ | ||
blockLastFinalized: HexString; | ||
/** The absolute height of this (i.e. relative to the initial genesis block) */ | ||
blockHeight: bigint; | ||
/** The baker ID of the baker for this block. Not available for a genesis block */ | ||
blockBaker?: BakerId; | ||
blockSlot: bigint; | ||
/** The time the block was verified */ | ||
blockArriveTime: Date; | ||
/** The time the block was received */ | ||
blockReceiveTime: Date; | ||
/** The time of the slot in which the block was baked */ | ||
blockSlotTime: Date; | ||
/** Whether the block is finalized */ | ||
finalized: boolean; | ||
/** The number of transactions in the block */ | ||
transactionCount: bigint; | ||
/** The total byte size of all transactions in the block */ | ||
transactionsSize: bigint; | ||
transactionEnergyCost: bigint; | ||
/** The energy cost of the transactions in the block */ | ||
transactionEnergyCost: Energy; | ||
/** | ||
* The genesis index for the block. This counst the number of protocol updates that have | ||
* preceeded this block, and defines the era of the block. | ||
*/ | ||
genesisIndex: number; | ||
/** The height of this block relative to the (re)genesis block of its era */ | ||
eraBlockHeight: number; | ||
/** The protocol version the block belongs to */ | ||
protocolVersion: bigint; | ||
} | ||
/** Block info used for protocol version 1-5 */ | ||
export interface BlockInfoV0 extends BlockInfoCommon { | ||
/** The slot number in which the block was baked. */ | ||
blockSlot: bigint; | ||
} | ||
/** Block info used from protocol version 6 */ | ||
export interface BlockInfoV1 extends BlockInfoCommon { | ||
/** The block round */ | ||
round: Round; | ||
/** The block epoch */ | ||
epoch: Epoch; | ||
} | ||
/** Union of all block info versions */ | ||
export declare type BlockInfo = BlockInfoV0 | BlockInfoV1; | ||
export interface CommonBlockInfo { | ||
@@ -500,40 +663,92 @@ hash: HexString; | ||
export declare type BlocksAtHeightRequest = AbsoluteBlocksAtHeightRequest | RelativeBlocksAtHeightRequest; | ||
export interface ConsensusStatus { | ||
bestBlock: string; | ||
genesisBlock: string; | ||
currentEraGenesisBlock: string; | ||
lastFinalizedBlock: string; | ||
/** | ||
* In milliseconds | ||
*/ | ||
epochDuration: bigint; | ||
/** | ||
* In milliseconds | ||
*/ | ||
slotDuration: bigint; | ||
/** Common properties for consensus status types used across all protocol versions */ | ||
export interface ConsensusStatusCommon { | ||
/** Hash of the current best block */ | ||
bestBlock: HexString; | ||
/** Hash of the initial genesis block */ | ||
genesisBlock: HexString; | ||
/** Hash of the genesis block of the current era, i.e. since the last protocol update. */ | ||
currentEraGenesisBlock: HexString; | ||
/** Hash of the last finalized block */ | ||
lastFinalizedBlock: HexString; | ||
/** Current epoch duration, in milliseconds */ | ||
epochDuration: Duration; | ||
/** Absolute height of the best block */ | ||
bestBlockHeight: bigint; | ||
/** Absolute height of the last finalized block */ | ||
lastFinalizedBlockHeight: bigint; | ||
/** Number of finalizations */ | ||
finalizationCount: bigint; | ||
/** Total number of blocks received and verified */ | ||
blocksVerifiedCount: bigint; | ||
/** Total number of blocks received */ | ||
blocksReceivedCount: bigint; | ||
/** Exponential moving average latency between a block's slot time and its arrival. */ | ||
blockArriveLatencyEMA: number; | ||
/** Standard deviation of exponential moving average latency between a block's slot time and its arrival. */ | ||
blockArriveLatencyEMSD: number; | ||
/** Exponential moving average latency between a block's slot time and received time. */ | ||
blockReceiveLatencyEMA: number; | ||
/** Standard deviation of exponential moving average latency between a block's slot time and received time. */ | ||
blockReceiveLatencyEMSD: number; | ||
/** Exponential moving average number of transactions per block. */ | ||
transactionsPerBlockEMA: number; | ||
/** Standard deviation of exponential moving average number of transactions per block. */ | ||
transactionsPerBlockEMSD: number; | ||
/** Exponential moving average time between receiving blocks. */ | ||
blockReceivePeriodEMA?: number; | ||
/** Standard deviation of exponential moving average time between receiving blocks. */ | ||
blockReceivePeriodEMSD?: number; | ||
/** Exponential moving average time between block arrivals. */ | ||
blockArrivePeriodEMA?: number; | ||
/** Standard deviation of exponential moving average time between block arrivals. */ | ||
blockArrivePeriodEMSD?: number; | ||
/** Exponential moving average time between finalizations. */ | ||
finalizationPeriodEMA?: number; | ||
/** Standard deviation of exponential moving average time between finalizations. */ | ||
finalizationPeriodEMSD?: number; | ||
/** Time of the (original) genesis block. */ | ||
genesisTime: Date; | ||
/** Time when the current era started. */ | ||
currentEraGenesisTime: Date; | ||
/** The last time a block was received. */ | ||
blockLastReceivedTime?: Date; | ||
/** The last time a block was verified (added to the tree). */ | ||
blockLastArrivedTime?: Date; | ||
/** Time of last verified finalization. */ | ||
lastFinalizedTime?: Date; | ||
/** | ||
* The number of chain restarts via a protocol update. A completed | ||
* protocol update instruction might not change the protocol version | ||
* specified in the previous field, but it always increments the genesis | ||
* index. | ||
*/ | ||
genesisIndex: number; | ||
/** Currently active protocol version. */ | ||
protocolVersion: bigint; | ||
} | ||
/** Consensus status used for protocol version 1-5 */ | ||
export interface ConsensusStatusV0 extends ConsensusStatusCommon { | ||
/** (Current) slot duration in milliseconds */ | ||
slotDuration: Duration; | ||
} | ||
export interface ConcordiumBftStatus { | ||
/** Current duration before a round times out, in milliseconds */ | ||
currentTimeoutDuration: Duration; | ||
/** Current round */ | ||
currentRound: Round; | ||
/** Current epoch */ | ||
currentEpoch: Epoch; | ||
/** | ||
* The first block in the epoch with timestamp at least this is considered to be | ||
* the trigger block for the epoch transition. | ||
*/ | ||
triggerBlockTime: Date; | ||
} | ||
/** Consensus status used from protocol version 6 */ | ||
export declare type ConsensusStatusV1 = ConsensusStatusCommon & { | ||
concordiumBFTStatus: ConcordiumBftStatus; | ||
}; | ||
/** Union of consensus status types used across all protocol versions */ | ||
export declare type ConsensusStatus = ConsensusStatusV0 | ConsensusStatusV1; | ||
export interface CryptographicParameters { | ||
@@ -600,2 +815,7 @@ onChainCommitmentKey: string; | ||
} | ||
/** | ||
* Parses a wallet export file into a WalletExportFormat. The wallet export | ||
* file is exported from a concordium wallet. | ||
*/ | ||
export declare function parseWallet(walletString: JsonString): WalletExportFormat; | ||
export interface ChainArData { | ||
@@ -846,7 +1066,18 @@ encIdCredPubShare: string; | ||
} | ||
export interface ElectionInfo { | ||
electionDifficulty: number; | ||
/** Common properties for election info across all protocol versions */ | ||
export interface ElectionInfoCommon { | ||
electionNonce: HexString; | ||
bakerElectionInfo: BakerElectionInfo[]; | ||
} | ||
/** Election info used for protocol version 1-5 */ | ||
export interface ElectionInfoV0 extends ElectionInfoCommon { | ||
electionDifficulty: number; | ||
} | ||
/** Election info used from protocol version 6 */ | ||
export declare type ElectionInfoV1 = ElectionInfoCommon; | ||
/** | ||
* Union of different versions of election info across all protocol versions. | ||
* Contains information related to baker election for a particular block | ||
*/ | ||
export declare type ElectionInfo = ElectionInfoV0 | ElectionInfoV1; | ||
export interface NextUpdateSequenceNumbers { | ||
@@ -869,2 +1100,6 @@ rootKeys: bigint; | ||
timeParameters: bigint; | ||
timeoutParameters: bigint; | ||
minBlockTime: bigint; | ||
blockEnergyLimit: bigint; | ||
finalizationCommiteeParameters: bigint; | ||
} | ||
@@ -1067,3 +1302,3 @@ export declare type BlockFinalizationSummary = BlockFinalizationSummary_None | BlockFinalizationSummary_Record; | ||
I64 = 9, | ||
/** Token amount in microCCD (10^-6 GTU). */ | ||
/** Token amount in microCCD (10^-6 CCD). */ | ||
Amount = 10, | ||
@@ -1070,0 +1305,0 @@ /** Sender account address. */ |
"use strict"; | ||
/** | ||
* @module Common GRPC-Client | ||
*/ | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
@@ -17,3 +20,3 @@ if (k2 === undefined) k2 = k; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SchemaVersion = exports.ContractVersion = exports.buildInvoker = exports.isInstanceInfoV0 = exports.isInstanceInfoV1 = exports.ParameterType = exports.isAccountTransactionType = exports.AccountTransactionType = exports.BlockItemKind = exports.DelegationTargetType = exports.PoolStatusType = exports.BakerPoolPendingChangeType = exports.OpenStatusText = exports.OpenStatus = exports.StakePendingChangeType = exports.instanceOfTransferWithMemoTransactionSummary = exports.TransactionSummaryType = exports.TransactionStatusEnum = exports.IdDocType = exports.Sex = exports.AttributeKeyString = exports.AttributesKeys = void 0; | ||
exports.SchemaVersion = exports.ContractVersion = exports.buildInvoker = exports.isInstanceInfoV0 = exports.isInstanceInfoV1 = exports.ParameterType = exports.isAccountTransactionType = exports.AccountTransactionType = exports.BlockItemKind = exports.DelegationTargetType = exports.PoolStatusType = exports.BakerPoolPendingChangeType = exports.OpenStatusText = exports.OpenStatus = exports.StakePendingChangeType = exports.parseWallet = exports.instanceOfTransferWithMemoTransactionSummary = exports.TransactionSummaryType = exports.TransactionStatusEnum = exports.IdDocType = exports.Sex = exports.AttributeKeyString = exports.AttributesKeys = void 0; | ||
__exportStar(require("./types/NodeInfo"), exports); | ||
@@ -94,2 +97,38 @@ __exportStar(require("./types/PeerInfo"), exports); | ||
exports.instanceOfTransferWithMemoTransactionSummary = instanceOfTransferWithMemoTransactionSummary; | ||
/** | ||
* Parses a wallet export file into a WalletExportFormat. The wallet export | ||
* file is exported from a concordium wallet. | ||
*/ | ||
function parseWallet(walletString) { | ||
const wallet = JSON.parse(walletString); | ||
console.log(typeof wallet.type); | ||
if (typeof wallet.type !== 'string') { | ||
throw Error('Expected field "type" to be of type "string" but was of type "' + | ||
typeof wallet.type + | ||
'"'); | ||
} | ||
if (typeof wallet.v !== 'number') { | ||
throw Error('Expected field "v" to be of type "number" but was of type "' + | ||
typeof wallet.v + | ||
'"'); | ||
} | ||
if (typeof wallet.environment !== 'string') { | ||
throw Error('Expected field "environment" to be of type "string" but was of type "' + | ||
typeof wallet.environment + | ||
'"'); | ||
} | ||
if (typeof wallet.value.address !== 'string') { | ||
throw Error('Expected field "value.address" to be of type "string" but was of type "' + | ||
typeof wallet.value.address + | ||
'"'); | ||
} | ||
if (wallet.value.accountKeys === undefined) { | ||
throw Error('Expected field "value.accountKeys" to be defined, but was not'); | ||
} | ||
if (wallet.value.credentials === undefined) { | ||
throw Error('Expected field "value.credentials" to be defined, but was not'); | ||
} | ||
return wallet; | ||
} | ||
exports.parseWallet = parseWallet; | ||
var StakePendingChangeType; | ||
@@ -196,3 +235,3 @@ (function (StakePendingChangeType) { | ||
ParameterType[ParameterType["I64"] = 9] = "I64"; | ||
/** Token amount in microCCD (10^-6 GTU). */ | ||
/** Token amount in microCCD (10^-6 CCD). */ | ||
ParameterType[ParameterType["Amount"] = 10] = "Amount"; | ||
@@ -199,0 +238,0 @@ /** Sender account address. */ |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
}) : function(o, v) { | ||
o["default"] = v; | ||
}); | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
__setModuleDefault(result, mod); | ||
return result; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AccountAddress = void 0; | ||
const bs58check = __importStar(require("bs58check")); | ||
const bs58check_1 = __importDefault(require("bs58check")); | ||
const buffer_1 = require("buffer/"); | ||
@@ -42,3 +22,3 @@ /** | ||
try { | ||
this.decodedAddress = buffer_1.Buffer.from(bs58check.decode(address).slice(1)); | ||
this.decodedAddress = buffer_1.Buffer.from(bs58check_1.default.decode(address).subarray(1)); | ||
this.address = address; | ||
@@ -51,3 +31,3 @@ } | ||
static fromBytes(bytes) { | ||
return new AccountAddress(bs58check.encode(buffer_1.Buffer.concat([buffer_1.Buffer.of(1), bytes]))); | ||
return new AccountAddress(bs58check_1.default.encode(buffer_1.Buffer.concat([buffer_1.Buffer.of(1), bytes]))); | ||
} | ||
@@ -54,0 +34,0 @@ toJSON() { |
@@ -1,78 +0,62 @@ | ||
import { Amount, AuthorizationsV0, AuthorizationsV1, Base58String, HexString } from '..'; | ||
import type { IpInfo, ArInfo, VerifyKey, ExchangeRate, TransactionFeeDistribution, MintDistribution, GasRewards, MintRate, CommissionRates } from '../types'; | ||
export interface MintDistributionUpdate { | ||
updateType: UpdateType.MintDistribution; | ||
update: MintDistribution; | ||
} | ||
export interface FoundationAccountUpdate { | ||
updateType: UpdateType.FoundationAccount; | ||
update: FoundationAccount; | ||
} | ||
export interface ElectionDifficultyUpdate { | ||
updateType: UpdateType.ElectionDifficulty; | ||
update: ElectionDifficulty; | ||
} | ||
export interface EuroPerEnergyUpdate { | ||
updateType: UpdateType.EuroPerEnergy; | ||
update: ExchangeRate; | ||
} | ||
export interface MicroGtuPerEuroUpdate { | ||
updateType: UpdateType.MicroGtuPerEuro; | ||
update: ExchangeRate; | ||
} | ||
export interface TransactionFeeDistributionUpdate { | ||
updateType: UpdateType.TransactionFeeDistribution; | ||
update: TransactionFeeDistribution; | ||
} | ||
export interface GasRewardsUpdate { | ||
updateType: UpdateType.GasRewards; | ||
update: GasRewards; | ||
} | ||
export interface AddAnonymityRevokerUpdate { | ||
updateType: UpdateType.AddAnonymityRevoker; | ||
update: AddAnonymityRevoker; | ||
} | ||
export interface AddIdentityProviderUpdate { | ||
updateType: UpdateType.AddIdentityProvider; | ||
update: AddIdentityProvider; | ||
} | ||
export interface CooldownParametersUpdate { | ||
updateType: UpdateType.CooldownParameters; | ||
update: CooldownParameters; | ||
} | ||
export interface TimeParametersUpdate { | ||
updateType: UpdateType.TimeParameters; | ||
update: TimeParameters; | ||
} | ||
export interface ProtocolUpdate { | ||
updateType: UpdateType.Protocol; | ||
update: ProtocolUpdateDetails; | ||
} | ||
export interface PoolParametersUpdate { | ||
updateType: UpdateType.PoolParameters; | ||
update: PoolParameters; | ||
} | ||
export interface BakerStakeThresholdUpdate { | ||
updateType: UpdateType.BakerStakeThreshold; | ||
update: BakerStakeThreshold; | ||
} | ||
export interface Level1Update { | ||
updateType: UpdateType.Level1; | ||
update: KeyUpdate; | ||
} | ||
export interface RootUpdate { | ||
updateType: UpdateType.Root; | ||
update: KeyUpdate; | ||
} | ||
export interface PendingHigherLevelKeyUpdate { | ||
updateType: UpdateType.HigherLevelKeyUpdate; | ||
update: HigherLevelKeyUpdate; | ||
} | ||
export interface PendingAuthorizationKeysUpdate { | ||
updateType: UpdateType.AuthorizationKeysUpdate; | ||
update: AuthorizationKeysUpdate; | ||
} | ||
export declare type CommonUpdate = MicroGtuPerEuroUpdate | EuroPerEnergyUpdate | TransactionFeeDistributionUpdate | FoundationAccountUpdate | MintDistributionUpdate | ProtocolUpdate | GasRewardsUpdate | BakerStakeThresholdUpdate | ElectionDifficultyUpdate | AddAnonymityRevokerUpdate | AddIdentityProviderUpdate | CooldownParametersUpdate | PoolParametersUpdate | TimeParametersUpdate; | ||
import { Amount, AuthorizationsV0, AuthorizationsV1, Base58String, Duration, Energy, FinalizationCommitteeParameters, GasRewardsV0, GasRewardsV1, HexString, TimeoutParameters } from '..'; | ||
import type { IpInfo, ArInfo, VerifyKey, ExchangeRate, TransactionFeeDistribution, MintDistribution, MintRate, CommissionRates } from '../types'; | ||
declare type ChainUpdate<UpdateType, T> = { | ||
/** The type of the update */ | ||
updateType: UpdateType; | ||
/** The parameters used for the update */ | ||
update: T; | ||
}; | ||
/** An update to mint distribution parameters */ | ||
export declare type MintDistributionUpdate = ChainUpdate<UpdateType.MintDistribution, MintDistribution>; | ||
/** An update to the foundation account */ | ||
export declare type FoundationAccountUpdate = ChainUpdate<UpdateType.FoundationAccount, FoundationAccount>; | ||
/** An update to election difficulty parameters */ | ||
export declare type ElectionDifficultyUpdate = ChainUpdate<UpdateType.ElectionDifficulty, ElectionDifficulty>; | ||
/** An update to the euro per energy exchange rate */ | ||
export declare type EuroPerEnergyUpdate = ChainUpdate<UpdateType.EuroPerEnergy, ExchangeRate>; | ||
/** An update to the micro CCD per euro exchange rate */ | ||
export declare type MicroGtuPerEuroUpdate = ChainUpdate<UpdateType.MicroGtuPerEuro, ExchangeRate>; | ||
/** An update to transaction fee distribution parameters */ | ||
export declare type TransactionFeeDistributionUpdate = ChainUpdate<UpdateType.TransactionFeeDistribution, TransactionFeeDistribution>; | ||
/** An update to gas reward parameters for protocol version 1-5 */ | ||
export declare type GasRewardsV0Update = ChainUpdate<UpdateType.GasRewards, GasRewardsV0>; | ||
/** An update to gas reward parameters from protocol version 6 */ | ||
export declare type GasRewardsV1Update = ChainUpdate<UpdateType.GasRewardsCpv2, GasRewardsV1>; | ||
/** An update to add an anonymity revoker */ | ||
export declare type AddAnonymityRevokerUpdate = ChainUpdate<UpdateType.AddAnonymityRevoker, AddAnonymityRevoker>; | ||
/** An update to add an identity provider */ | ||
export declare type AddIdentityProviderUpdate = ChainUpdate<UpdateType.AddIdentityProvider, AddIdentityProvider>; | ||
/** An update to staking cooldown parameters */ | ||
export declare type CooldownParametersUpdate = ChainUpdate<UpdateType.CooldownParameters, CooldownParameters>; | ||
/** An update to time parameters */ | ||
export declare type TimeParametersUpdate = ChainUpdate<UpdateType.TimeParameters, TimeParameters>; | ||
/** An update holding a protocol update */ | ||
export declare type ProtocolUpdate = ChainUpdate<UpdateType.Protocol, ProtocolUpdateDetails>; | ||
/** An update to baker pool parameters */ | ||
export declare type PoolParametersUpdate = ChainUpdate<UpdateType.PoolParameters, PoolParameters>; | ||
/** An update to baker stake threshold parameters */ | ||
export declare type BakerStakeThresholdUpdate = ChainUpdate<UpdateType.BakerStakeThreshold, BakerStakeThreshold>; | ||
/** An update to timeout parameters, used from protocol version 6 */ | ||
export declare type TimeoutParametersUpdate = ChainUpdate<UpdateType.TimeoutParameters, TimeoutParameters>; | ||
/** An update to mininum time between blocks, used from protocol version 6 */ | ||
export declare type MinBlockTimeUpdate = ChainUpdate<UpdateType.MinBlockTime, Duration>; | ||
/** An update to maximum amount of energy per block, used from protocol version 6 */ | ||
export declare type BlockEnergyLimitUpdate = ChainUpdate<UpdateType.BlockEnergyLimit, Energy>; | ||
/** An update to finalization committee parameters, used from protocol version 6 */ | ||
export declare type FinalizationCommitteeParametersUpdate = ChainUpdate<UpdateType.FinalizationCommitteeParameters, FinalizationCommitteeParameters>; | ||
/** An update to level 1 key */ | ||
export declare type Level1Update = ChainUpdate<UpdateType.Level1, KeyUpdate>; | ||
/** An update to root key */ | ||
export declare type RootUpdate = ChainUpdate<UpdateType.Root, KeyUpdate>; | ||
/** A pending update to higher level keys */ | ||
export declare type PendingHigherLevelKeyUpdate = ChainUpdate<UpdateType.HigherLevelKeyUpdate, HigherLevelKeyUpdate>; | ||
/** A pending update to authorization keys */ | ||
export declare type PendingAuthorizationKeysUpdate = ChainUpdate<UpdateType.AuthorizationKeysUpdate, AuthorizationKeysUpdate>; | ||
/** A union of chain updates, barring key updates */ | ||
export declare type CommonUpdate = MicroGtuPerEuroUpdate | EuroPerEnergyUpdate | TransactionFeeDistributionUpdate | FoundationAccountUpdate | MintDistributionUpdate | ProtocolUpdate | GasRewardsV0Update | BakerStakeThresholdUpdate | ElectionDifficultyUpdate | AddAnonymityRevokerUpdate | AddIdentityProviderUpdate | CooldownParametersUpdate | PoolParametersUpdate | TimeParametersUpdate | GasRewardsV1Update | TimeoutParametersUpdate | MinBlockTimeUpdate | BlockEnergyLimitUpdate | FinalizationCommitteeParametersUpdate; | ||
/** A union of chain updates */ | ||
export declare type UpdateInstructionPayload = CommonUpdate | RootUpdate | Level1Update; | ||
/** A union of possible pending updates */ | ||
export declare type PendingUpdate = CommonUpdate | PendingHigherLevelKeyUpdate | PendingAuthorizationKeysUpdate; | ||
/** Chain update types */ | ||
export declare enum UpdateType { | ||
@@ -98,3 +82,8 @@ Root = "root", | ||
BakerStakeThreshold = "bakerStakeThreshold", | ||
Emergency = "emergency" | ||
Emergency = "emergency", | ||
GasRewardsCpv2 = "gasRewardsCpv2", | ||
TimeoutParameters = "timeoutParameters", | ||
MinBlockTime = "minBlockTime", | ||
BlockEnergyLimit = "blockEnergyLimit", | ||
FinalizationCommitteeParameters = "finalizationCommitteeParameters" | ||
} | ||
@@ -176,1 +165,2 @@ export declare type KeyUpdate = HigherLevelKeyUpdate | AuthorizationKeysUpdate; | ||
}; | ||
export {}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.AuthorizationKeysUpdateType = exports.HigherLevelKeyUpdateType = exports.KeyUpdateEntryStatus = exports.UpdateType = void 0; | ||
/** Chain update types */ | ||
var UpdateType; | ||
@@ -26,2 +27,7 @@ (function (UpdateType) { | ||
UpdateType["Emergency"] = "emergency"; | ||
UpdateType["GasRewardsCpv2"] = "gasRewardsCpv2"; | ||
UpdateType["TimeoutParameters"] = "timeoutParameters"; | ||
UpdateType["MinBlockTime"] = "minBlockTime"; | ||
UpdateType["BlockEnergyLimit"] = "blockEnergyLimit"; | ||
UpdateType["FinalizationCommitteeParameters"] = "finalizationCommitteeParameters"; | ||
})(UpdateType = exports.UpdateType || (exports.UpdateType = {})); | ||
@@ -28,0 +34,0 @@ var KeyUpdateEntryStatus; |
import { Buffer } from 'buffer/'; | ||
/** | ||
* Decodes an unsigned leb128 encoded value to bigint. | ||
* Decodes an unsigned leb128 encoded value to bigint. Note that if buffer | ||
* that is provided does not _only_ contain the uleb128 encoded number an | ||
* error will be thrown. | ||
* | ||
@@ -11,2 +13,13 @@ * @param {Buffer} buffer - The buffer to decode | ||
/** | ||
* Decodes an unsigned leb128 encoded value to bigint and returns it along | ||
* with the index of the end of the encoded uleb128 number + 1. | ||
* | ||
* @param {Buffer} bytes - The buffer to decode | ||
* @param {number} index - A non-negative index to decode at, defaults to 0 | ||
* | ||
* @returns {[bigint, number]} the decoded bigint value and the index of | ||
* the end of the encoded uleb128 number + 1. | ||
*/ | ||
export declare function uleb128DecodeWithIndex(bytes: Buffer, index?: number): [bigint, number]; | ||
/** | ||
* Encodes a bigint value as unsigned leb128. | ||
@@ -13,0 +26,0 @@ * |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.uleb128Encode = exports.uleb128Decode = void 0; | ||
exports.uleb128Encode = exports.uleb128DecodeWithIndex = exports.uleb128Decode = void 0; | ||
const buffer_1 = require("buffer/"); | ||
/** | ||
* Decodes an unsigned leb128 encoded value to bigint. | ||
* Decodes an unsigned leb128 encoded value to bigint. Note that if buffer | ||
* that is provided does not _only_ contain the uleb128 encoded number an | ||
* error will be thrown. | ||
* | ||
@@ -13,7 +15,39 @@ * @param {Buffer} buffer - The buffer to decode | ||
const uleb128Decode = (buffer) => { | ||
return buffer.reduce((result, byte, i) => result | (BigInt(byte & 0x7f) << BigInt(7 * i)), // For each byte, get the value of the 7 least significant bits (byte & 0x7f) and add this to the accumulator (<< 7 * i) | ||
0n); | ||
const [bigint, index] = uleb128DecodeWithIndex(buffer); | ||
if (index !== buffer.length) { | ||
throw Error('The provided buffer did not contain just a single ULEB128 encoded number'); | ||
} | ||
return bigint; | ||
}; | ||
exports.uleb128Decode = uleb128Decode; | ||
/** | ||
* Decodes an unsigned leb128 encoded value to bigint and returns it along | ||
* with the index of the end of the encoded uleb128 number + 1. | ||
* | ||
* @param {Buffer} bytes - The buffer to decode | ||
* @param {number} index - A non-negative index to decode at, defaults to 0 | ||
* | ||
* @returns {[bigint, number]} the decoded bigint value and the index of | ||
* the end of the encoded uleb128 number + 1. | ||
*/ | ||
function uleb128DecodeWithIndex(bytes, index = 0) { | ||
if (bytes.length <= index) { | ||
throw Error(`The ULEB128 encoding was not valid: The passed bytes from index ${index} must at least contain a single byte`); | ||
} | ||
let acc = 0n; | ||
let nextIndex = index; | ||
// For each byte, get the value of the 7 least significant bits (byte & 0x7f) and add this to the accumulator (<< 7 * i) | ||
for (let i = index; i < bytes.length; i++) { | ||
nextIndex += 1; | ||
const byte = bytes[i]; | ||
const c = BigInt(byte & 0x7f) << BigInt(7 * (i - index)); | ||
acc += c; | ||
if ((byte & 0x80) === 0x00) { | ||
return [acc, nextIndex]; | ||
} | ||
} | ||
throw Error('The ULEB128 encoding was not valid: Could not find end of number'); | ||
} | ||
exports.uleb128DecodeWithIndex = uleb128DecodeWithIndex; | ||
/** | ||
* Encodes a bigint value as unsigned leb128. | ||
@@ -20,0 +54,0 @@ * |
{ | ||
"name": "@concordium/common-sdk", | ||
"version": "7.0.1", | ||
"version": "8.0.0", | ||
"license": "Apache-2.0", | ||
@@ -54,3 +54,3 @@ "engines": { | ||
"dependencies": { | ||
"@concordium/rust-bindings": "0.12.0", | ||
"@concordium/rust-bindings": "1.0.0", | ||
"@grpc/grpc-js": "^1.3.4", | ||
@@ -57,0 +57,0 @@ "@noble/ed25519": "^1.7.1", |
877
README.md
@@ -1,874 +0,7 @@ | ||
# Common | ||
# Concordium JS SDKs Common Functionality | ||
This package is the shared library for the nodejs and web SDK's. | ||
This package is the shared library for the NodeJS and Web SDK's. | ||
**Table of Contents** | ||
- [Constructing transactions](#constructing-transactions) | ||
- [Create a simple transfer](#create-a-simple-transfer) | ||
- [Create a simple transfer with a memo](#create-a-simple-transfer-with-a-memo) | ||
- [Create a Register data transaction](#create-a-register-data-transaction) | ||
- [Create a configure delegation transaction](#create-a-configure-delegation-transaction) | ||
- [Create a configure baker transaction](#create-a-configure-baker-transaction) | ||
- [Create a credential for an existing account](#create-a-credential-for-an-existing-account) | ||
- [Create an update credentials transaction](#create-an-update-credentials-transaction) | ||
- [Deploy module](#deploy-module) | ||
- [Init Contract (parameterless smart contract)](#init-contract-parameterless-smart-contract) | ||
- [Update Contract (parameterless smart contract)](#update-contract-parameterless-smart-contract) | ||
- [Smart contract with parameters](#smart-contract-with-parameters) | ||
- [Serialize parameters with only the specific type's schema](#serialize-parameters-with-only-the-specific-types-schema) | ||
- [Utility functions](#utility-functions) | ||
- [Generate account alias](#generate-account-alias) | ||
- [Check for account alias](#check-for-account-alias) | ||
- [Deserialize contract state](#deserialize-contract-state) | ||
- [Deserialize a receive function's return value](#deserialize-a-receive-functions-return-value) | ||
- [Deserialize a function's error](#deserialize-a-functions-error) | ||
- [Deserialize a transaction](#deserialize-a-transaction) | ||
- [Creating an AccountSigner](#creating-an-accountsigner) | ||
- [Sign an account transaction](#sign-an-account-transaction) | ||
- [Sign a message](#sign-a-message) | ||
- [Check smart contract for support for standards](#check-smart-contract-for-support-for-standards) | ||
- [Identity proofs](#identity-proofs) | ||
- [Build Statement](#build-statement) | ||
- [Minimum Age](#minimum-age) | ||
- [Eu membership](#eu-membership) | ||
- [Reveal statement](#reveal-statement) | ||
- [Range statement](#range-statement) | ||
- [Membership statement](#membership-statement) | ||
- [Non membership statement](#non-membership-statement) | ||
- [Verify Statement (verifyIdstatement)](#verify-statement-verifyidstatement) | ||
- [Prove Statement (getIdProof)](#prove-statement-getidproof) | ||
- [ConcordiumNodeClient](#concordiumnodeclient) | ||
- [JSON-RPC client](#json-rpc-client) | ||
- [CIS-2 Contract](#cis-2-contract) | ||
# Constructing transactions | ||
## Create a simple transfer | ||
The following example demonstrates how a simple transfer can be created. | ||
```js | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: 1n, // the next nonce for this account, can be found using getNextAccountNonce | ||
sender: new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"), | ||
}; | ||
const simpleTransfer: SimpleTransferPayload = { | ||
amount: new CcdAmount(100n), | ||
toAddress: new AccountAddress("4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf"), | ||
}; | ||
const simpleTransferAccountTransaction: AccountTransaction = { | ||
header: header, | ||
payload: simpleTransfer, | ||
type: AccountTransactionType.Transfer, | ||
}; | ||
``` | ||
## Create a simple transfer with a memo | ||
The following example demonstrates how a simple transfer with a memo can be created. | ||
```js | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: 1n, // the next nonce for this account, can be found using getNextAccountNonce | ||
sender: new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"), | ||
}; | ||
const simpleTransferWithMemo: SimpleTransferWithMemoPayload = { | ||
amount: new CcdAmount(100n), | ||
toAddress: new AccountAddress("4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf"), | ||
memo: new DataBlob(Buffer.from('6B68656C6C6F20776F726C64', 'hex')), | ||
}; | ||
const simpleTransferWithMemoAccountTransaction: AccountTransaction = { | ||
header: header, | ||
payload: simpleTransferWithMemo, | ||
type: AccountTransactionType.TransferWithMemo, | ||
}; | ||
``` | ||
## Create a Register data transaction | ||
The following example demonstrates how a register data transaction can be created. | ||
```js | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: 1n, // the next nonce for this account, can be found using getNextAccountNonce | ||
sender: new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"), | ||
}; | ||
const registerData: RegisterDataPayload = { | ||
data: new DataBlob(Buffer.from('6B68656C6C6F20776F726C64', 'hex')) // Add the bytes you wish to register as a DataBlob | ||
}; | ||
const registerDataAccountTransaction: AccountTransaction = { | ||
header: header, | ||
payload: registerData, | ||
type: AccountTransactionType.RegisterData, | ||
}; | ||
``` | ||
## Create a configure delegation transaction | ||
The following example demonstrates how a configure delegation transaction can be created. | ||
Note that although all the fields are optional, they are all required, when becoming a delegator. | ||
```js | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: 1n, // the next nonce for this account, can be found using getNextAccountNonce | ||
sender: new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"), | ||
}; | ||
const configureDelegationPayload: ConfigureDelegationPayload = { | ||
stake: new CcdAmount(1000000000n), | ||
delegationTarget: { | ||
delegateType: DelegationTargetType.Baker, | ||
bakerId: 100n | ||
}, | ||
restakeEarnings: true, | ||
}; | ||
const configureDelegationAccountTransaction: AccountTransaction = { | ||
header: header, | ||
payload: configureDelegationPayload, | ||
type: AccountTransactionType.ConfigureDelegation, | ||
}; | ||
``` | ||
## Create a configure baker transaction | ||
The following example demonstrates how a configure baker transaction can be created. | ||
Note that although all the fields are optional, they are all required, when registering as a baker. | ||
```js | ||
const account = new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"); | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: 1n, // the next nonce for this account, can be found using getNextAccountNonce | ||
sender: account, | ||
}; | ||
const bakerKeys = generateBakerKeys(account); | ||
const configureBakerPayload: ConfigureBakerPayload = { | ||
stake: new CcdAmount(1000000000n), | ||
restakeEarnings: true, | ||
openForDelegation: OpenStatus.OpenForAll, | ||
keys: bakerKeys, | ||
metadataUrl: "www.url.for.metadata", | ||
transactionFeeCommission: 10000, | ||
bakingRewardCommission: 10000, | ||
finalizationRewardCommission: 100000, | ||
}; | ||
const configureBakerAccountTransaction: AccountTransaction = { | ||
header: header, | ||
payload: configureBakerPayload, | ||
type: AccountTransactionType.ConfigureBaker, | ||
}; | ||
``` | ||
The open for delegation field determines the baker pools status and can have three different values: | ||
- `OpenForAll`: new delegators can join the pool. | ||
- `ClosedForAll`: new delegators won't be able to join the pool, but the current delegators won't be moved to passive delegation. | ||
- `ClosedForNew`: new delegators won't be able to join the pool, and the current delegators will be moved to passive delegation. | ||
The three commission rates should specified in parts per hundred thousand, i.e. 100% is 100000 and 1% 1000. Additionally they value should be within the allowed range. | ||
The allowed ranges are part of the chain parameters. | ||
## Create a credential for an existing account | ||
The following example demonstrates how to create a credential for an existing account. This | ||
credential can then be deployed onto the account by the account owner with an update | ||
credentials transaction. See [Create an update credentials transaction](#Create-an-update-credentials-transaction) for how to | ||
create this transaction payload using the output from the example below. | ||
See [Construct IdentityInput](#Construct-identityInput-for-creating-credentials) for how to construct an IdentityInput. | ||
```js | ||
const lastFinalizedBlockHash = (await client.getConsensusStatus()).lastFinalizedBlock; | ||
const cryptographicParameters = await client.getCryptographicParameters(lastFinalizedBlockHash); | ||
if (!cryptographicParameters) { | ||
throw new Error('Cryptographic parameters were not found on a block that has been finalized.'); | ||
} | ||
// The parts of the identity required to create a new credential, parsed from | ||
// e.g. a wallet export. | ||
const identityInput: IdentityInput = ... | ||
// Require just one key on the credential to sign. This can be any number | ||
// up to the number of public keys added to the credential. | ||
const threshold: number = 1; | ||
// The index of the credential that will be created. This index is per identity | ||
// and has to be in sequence, and not already used. Note that index 0 is used | ||
// by the initial credential that was created with the identity. | ||
const credentialIndex: number = 1; | ||
// In this example the credential will have one signing key, but there | ||
// could be multiple. The signatures on the credential must be supplied | ||
// in the same order as the keys are here. | ||
const publicKeys: VerifyKey[] = [ | ||
{ | ||
schemeId: "Ed25519", | ||
verifyKey: "c8cd7623c5a9316d8e2fccb51e1deee615bdb5d324fb4a6d33801848fb5e459e" | ||
} | ||
]; | ||
// The attributes to reveal about the account holder on chain. In the case of an | ||
// empty array no attributes are revealed. | ||
const revealedAttributes: AttributeKey[] = []; | ||
// The next step creates an unsigned credential for an existing account. | ||
// Note that unsignedCredentialForExistingAccount also contains the randomness used, | ||
// which should be saved to later be able to reveal attributes, or prove properties about them. | ||
const existingAccountAddress = new AccountAddress("3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGPUe8JsoAcU"); | ||
const unsignedCredentialForExistingAccount = createUnsignedCredentialForExistingAccount( | ||
identityInput, | ||
cryptographicParameters.value, | ||
threshold, | ||
publicKeys, | ||
credentialIndex, | ||
revealedAttributes, | ||
existingAccountAddress | ||
); | ||
// Sign the credential information. | ||
const credentialDigestToSign = getCredentialForExistingAccountSignDigest(unsignedCredentialForExistingAccount.unsignedCdi, existingAccountAddress); | ||
const credentialSigningKey = 'acab9ec5dfecfe5a6e13283f7ca79a6f6f5c685f036cd044557969e4dbe9d781'; | ||
const credentialSignature = Buffer.from(await ed.sign(credentialDigestToSign, credentialSigningKey)).toString('hex'); | ||
// Combine the credential and the signatures so that the object is ready | ||
// to be submitted as part of an update credentials transaction. This is the | ||
// object that must be provided to the account owner, who can then use it to | ||
// deploy it to their account. | ||
const signedCredentialForExistingAccount: CredentialDeploymentInfo = buildSignedCredentialForExistingAccount(unsignedCredentialForExistingAccount.unsignedCdi, [credentialSignature]); | ||
``` | ||
## Create an update credentials transaction | ||
The following demonstrates how to construct an update credentials transaction, which is | ||
used to deploy additional credentials to an account, remove existing credentials on the account | ||
or to update the credential threshold on the account. Note that the initial credential with | ||
index 0 cannot be removed. | ||
```js | ||
// The signed credential that is to be deployed on the account. Received from the | ||
// credential holder. | ||
const signedCredentialForExistingAccount: CredentialDeploymentInfo = ... | ||
// The credentials that are deployed have to be indexed. Index 0 is used up | ||
// by the initial credential on an account. The indices that have already been | ||
// used can be found in the AccountInfo. | ||
const accountAddress = new AccountAddress("3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGPUe8JsoAcU"); | ||
const accountInfo = await client.getAccountInfo(accountAddress, lastFinalizedBlockHash); | ||
const nextAvailableIndex = Math.max(...Object.keys(accountInfo.accountCredentials).map((key) => Number(key))) + 1; | ||
// The current number of credentials on the account is required, as it is used to calculate | ||
// the correct energy cost. | ||
const currentNumberOfCredentials = BigInt(Object.keys(accountInfo.accountCredentials).length); | ||
const newCredential: IndexedCredentialDeploymentInfo = { | ||
cdi: signedCredentialForExistingAccount, | ||
index: nextAvailableIndex | ||
}; | ||
// List the credential id (credId) of any credentials that should be removed from the account. | ||
// The existing credentials (and their credId) can be found in the AccountInfo. | ||
const credentialsToRemove = ["b0f11a9dcdd0758c8eec717956455deed73a0db59995da2cb20d73ee974eb39aec2c79970c640126827a8fbb84217424"]; | ||
// Update the credential threshold to 2, so that transactions require signatures from both | ||
// of the credentials. If left at e.g. 1, then both credentials can create transactions | ||
// by themselves. | ||
const threshold = 2; | ||
const updateCredentialsPayload: UpdateCredentialsPayload = { | ||
newCredentials: [newCredential], | ||
removeCredentialIds: credentialsToRemove, | ||
threshold: threshold, | ||
currentNumberOfCredentials: currentNumberOfCredentials, | ||
}; | ||
``` | ||
## Deploy module | ||
The following example demonstrates how to construct a "deployModule" transaction, which is used to deploy a smart contract module. | ||
```js | ||
//Get the wasm file as a buffer. | ||
const wasmModule = Buffer.from(fs.readFileSync('path/to/module.wasm')); | ||
const deployModule: DeployModulePayload = { | ||
source: wasmModule | ||
}; | ||
const header: AccountTransactionHeader = { | ||
expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), | ||
nonce: nextAccountNonce.nonce, | ||
sender: new AccountAddress(senderAccountAddress), | ||
}; | ||
const deployModuleTransaction: AccountTransaction = { | ||
header: header, | ||
payload: deployModule, | ||
type: AccountTransactionType.DeployModule, | ||
}; | ||
``` | ||
Note that if built using cargo-concordium `1.0.0`, the version should be added to the payload. In `2.0.0` and newer, the version is prepended into the module itself. To deploy a V0 module, which has been built with cargo-concordium version below 2, | ||
you should add the version field to the payload: | ||
```js | ||
const deployModule: DeployModulePayload = { | ||
source: wasmModule, | ||
version: 0, | ||
}; | ||
``` | ||
Finally, to actually deploy the module to the chain, send the constructed `deployModuleTransaction` to the chain using `sendAccountTransaction`. (See [Send Account Transaction](#Send-Account-Transaction) for how to do this) | ||
## Init Contract (parameterless smart contract) | ||
The following example demonstrates how to initialize a smart contract from a module, which has already been deployed. | ||
The name of the contract "INDBank". | ||
In this example, the contract does not take any parameters, so we can leave parameters as an empty buffer. | ||
```js | ||
const contractName = 'INDBank'; | ||
const params = Buffer.from([]); | ||
//The amount of energy that can be used for contract execution. | ||
const maxContractExecutionEnergy = 300000n; | ||
``` | ||
Create init contract transaction | ||
```js | ||
const initModule: InitContractPayload = { | ||
amount: new CcdAmount(0n), // Amount to send to the contract. If the smart contract is not payable, set the amount to 0. | ||
moduleRef: new ModuleReference('a225a5aeb0a5cf9bbc59209e15df030e8cc2c17b8dba08c4bf59f80edaedd8b1'), // Module reference | ||
initName: contractName, | ||
params: params, | ||
maxContractExecutionEnergy: maxContractExecutionEnergy | ||
}; | ||
const initContractTransaction: AccountTransaction = { | ||
header: header, | ||
payload: initModule, | ||
type: AccountTransactionType.InitContract, | ||
}; | ||
``` | ||
Finally, to actually initialize the contract on the chain, send the constructed `initContractTransaction` to the chain using `sendAccountTransaction`. (See [Send Account Transaction](#Send-Account-Transaction) for how to do this) | ||
## Update Contract (parameterless smart contract) | ||
The following example demonstrates how to update a smart contract. | ||
To update a smart contract we create a 'updateContractTransaction'. | ||
To do this we need to specify the name of the receive function, which should contain the contract name as a prefix (So if the contract has the name "INDBank" and the receive function has the name "insertAmount" then the receiveName should be "INDBank.insertAmount"). | ||
We also need to supply the contract address of the contract instance. This consists of an index and a subindex. | ||
In this example, the contract does not take any parameters, so we can leave the parameters/message as an empty buffer. | ||
```js | ||
const receiveName = 'INDBank.insertAmount'; | ||
const message = Buffer.from([]); | ||
const contractAddress = { index: BigInt(83), subindex: BigInt(0) } as ContractAddress; | ||
//The amount of energy that can be used for contract execution. | ||
const maxContractExecutionEnergy = 30000n; | ||
``` | ||
Create update contract transaction | ||
```js | ||
const updateModule: UpdateContractPayload = | ||
{ | ||
amount: new CcdAmount(1000n), | ||
address: contractAddress, | ||
receiveName: receiveName, | ||
message: message, | ||
maxContractExecutionEnergy: maxContractExecutionEnergy | ||
}; | ||
const updateContractTransaction: AccountTransaction = { | ||
header: header, | ||
payload: updateModule, | ||
type: AccountTransactionType.Update, | ||
}; | ||
``` | ||
Finally, to actually update the contract on the chain, send the constructed `updateContractTransaction` to the chain using `sendAccountTransaction`. (See [Send Account Transaction](#Send-Account-Transaction) for how to do this) | ||
## Smart contract with parameters | ||
In the previous sections we have seen how to initialize and update contracts without parameters. In this section we will describe how to initialize and update contracts with parameters. | ||
The user should provide the input in the JSON format specified in [our documentation](https://developer.concordium.software/en/mainnet/smart-contracts/references/schema-json.html). | ||
Let us consider the following example where the contract's initialization parameter is the following structure: | ||
```rust | ||
#[derive(SchemaType, Serialize)] | ||
struct MyStruct { | ||
age: u16, | ||
name: String, | ||
city: String, | ||
} | ||
``` | ||
An example of a valid input would be: | ||
```js | ||
const userInput = { | ||
age: 51, | ||
name: 'Concordium', | ||
city: 'Zug', | ||
}; | ||
``` | ||
An other example could be if the parameter is the following "SomeEnum": | ||
```rust | ||
#[derive(SchemaType, Serialize)] | ||
enum AnotherEnum { | ||
D, | ||
} | ||
#[derive(SchemaType, Serialize)] | ||
enum SomeEnum { | ||
B(AnotherEnum), | ||
} | ||
``` | ||
Then the following would be a valid input: | ||
```js | ||
const userInput = { | ||
B: [ | ||
{ | ||
D: [] | ||
} | ||
] | ||
}; | ||
``` | ||
Then the user needs to provide the schema for the module. Here we load the schema from a file: | ||
```js | ||
const rawModuleSchema = Buffer.from(fs.readFileSync( | ||
'SCHEMA-FILE-PATH' | ||
)); | ||
``` | ||
Then the parameters can be serialized into bytes: | ||
```js | ||
const inputParams = serializeInitContractParameters( | ||
"my-contract-name", | ||
userInput, | ||
rawModuleSchema, | ||
schemaVersion | ||
); | ||
``` | ||
For V0 contracts the schemaVersion should be `SchemaVersion.V0`. For V1 contracts it should currently be `SchemaVersion.V1`, unless the contract have been built using cargo-concordium >=2.0.0, which are internally versioned, and then the version does not need to be provided. | ||
Then the payload and transaction can be constructed, in the same way as the parameterless example: | ||
```js | ||
const initModule: InitContractPayload = { | ||
amount: new CcdAmount(0n), | ||
moduleRef: new ModuleReference( | ||
'6cabee5b2d9d5013216eef3e5745288dcade77a4b1cd0d7a8951262476d564a0' | ||
), | ||
contractName: contractName, | ||
params: inputParams, | ||
maxContractExecutionEnergy: baseEnergy, | ||
}; | ||
const initContractTransaction: AccountTransaction = { | ||
header: header, | ||
payload: initModule, | ||
type: AccountTransactionType.InitContract, | ||
}; | ||
``` | ||
Finally, to actually initialize the contract on the chain, send the constructed `initContractTransaction` to the chain using `sendAccountTransaction`. (See [Send Account Transaction](#Send-Account-Transaction) for how to do this) | ||
To update a contract with parameters, consider the example where the input is an i64 value, like -2000000. | ||
```js | ||
const userInput = -2000000; | ||
const contractName = "my-contract-name"; | ||
const receiveFunctionName = "my-receive-function-name"; | ||
const receiveName = contractName + '.' + receiveFunctionName; | ||
``` | ||
Then the user need to provide the schema. Here we load the schema from a file: | ||
```js | ||
const rawModuleSchema = Buffer.from(fs.readFileSync( | ||
'SCHEMA-FILE-PATH' | ||
)); | ||
``` | ||
Then the parameters can be serialized into bytes: | ||
```js | ||
const inputParams = serializeUpdateContractParameters( | ||
contractName, | ||
receiveFunctionName, | ||
userInput, | ||
rawModuleSchema, | ||
schemaVersion | ||
); | ||
``` | ||
For V0 contracts the schema version should be `SchemaVersion.V0`. For V1 contracts it should currently be `SchemaVersion.V1`, unless the contract have been built using cargo-concordium >=2.0.0, which are internally versioned, and then the version does not need to be provided. | ||
Then we will construct the update payload with parameters obtained | ||
```js | ||
const updateModule: UpdateContractPayload = { | ||
amount: new CcdAmount(1000n), | ||
address: contractAddress, | ||
receiveName: receiveName, | ||
message: inputParams, | ||
maxContractExecutionEnergy: baseEnergy, | ||
} as UpdateContractPayload; | ||
const updateContractTransaction: AccountTransaction = { | ||
header: header, | ||
payload: updateModule, | ||
type: AccountTransactionType.Update, | ||
}; | ||
``` | ||
Finally, to actually update the contract on the chain, send the constructed `updateContractTransaction` to the chain using `sendAccountTransaction`. (See [Send Account Transaction](#Send-Account-Transaction) for how to do this) | ||
## Serialize parameters with only the specific type's schema | ||
In the previous section the schema used was assumed to be the schema for an entire module. In some cases one might want to use a schema containing only the specific type of the parameter. | ||
For this, the function `serializeTypeValue` can used. | ||
``` | ||
const inputParams = serializeTypeValue(userInput, rawTypeSchema); | ||
``` | ||
For reference, the type schema for parameters can be extracted using the functions `getInitContractParameterSchema` and `getUpdateContractParameterSchema`. For a receive function: | ||
``` | ||
const rawTypeSchema = getUpdateContractParameterSchema( | ||
rawModuleSchema, | ||
contractName, | ||
receiveFunctionName, | ||
schemaVersion | ||
) | ||
``` | ||
And for the initialization: | ||
``` | ||
const rawTypeSchema = getInitContractParameterSchema( | ||
rawModuleSchema, | ||
contractName, | ||
schemaVersion | ||
) | ||
``` | ||
# Utility functions | ||
## Generate account alias | ||
The following shows how to generate an account alias. The alias is an alternative address, which is connected to the same account. | ||
The getAlias function takes a counter (0 <= counter < 2^24) to determine which alias to return. | ||
``` | ||
const accountAddress = new AccountAddress("3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGPUe8JsoAcU"); | ||
const aliasCount = 1; | ||
const alias: AccountAddress = getAlias(accountAddress, aliasCount); | ||
``` | ||
## Check for account alias | ||
The following shows how to check if two addresses are aliases. | ||
``` | ||
const accountAddress = new AccountAddress("3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGPUe8JsoAcU"); | ||
const anotherAccountAddress = new AccountAddress("3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGJhiz8WxC5b"); | ||
if (isAlias(accountAddress, anotherAccountAddress)) { | ||
... // the addresses are aliases | ||
} else { | ||
... // the addresses are not aliases | ||
} | ||
``` | ||
## Deserialize contract state | ||
The following example demonstrates how to deserialize a contract's state: | ||
```js | ||
const contractName = "my-contract-name" | ||
const schema = Buffer.from(schemaSource); // Load schema from file | ||
const rawContractState = Buffer.from(stateSource); // Could be getinstanceInfo(...).model | ||
const state = deserializeContractState(contractName, schema, rawContractState); | ||
``` | ||
## Deserialize a receive function's return value | ||
The following example demonstrates how to deserialize a receive function's return value: | ||
```js | ||
const rawReturnValue = Buffer.from(returnValueSource); | ||
const schema = Buffer.from(schemaSource); // Load schema from file | ||
const contractName = "my-contract-name"; | ||
const functionName = "receive-function"; | ||
const schemaVersion = SchemaVersion.V1; | ||
const returnValue = deserializeReceiveReturnValue(rawReturnValue, schema, contractName, functionName, schemaVersion); | ||
``` | ||
Note that for V0 contracts the schemaVersion should be `SchemaVersion.V0`. For V1 contracts it should currently be `SchemaVersion.V1`, unless the contract have been built using cargo-concordium >=2.0.0, which are internally versioned, and then the version does not need to be provided. | ||
## Deserialize a function's error | ||
The following example demonstrates how to deserialize a receive function's error: | ||
```js | ||
const rawError = Buffer.from(errorSource); | ||
const schema = Buffer.from(schemaSource); // Load schema from file | ||
const contractName = "my-contract-name"; | ||
const functionName = "receive-function"; | ||
const error = deserializeReceiveError(rawError, schema, contractName, functionName); | ||
``` | ||
Likewise for an init function's error: | ||
```js | ||
const rawError = Buffer.from(errorSource); | ||
const schema = Buffer.from(schemaSource); // Load schema from file | ||
const contractName = "my-contract-name"; | ||
const error = deserializeInitError(rawError, schema, contractName); | ||
``` | ||
## Deserialize a transaction | ||
The following example demonstrates how to deserialize a transaction: | ||
```js | ||
const serializedTransaction: Buffer = ... | ||
const deserialized = deserializeTransaction(serializedTransaction); | ||
if (deserialized.kind === BlockItemKind.AccountTransactionKind) { | ||
// transaction is an account transaction | ||
const accountTransaction: AccountTransaction = deserialized.transaction.accountTransaction; | ||
const signatures: AccountTransactionSignature = deserialized.transaction.signatures; | ||
... | ||
if (accountTransaction.type === AccountTransactionType.Transfer) { | ||
// transaction is a simple transfer | ||
} | ||
} else if (deserialized.kind === BlockItemKind.CredentialDeploymentKind) { | ||
// transaction is a credentialDeployment | ||
const credentialDeployment = deserialized.transaction.credential; | ||
} | ||
``` | ||
Note that currently the only supported account transaction kinds are `Transfer`, `TransferWithMemo` and `RegisterData`. If attempting to deserialize other transaction kinds, the function will throw an error; | ||
## Creating an `AccountSigner` | ||
It is possible to build an `AccountSigner` in a variety of ways by utilizing the function `buildAccountSigner`. For a simple account, with a single credential and one keypair in the credential, one can supply a single private key, like so: | ||
```js | ||
const privateKey = '...'; // Private key of an account as hex string | ||
const signer: AccountSigner = buildAccountSigner(privateKey); | ||
``` | ||
For a more complex account with one or more credentials, each with one or more keypairs, `buildAccountSigner` is also compatible with the format created by the chain genesis tool, Concordium wallet exports, along with a map of type `SimpleAccountKeys`. | ||
```js | ||
const keys: SimpleAccountKeys = { | ||
0: { | ||
0: '...', // Private key of an account as hex string | ||
1: '...', | ||
... | ||
}, | ||
... | ||
}; | ||
const signer: AccountSigner = buildAccountSigner(keys); | ||
``` | ||
## Sign an account transaction | ||
The following example demonstrates how to use the `signTransaction` helper function to sign a account transaction: | ||
```js | ||
let accountTransaction: AccountTransaction; | ||
// Create the transaction | ||
// ... | ||
const signer: AccountSigner = ...; | ||
const transactionSignature: AccountTransactionSignature = signTransaction(accountTransaction, signer); | ||
... | ||
sendTransaction(accountTransaction, transactionSignature); | ||
``` | ||
The following is an example of how to sign an account transaction without using the `signTransaction` helper function: | ||
```js | ||
import * as ed from "@noble/ed25519"; | ||
let accountTransaction: AccountTransaction; | ||
// Create the transaction | ||
// ... | ||
// Sign the transaction, the following is just an example, and any method for signing | ||
// with the key can be employed. | ||
const signingKey = "ce432f6bba0d47caec1f45739331dc354b6d749fdb8ab7c2b7f6cb24db39ca0c"; | ||
const hashToSign = getAccountTransactionSignDigest(accountTransaction); | ||
const signature = Buffer.from(await ed.sign(hashToSign, signingKey)).toString("hex"); | ||
// The signatures used to sign the transaction must be provided in a structured way, | ||
// so that each signature can be mapped to the credential that signed the transaction. | ||
// In this example we assume the key used was from the credential with index 0, and it | ||
// was the key with index 0. | ||
const signatures: AccountTransactionSignature = { | ||
0: { | ||
0: signature | ||
} | ||
}; | ||
``` | ||
## Sign a message | ||
To have an account sign an arbritrary message, one can use the `signMessage` function: | ||
```js | ||
const account = new AccountAddress("4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M"); | ||
const message = "testMessage"; | ||
const signer: AccountSigner = ...; | ||
const signature = signMessage(account, message, signer); | ||
``` | ||
What is actually signed is the sha256 hash of the account address, eight zero bytes and the actual message. This ensures that the message cannot be an account transaction. To easily verify the signature, one can use the `verifyMessageSignature` function: | ||
```js | ||
const message = "testMessage"; | ||
const signature = ...; // signature from signMessage | ||
const accountInfo = ...; // the getAccountInfo node entrypoint can be used for this | ||
if (!verifyMessageSignature(message, signature, accountInfo)) { | ||
// the signature is incorrect | ||
} | ||
``` | ||
The message can either be a utf8 encoded string or a Uint8Array directly containing the message bytes. | ||
## Deserialize smart contract types with only the specific type's schema | ||
The SDK exposes a general function to deserialize smart contract values from binary format to their JSON representation. In the previous sections the schema used was assumed to be the schema for an entire module, this function can be used with the schema containing only the specific type of the parameter, return value, event or error. | ||
``` | ||
const deserializedValue = deserializeTypeValue(serializedValue, rawTypeSchema); | ||
``` | ||
Note that the specific schema can be obtained using [cargo-concordium](https://developer.concordium.software/en/mainnet/smart-contracts/guides/setup-tools.html#cargo-concordium)'s `schema-json` command, and specifically for parameters, this SDK exposes functions for that, check [the serialize parameters with only the specific types schema section](serialize-parameters-with-only-the-specific-types-schema) for those. | ||
## Check smart contract for support for standards | ||
To check if a smart contract supports a certain standard (according to [CIS-0 standard detection](https://proposals.concordium.software/CIS/cis-0.html)), the utility function `cis0Supports` can be used. It should be noted, that the support of the contract is purely based on the claims of the contract and does not give any guarantees for whether the contract adheres to the standard it claims to implement. The function returns `undefined` if the contract does not support CIS-0. | ||
This requires a [`ConcordiumNodeClient`](../../docs/gRPC.md). | ||
```js | ||
const client = ...; // `ConcordiumNodeClient` | ||
const address = {index: 1234n, subindex: 0n}; // Contract to check for support. | ||
const standardId = 'CIS-2'; | ||
// const standardIds = ['CIS-1', 'CIS-2']; // Example of a list of standards to check for. | ||
const supportResult = await cis0Supports(client, address, 'CIS-2'); | ||
``` | ||
# Identity proofs | ||
## Build Statement | ||
The SDK contains a helper to create statements about identities, which can then be proven. | ||
To do so, use the IdStatementBuilder, to build a statement: | ||
```js | ||
const statementBuilder = new IdStatementBuilder(); | ||
... | ||
const statement = statementBuilder.getStatement(); | ||
``` | ||
The statement can then be proved using the `getIdProof`, or be provided to a wallet for them it to provide a proof for the statement. | ||
There are currently 4 types of the statements, and if multiple are added, the resulting statement is the conjunction between them. | ||
| Attribute name | Format | | ||
|--------------------|-----------------------------------------------------------------------------| | ||
| firstName | string | | ||
| lastName | string | | ||
| sex | ISO/IEC 5218 | | ||
| dob | ISO8601 YYYYMMDD | | ||
| countryOfResidence | ISO3166-1 alpha-2 | | ||
| nationality | ISO3166-1 alpha-2 | | ||
| idDocType | na=0, passport=1, national id card=2, driving license=3, immigration card=4 | | ||
| idDocNo | string | | ||
| idDocIssuer | ISO3166-1 alpha-2 or ISO3166-2 if applicable | | ||
| idDocIssuedAt | ISO8601 YYYYMMDD | | ||
| idDocExpiresAt | ISO8601 YYYYMMDD | | ||
| nationalIdNo | string | | ||
| taxIdNo | string | | ||
The first parameter of the statement builder is a boolean, which defaults to true, that specifies whether the statement should be checked while being built. | ||
It checks that: | ||
- The used attribute tag is a known one | ||
- There is not multiple statements on the same attribute | ||
- Lower, upper and sets members have the format expected of the attribute | ||
### Minimum Age | ||
There is a helper function for specifying the prover must have some minimum age. | ||
Example: add the statement that the prover must be born at least 18 years old: | ||
```js | ||
statementBuilder.addMinimumAge(18); | ||
``` | ||
### Eu membership | ||
There are helpers for specifying the country of residency or nationality to be one of the EU member states. | ||
```js | ||
statementBuilder.addEUNationality(); | ||
statementBuilder.addEUResidency(); | ||
``` | ||
### Reveal statement | ||
State that a given attribute should be revealed as part of the proof. | ||
```js | ||
statementBuilder.revealAttribute(AttributesKeys.nationality); | ||
``` | ||
### Range statement | ||
State that a given attribute should be between 2 given values. | ||
Example: add the statement that the prover must be born between January 1, 1941 and Februar 2, 2005. | ||
```js | ||
statementBuilder.addRange(AttributesKeys.dob, 19410101, 20050202); | ||
``` | ||
Note that this type of statement is only allowed for the following attributes: | ||
- dob (date of birth) | ||
- idDocIssuedAt | ||
- idDocExpiresAt | ||
### Membership statement | ||
Example: add the statement that the prover's country of residency is France or Spain: | ||
```js | ||
statementBuilder.addMembership(AttributesKeys.CountryOfResidency, ['FR', 'ES']); | ||
``` | ||
Note that this type of statement is only allowed for the following attributes: | ||
- Nationality | ||
- CountryOfResidency | ||
- IdDocIssuer | ||
- IdDocType | ||
### Non membership statement | ||
Example: add the statement that the prover's country of residency not Germany nor Portugal: | ||
```js | ||
statementBuilder.addNonMembership(AttributesKeys.CountryOfResidency, ['DE', 'PT']); | ||
``` | ||
Note that this type of statement is only allowed for the following attributes: | ||
- Nationality | ||
- CountryOfResidency | ||
- IdDocIssuer | ||
- IdDocType | ||
## Verify Statement (verifyIdstatement) | ||
The SDK provides a helper function to verify a statement, that it is well-formed and complies with the current rules. | ||
The function is `verifyIdstatement` and it will throw an error if the statement does not verify. | ||
Example: | ||
```js | ||
const statement = ... | ||
let isValid = true; | ||
try { | ||
verifyIdstatement(statement); | ||
} catch (e) { | ||
// States why the statement is not valid: | ||
console.log(e.message); | ||
isValid = false; | ||
} | ||
``` | ||
## Prove Statement (getIdProof) | ||
The SDK provides a helper function to prove an id statement. | ||
The function is `getIdProof`: | ||
Example: | ||
```js | ||
const statement = ... | ||
const challenge = ... | ||
const proof = getIdProof({ | ||
idObject, | ||
globalContext, | ||
seedAsHex, | ||
net: 'Mainnet', | ||
identityProviderIndex, | ||
identityIndex, | ||
credNumber, | ||
statement, | ||
challenge, | ||
}) | ||
``` | ||
# ConcordiumNodeClient | ||
The SDK provides a gRPC client, which can interact with the [Concordium Node](https://github.com/Concordium/concordium-node) | ||
For an overview of the endpoints, [check here](../../docs/gRPC.md). | ||
To create a client, the helper functions in the node or web sdk should be used as they use the appropriate transport. | ||
The [nodejs SDK uses a regular gRPC transport](../nodejs#ConcordiumNodeClient), while the [web SDK uses a gRPC-web transport](../web#ConcordiumNodeClient). | ||
# JSON-RPC client | ||
> :warning: **The JSON-RPC client has been deprecated**: the gRPC client should be used instead to communicate directly with a node | ||
The SDK also provides a JSON-RPC client, [check here for the documentation](../../docs/JSON-RPC.md). | ||
# CIS-2 contract | ||
The SDK provides a class for interacting with smart contracts adhering to the [CIS-2 standard](https://proposals.concordium.software/CIS/cis-2.html). | ||
For an overview of the class, [check here](../../docs/CIS2Contract.md). | ||
Please see the | ||
[documentation](https://developer.concordium.software/concordium-node-sdk-js/index.html) | ||
for more information |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
1271307
1.13%108
1.89%29453
3.66%8
-99.09%1
Infinity%+ Added
- Removed