diff --git a/examples/ccd-js-gen/wCCD/generate.ts b/examples/ccd-js-gen/wCCD/generate.ts index e00ff31f9..41ff7529a 100644 --- a/examples/ccd-js-gen/wCCD/generate.ts +++ b/examples/ccd-js-gen/wCCD/generate.ts @@ -37,7 +37,7 @@ const grpcClient = new ConcordiumGRPCNodeClient( credentials.createInsecure() ); -const wCCDModuleRef = new SDK.ModuleReference( +const wCCDModuleRef = SDK.ModuleReference.fromHexString( 'cc285180b45d7695db75c29dee004d2e81a1383880c9b122399bea809196c98f' ); diff --git a/examples/client/getBlockItemStatus.ts b/examples/client/getBlockItemStatus.ts index f789f3e73..173625bbb 100644 --- a/examples/client/getBlockItemStatus.ts +++ b/examples/client/getBlockItemStatus.ts @@ -1,5 +1,9 @@ import { parseEndpoint } from '../shared/util.js'; -import { BlockItemStatus, TransactionHash } from '@concordium/web-sdk'; +import { + BlockItemStatus, + CcdAmount, + TransactionHash, +} from '@concordium/web-sdk'; import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs'; import { credentials } from '@grpc/grpc-js'; @@ -86,7 +90,7 @@ const client = new ConcordiumGRPCNodeClient( case 'transfer': // The transaction is a simple transfer const { amount, to } = summary.transfer; - const ccdAmount = Number(amount / 1000000n); + const ccdAmount = CcdAmount.toCcd(amount); console.log(ccdAmount, 'CCD sent to', to); break; case 'failed': diff --git a/examples/client/getEmbeddedSchema.ts b/examples/client/getEmbeddedSchema.ts index 0d5bc0417..dcb81bb27 100644 --- a/examples/client/getEmbeddedSchema.ts +++ b/examples/client/getEmbeddedSchema.ts @@ -53,7 +53,7 @@ const client = new ConcordiumGRPCNodeClient( (async () => { // #region documentation-snippet - const moduleRef = new ModuleReference(cli.flags.module); + const moduleRef = ModuleReference.fromHexString(cli.flags.module); const schema = await client.getEmbeddedSchema(moduleRef); // #endregion documentation-snippet diff --git a/examples/client/getModuleSource.ts b/examples/client/getModuleSource.ts index 9182763b7..6d53dd54c 100644 --- a/examples/client/getModuleSource.ts +++ b/examples/client/getModuleSource.ts @@ -61,7 +61,7 @@ const client = new ConcordiumGRPCNodeClient( (async () => { // #region documentation-snippet - const ref = new ModuleReference(cli.flags.module); + const ref = ModuleReference.fromHexString(cli.flags.module); const blockHash = cli.flags.block === undefined ? undefined diff --git a/examples/client/getPassiveDelegationInfo.ts b/examples/client/getPassiveDelegationInfo.ts index 5633d5b0a..175947b59 100644 --- a/examples/client/getPassiveDelegationInfo.ts +++ b/examples/client/getPassiveDelegationInfo.ts @@ -1,5 +1,9 @@ import { parseEndpoint } from '../shared/util.js'; -import { BlockHash, PassiveDelegationStatus } from '@concordium/web-sdk'; +import { + BlockHash, + CcdAmount, + PassiveDelegationStatus, +} from '@concordium/web-sdk'; import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs'; import { credentials } from '@grpc/grpc-js'; @@ -56,11 +60,11 @@ const client = new ConcordiumGRPCNodeClient( console.log( 'CCD provided by the delegators to the pool:', - passiveDelegationInfo.delegatedCapital / 1000000n + CcdAmount.toCcd(passiveDelegationInfo.delegatedCapital) ); console.log( 'Total capital in CCD of ALL pools:', - passiveDelegationInfo.allPoolTotalCapital / 1000000n + CcdAmount.toCcd(passiveDelegationInfo.allPoolTotalCapital) ); console.log('Pool commision rates:', passiveDelegationInfo.commissionRates); // #endregion documentation-snippet diff --git a/examples/client/getPoolInfo.ts b/examples/client/getPoolInfo.ts index 4e47c8ee5..70c1636ae 100644 --- a/examples/client/getPoolInfo.ts +++ b/examples/client/getPoolInfo.ts @@ -1,5 +1,5 @@ import { parseEndpoint } from '../shared/util.js'; -import { BakerPoolStatus, BlockHash } from '@concordium/web-sdk'; +import { BakerPoolStatus, BlockHash, CcdAmount } from '@concordium/web-sdk'; import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs'; import { credentials } from '@grpc/grpc-js'; @@ -67,15 +67,15 @@ const client = new ConcordiumGRPCNodeClient( console.log('Baker address:', bakerPool.bakerAddress); console.log( 'CCD provided by the baker to the pool:', - bakerPool.bakerEquityCapital / 1000000n + CcdAmount.toCcd(bakerPool.bakerEquityCapital) ); console.log( 'CCD provided by the delegators to the pool:', - bakerPool.delegatedCapital / 1000000n + CcdAmount.toCcd(bakerPool.delegatedCapital) ); console.log( 'Total capital in CCD of ALL pools:', - bakerPool.allPoolTotalCapital / 1000000n + CcdAmount.toCcd(bakerPool.allPoolTotalCapital) ); console.log('Pool commision rates:', bakerPool.poolInfo.commissionRates); // #endregion documentation-snippet diff --git a/examples/client/invokeContract.ts b/examples/client/invokeContract.ts index 63661f1cd..b7b9936c8 100644 --- a/examples/client/invokeContract.ts +++ b/examples/client/invokeContract.ts @@ -100,7 +100,7 @@ const client = new ConcordiumGRPCNodeClient( ? AccountAddress.fromBase58(cli.flags.invoker) : undefined; const amount = cli.flags.amount - ? new CcdAmount(BigInt(cli.flags.amount)) + ? CcdAmount.fromMicroCcd(cli.flags.amount) : undefined; const parameter = cli.flags.parameter ? Parameter.fromHexString(cli.flags.parameter) diff --git a/examples/common/bakerAdd.ts b/examples/common/bakerAdd.ts index 873861374..e37f41dbe 100644 --- a/examples/common/bakerAdd.ts +++ b/examples/common/bakerAdd.ts @@ -75,7 +75,7 @@ const client = new ConcordiumGRPCNodeClient( const signer = buildAccountSigner(wallet); const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender, }; @@ -83,7 +83,7 @@ const client = new ConcordiumGRPCNodeClient( const bakerKeys = generateBakerKeys(sender); const configureBakerPayload: ConfigureBakerPayload = { - stake: new CcdAmount(BigInt(cli.flags.stake)), + stake: CcdAmount.fromMicroCcd(cli.flags.stake), restakeEarnings: true, openForDelegation: OpenStatus.OpenForAll, keys: bakerKeys, diff --git a/examples/common/bakerRemove.ts b/examples/common/bakerRemove.ts index 5c55fc064..8c109ca28 100644 --- a/examples/common/bakerRemove.ts +++ b/examples/common/bakerRemove.ts @@ -66,13 +66,13 @@ const client = new ConcordiumGRPCNodeClient( const signer = buildAccountSigner(wallet); const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender, }; const configureBakerPayload: ConfigureBakerPayload = { - stake: new CcdAmount(0n), + stake: CcdAmount.zero(), }; const configureBakerAccountTransaction: AccountTransaction = { diff --git a/examples/common/delegationAdd.ts b/examples/common/delegationAdd.ts index 955a0cf0b..480f34749 100644 --- a/examples/common/delegationAdd.ts +++ b/examples/common/delegationAdd.ts @@ -80,13 +80,13 @@ const client = new ConcordiumGRPCNodeClient( const signer = buildAccountSigner(wallet); const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender: sender, }; const configureDelegationPayload: ConfigureDelegationPayload = { - stake: new CcdAmount(BigInt(cli.flags.stake)), + stake: CcdAmount.fromMicroCcd(cli.flags.stake), delegationTarget: { delegateType: DelegationTargetType.PassiveDelegation, }, diff --git a/examples/common/delegationRemove.ts b/examples/common/delegationRemove.ts index 0571aa94a..9b8a495ce 100644 --- a/examples/common/delegationRemove.ts +++ b/examples/common/delegationRemove.ts @@ -65,13 +65,13 @@ const client = new ConcordiumGRPCNodeClient( const sender = AccountAddress.fromBase58(wallet.value.address); const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender: sender, }; const configureDelegationPayload: ConfigureDelegationPayload = { - stake: new CcdAmount(0n), + stake: CcdAmount.zero(), }; const configureDelegationTransaction: AccountTransaction = { diff --git a/examples/common/deployModule.ts b/examples/common/deployModule.ts index 0492cebb5..d740412cd 100644 --- a/examples/common/deployModule.ts +++ b/examples/common/deployModule.ts @@ -81,7 +81,7 @@ const client = new ConcordiumGRPCNodeClient( }; const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender, }; diff --git a/examples/common/simpleTransfer.ts b/examples/common/simpleTransfer.ts index 86a9afa7c..1b3417046 100644 --- a/examples/common/simpleTransfer.ts +++ b/examples/common/simpleTransfer.ts @@ -89,7 +89,7 @@ const client = new ConcordiumGRPCNodeClient( ); const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: nextNonce.nonce, sender, }; @@ -98,13 +98,13 @@ const client = new ConcordiumGRPCNodeClient( let simpleTransfer = undefined; if (cli.flags.memo) { simpleTransfer = { - amount: new CcdAmount(BigInt(cli.flags.amount)), + amount: CcdAmount.fromMicroCcd(cli.flags.amount), toAddress, memo: new DataBlob(Buffer.from(cli.flags.memo, 'hex')), }; } else { simpleTransfer = { - amount: new CcdAmount(BigInt(cli.flags.amount)), + amount: CcdAmount.fromMicroCcd(cli.flags.amount), toAddress, }; } diff --git a/examples/composed-examples/initAndUpdateContract.ts b/examples/composed-examples/initAndUpdateContract.ts index 6bade971b..da2f3df8b 100644 --- a/examples/composed-examples/initAndUpdateContract.ts +++ b/examples/composed-examples/initAndUpdateContract.ts @@ -80,7 +80,7 @@ const client = new ConcordiumGRPCNodeClient( const sender = AccountAddress.fromBase58(wallet.value.address); const signer = buildAccountSigner(wallet); - const moduleRef = new ModuleReference( + const moduleRef = ModuleReference.fromHexString( '44434352ddba724930d6b1b09cd58bd1fba6ad9714cf519566d5fe72d80da0d1' ); const maxCost = Energy.create(30000); @@ -95,7 +95,7 @@ const client = new ConcordiumGRPCNodeClient( // #region documentation-snippet-init-contract const initHeader: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender, }; @@ -107,7 +107,7 @@ const client = new ConcordiumGRPCNodeClient( ); const initPayload: InitContractPayload = { - amount: new CcdAmount(0n), + amount: CcdAmount.zero(), moduleRef: moduleRef, initName: contractName, param: initParams, @@ -146,7 +146,7 @@ const client = new ConcordiumGRPCNodeClient( // #region documentation-snippet-update-contract const updateHeader: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: TransactionExpiry.futureMinutes(60), nonce: (await client.getNextAccountNonce(sender)).nonce, sender, }; @@ -159,7 +159,7 @@ const client = new ConcordiumGRPCNodeClient( ); const updatePayload: UpdateContractPayload = { - amount: new CcdAmount(0n), + amount: CcdAmount.zero(), address: unwrap(contractAddress), receiveName, message: updateParams, diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index 6a968ad72..0156e1f1f 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -42,6 +42,9 @@ The API now uses dedicated types instead of language primitives: - Use `SequenceNumber` (formerly called nonce) instead of a bigint. Use `SequenceNumber.create()` to construct it. - Use `Timestamp` instead of a bigint. Can be constructed using `Timestamp.fromMillis()`. - Use `Duration` instead of a bigint. Can be constructed using `Duration.fromMillis()`. +- Use `CcdAmount` instead of a bigint. Can be constructed using `CcdAmount.fromMicroCcd()`. +- Use `TransactionExpiry` instead of a Date object. Can be constructed using `TransactionExpiry.fromDate()`. +- Use `ModuleReference` instead of a string with hex encoding. Can be constructed using `ModuleReference.fromHexString('')`. Several types have been replaced with a module containing the type itself together with functions for constructing and converting the type: - `AccountAddress` is now a module with functions related to account addresses: @@ -54,8 +57,18 @@ Several types have been replaced with a module containing the type itself togeth - `CredentialRegistrationId` is now a module with functions related to credential registration IDs: - To refer to `CredentialRegistrationId` as a type use `CredentialRegistrationId.Type`. - Constructing `new CredentialRegistrationId("")` is now `CredentialRegistrationId.fromHexString("")`. +- `CcdAmount` is now a module with functions related to amounts of CCDs: + - To refer to `CcdAmount` as a type use `CcdAmount.Type`. + - Constructing `new CcdAmount()` is now `CcdAmount.fromMicroCcd()`. + - The methods `toMicroCcd` and `toCcd` are now functions refered to as `CcdAmount.toMicroCcd` and `CcdAmount.toCcd` respectively. +- `TransactionExpiry` is now a module with functions related to amounts of expiry time of transactions: + - To refer to `TransactionExpiry` as a type use `TransactionExpiry.Type`. + - Constructing `new TransactionExpiry(, )` is now `TransactionExpiry.fromDate()`, and the check of being a time in the future is removed and done when sending the transaction instead. +- `ModuleReference` is now a module with functions related to references to smart contract modules: + - To refer to `ModuleReference` as a type use `ModuleReference.Type`. + - Constructing `new ModuleReference("")` is now `ModuleReference.fromHexString("")`. + - The static method `ModuleReference.fromBytes` is now `ModuleReference.fromBuffer`. - Removed `JsonRpcClient` and types and functionality associated solely with this class. - - Renamed `AccountSequenceNumber` module to `SequenceNumber`. - Fix type for `TranferredEvent` from `ContractTraceEvent` to only be from contract addresses to account addresses. diff --git a/packages/sdk/src/GenericContract.ts b/packages/sdk/src/GenericContract.ts index 7b175242c..1af80ca60 100644 --- a/packages/sdk/src/GenericContract.ts +++ b/packages/sdk/src/GenericContract.ts @@ -21,9 +21,9 @@ import * as ReceiveName from './types/ReceiveName.js'; import * as Parameter from './types/Parameter.js'; import * as Energy from './types/Energy.js'; import * as TransactionHash from './types/TransactionHash.js'; -import { CcdAmount } from './types/ccdAmount.js'; -import { TransactionExpiry } from './types/transactionExpiry.js'; -import { ModuleReference } from './types/moduleReference.js'; +import * as CcdAmount from './types/CcdAmount.js'; +import * as TransactionExpiry from './types/TransactionExpiry.js'; +import * as ModuleReference from './types/ModuleReference.js'; import * as BlockHash from './types/BlockHash.js'; import * as ReturnValue from './types/ReturnValue.js'; @@ -31,12 +31,12 @@ import * as ReturnValue from './types/ReturnValue.js'; * Metadata necessary for smart contract transactions */ export type ContractTransactionMetadata = { - /** Amount (in microCCD) to include in the transaction. Defaults to 0n */ - amount?: bigint; + /** Amount to include in the transaction. Defaults to 0 */ + amount?: CcdAmount.Type; /** The sender address of the transaction */ senderAddress: AccountAddress.Type; /** Expiry date of the transaction. Defaults to 5 minutes in the future */ - expiry?: Date; + expiry?: TransactionExpiry.Type; /** Max energy to be used for the transaction */ energy: Energy.Type; }; @@ -92,9 +92,8 @@ export type ContractUpdateTransactionWithSchema< /** * Default expiry date used for contract update transactions. */ -export function getContractUpdateDefaultExpiryDate(): Date { - const future5Minutes = Date.now() + 5 * 60 * 1000; - return new Date(future5Minutes); +export function getContractUpdateDefaultExpiryDate(): TransactionExpiry.Type { + return TransactionExpiry.futureMinutes(5); } /** @@ -154,7 +153,7 @@ export type ContractCheckOnChainOptions = { * The expected module reference to be used by the contract instance. * When not provided no check is done against the module reference. */ - moduleReference?: ModuleReference; + moduleReference?: ModuleReference.Type; }; /** @@ -334,7 +333,10 @@ class ContractBase { public createUpdateTransaction( entrypoint: EntrypointName.Type, serializeInput: (input: T) => ArrayBuffer, - { amount = 0n, energy }: CreateContractTransactionMetadata, + { + amount = CcdAmount.zero(), + energy, + }: CreateContractTransactionMetadata, input: T, inputJsonFormatter?: (input: T) => J ): @@ -343,7 +345,7 @@ class ContractBase { const parameter = Parameter.fromBuffer(serializeInput(input)); const payload: UpdateContractPayload = { - amount: new CcdAmount(amount), + amount, address: this.contractAddress, receiveName: ReceiveName.create(this.contractName, entrypoint), maxContractExecutionEnergy: energy, @@ -408,7 +410,7 @@ class ContractBase { senderAddress ); const header = { - expiry: new TransactionExpiry(expiry), + expiry, nonce: nonce, sender: senderAddress, }; diff --git a/packages/sdk/src/accountTransactions.ts b/packages/sdk/src/accountTransactions.ts index c777e3086..4381e54b0 100644 --- a/packages/sdk/src/accountTransactions.ts +++ b/packages/sdk/src/accountTransactions.ts @@ -26,7 +26,7 @@ import { } from './types.js'; import * as AccountAddress from './types/AccountAddress.js'; import { DataBlob } from './types/DataBlob.js'; -import { CcdAmount } from './types/ccdAmount.js'; +import * as CcdAmount from './types/CcdAmount.js'; import { Cursor } from './deserializationHelpers.js'; import * as ReceiveName from './types/ReceiveName.js'; import * as Parameter from './types/Parameter.js'; @@ -56,7 +56,7 @@ export class SimpleTransferHandler const toAddress = AccountAddress.fromBuffer( Buffer.from(serializedPayload.read(32)) ); - const amount = new CcdAmount( + const amount = CcdAmount.fromMicroCcd( serializedPayload.read(8).readBigUInt64BE(0) ); return { @@ -89,7 +89,7 @@ export class SimpleTransferWithMemoHandler const memo = new DataBlob( Buffer.from(serializedPayload.read(memoLength)) ); - const amount = new CcdAmount( + const amount = CcdAmount.fromMicroCcd( serializedPayload.read(8).readBigUInt64BE(0) ); return { diff --git a/packages/sdk/src/cis4/CIS4Contract.ts b/packages/sdk/src/cis4/CIS4Contract.ts index 77e6da61d..a74bd2596 100644 --- a/packages/sdk/src/cis4/CIS4Contract.ts +++ b/packages/sdk/src/cis4/CIS4Contract.ts @@ -37,6 +37,7 @@ import { } from './util.js'; import * as BlockHash from '../types/BlockHash.js'; import * as TransactionHash from '../types/TransactionHash.js'; +import * as TransactionExpiry from '../types/TransactionExpiry.js'; type Views = | 'credentialEntry' @@ -588,7 +589,9 @@ export class CIS4Contract extends CISContract { metadata, credHolderSigner, nonce, - metadata.expiry ?? getContractUpdateDefaultExpiryDate(), + TransactionExpiry.toDate( + metadata.expiry ?? getContractUpdateDefaultExpiryDate() + ), reason ); return this.sendUpdateTransaction(transaction, metadata, signer); @@ -679,7 +682,9 @@ export class CIS4Contract extends CISContract { revokerSigner, credentialPubKey, nonce, - metadata.expiry ?? getContractUpdateDefaultExpiryDate(), + TransactionExpiry.toDate( + metadata.expiry ?? getContractUpdateDefaultExpiryDate() + ), reason ); return this.sendUpdateTransaction(transaction, metadata, signer); diff --git a/packages/sdk/src/deserialization.ts b/packages/sdk/src/deserialization.ts index 68ad74259..fd5072683 100644 --- a/packages/sdk/src/deserialization.ts +++ b/packages/sdk/src/deserialization.ts @@ -8,7 +8,7 @@ import { } from './types.js'; import * as AccountAddress from './types/AccountAddress.js'; import * as AccountSequenceNumber from './types/SequenceNumber.js'; -import { TransactionExpiry } from './types/transactionExpiry.js'; +import * as TransactionExpiry from './types/TransactionExpiry.js'; /** * Reads an unsigned 8-bit integer from the given {@link Cursor}. @@ -71,8 +71,7 @@ function deserializeTransactionHeader( // payloadSize serializedHeader.read(4).readUInt32BE(0); const expiry = TransactionExpiry.fromEpochSeconds( - serializedHeader.read(8).readBigUInt64BE(0), - true + serializedHeader.read(8).readBigUInt64BE(0) ); return { sender, diff --git a/packages/sdk/src/energyCost.ts b/packages/sdk/src/energyCost.ts index 2261eb0f6..d08c03b98 100644 --- a/packages/sdk/src/energyCost.ts +++ b/packages/sdk/src/energyCost.ts @@ -7,6 +7,7 @@ import { Ratio, } from './types.js'; import * as Energy from './types/Energy.js'; +import * as CcdAmount from './types/CcdAmount.js'; /** * These constants must be consistent with constA and constB in: @@ -80,9 +81,11 @@ export function getExchangeRate({ * Given an NRG amount and the current blockchain parameters, this returns the corresponding amount in microCcd. */ export function convertEnergyToMicroCcd( - cost: bigint, + cost: Energy.Type, chainParameters: ChainParameters -): bigint { +): CcdAmount.Type { const rate = getExchangeRate(chainParameters); - return collapseRatio(multiplyRatio(rate, cost)); + return CcdAmount.fromMicroCcd( + collapseRatio(multiplyRatio(rate, cost.value)) + ); } diff --git a/packages/sdk/src/grpc/GRPCClient.ts b/packages/sdk/src/grpc/GRPCClient.ts index 0ca7db5c7..a79a14dd1 100644 --- a/packages/sdk/src/grpc/GRPCClient.ts +++ b/packages/sdk/src/grpc/GRPCClient.ts @@ -35,9 +35,9 @@ import type { BlockItemStatus, BlockItemSummary, } from '../types/blockItemSummary.js'; -import { ModuleReference } from '../types/moduleReference.js'; +import * as ModuleReference from '../types/ModuleReference.js'; import { DEFAULT_INVOKE_ENERGY } from '../constants.js'; -import { TransactionExpiry } from '../types/transactionExpiry.js'; +import * as TransactionExpiry from '../types/TransactionExpiry.js'; import * as BlockHash from '../types/BlockHash.js'; import * as TransactionHash from '../types/TransactionHash.js'; import * as ContractAddress from '../types/ContractAddress.js'; @@ -191,7 +191,7 @@ export class ConcordiumGRPCClient { * @throws An error of type `RpcError` if not found in the block. */ async getModuleSource( - moduleRef: ModuleReference, + moduleRef: ModuleReference.Type, blockHash?: BlockHash.Type ): Promise { const moduleSourceRequest: v2.ModuleSourceRequest = { @@ -229,7 +229,7 @@ export class ConcordiumGRPCClient { * @throws If the module or schema cannot be parsed */ async getEmbeddedSchema( - moduleRef: ModuleReference, + moduleRef: ModuleReference.Type, blockHash?: BlockHash.Type ): Promise { const versionedSource = await this.getModuleSource( @@ -375,12 +375,19 @@ export class ConcordiumGRPCClient { const transactionSignature: v2.AccountTransactionSignature = translate.accountTransactionSignatureToV2(signature); + if (TransactionExpiry.toDate(header.expiry) < new Date()) { + throw new Error( + 'A transaction expiry is not allowed to be in the past: ' + + TransactionExpiry.toDate(header.expiry) + ); + } + // Put together sendBlockItemRequest const convertedHeader: v2.AccountTransactionHeader = { sender: AccountAddress.toProto(header.sender), sequenceNumber: SequenceNumber.toProto(header.nonce), energyAmount: Energy.toProto(energyAmount), - expiry: { value: header.expiry.expiryEpochSeconds }, + expiry: TransactionExpiry.toProto(header.expiry), }; const accountTransaction: v2.AccountTransaction = { signature: transactionSignature, @@ -417,12 +424,10 @@ export class ConcordiumGRPCClient { */ async sendCredentialDeploymentTransaction( rawPayload: Uint8Array, - expiry: TransactionExpiry + expiry: TransactionExpiry.Type ): Promise { const credentialDeployment: v2.CredentialDeployment = { - messageExpiry: { - value: expiry.expiryEpochSeconds, - }, + messageExpiry: TransactionExpiry.toProto(expiry), payload: { oneofKind: 'rawPayload', rawPayload, diff --git a/packages/sdk/src/grpc/translation.ts b/packages/sdk/src/grpc/translation.ts index 272c50257..f4d646cae 100644 --- a/packages/sdk/src/grpc/translation.ts +++ b/packages/sdk/src/grpc/translation.ts @@ -4,8 +4,8 @@ import bs58check from 'bs58check'; import * as v1 from '../types.js'; import * as v2 from '../grpc-api/v2/concordium/types.js'; import { mapRecord, unwrap } from '../util.js'; -import { ModuleReference } from '../types/moduleReference.js'; -import { CcdAmount } from '../types/ccdAmount.js'; +import * as ModuleReference from '../types/ModuleReference.js'; +import * as CcdAmount from '../types/CcdAmount.js'; import * as AccountAddress from '../types/AccountAddress.js'; import * as BlockHash from '../types/BlockHash.js'; import * as ReceiveName from '../types/ReceiveName.js'; @@ -38,7 +38,7 @@ export function unwrapToBase58( function trRelease(release: v2.Release): v1.ReleaseScheduleWithTransactions { return { timestamp: trTimestamp(release.timestamp), - amount: unwrap(release.amount?.value), + amount: CcdAmount.fromProto(unwrap(release.amount)), transactions: release.transactions.map(unwrapValToHex), }; } @@ -46,7 +46,7 @@ function trRelease(release: v2.Release): v1.ReleaseScheduleWithTransactions { function trNewRelease(release: v2.NewRelease): v1.ReleaseSchedule { return { timestamp: trTimestamp(release.timestamp), - amount: unwrap(release.amount?.value), + amount: CcdAmount.fromProto(unwrap(release.amount)), }; } @@ -213,7 +213,7 @@ function trDelegator( ): v1.AccountDelegationDetails { return { restakeEarnings: deleg.restakeEarnings, - stakedAmount: unwrap(deleg.stakedAmount?.value), + stakedAmount: CcdAmount.fromProto(unwrap(deleg.stakedAmount)), delegationTarget: trDelegatorTarget(unwrap(deleg.target)), // Set the following value if deleg.pendingChange is set to true ...(deleg.pendingChange && { @@ -249,7 +249,7 @@ function trBaker(baker: v2.AccountStakingInfo_Baker): v1.AccountBakerDetails { bakerAggregationVerifyKey: unwrapValToHex(bakerInfo?.aggregationKey), bakerElectionVerifyKey: unwrapValToHex(baker.bakerInfo?.electionKey), bakerSignatureVerifyKey: unwrapValToHex(bakerInfo?.signatureKey), - stakedAmount: unwrap(baker.stakedAmount?.value), + stakedAmount: CcdAmount.fromProto(unwrap(baker.stakedAmount)), // Set the following value if baker.pendingChange is set to true ...(baker.pendingChange && { pendingChange: trPendingChange(baker.pendingChange), @@ -327,8 +327,8 @@ function transPoolPendingChange( v1.BakerPoolPendingChangeType.ReduceBakerCapital, // TODO ensure units are aligned effectiveTime: trTimestamp(change.change.reduce.effectiveTime), - bakerEquityCapital: unwrap( - change.change.reduce.reducedEquityCapital?.value + bakerEquityCapital: CcdAmount.fromProto( + unwrap(change.change.reduce.reducedEquityCapital) ), }; } @@ -362,11 +362,15 @@ function transPaydayStatus( return { blocksBaked: status.blocksBaked, finalizationLive: status.finalizationLive, - transactionFeesEarned: unwrap(status.transactionFeesEarned?.value), - effectiveStake: unwrap(status.effectiveStake?.value), + transactionFeesEarned: CcdAmount.fromProto( + unwrap(status.transactionFeesEarned) + ), + effectiveStake: CcdAmount.fromProto(unwrap(status.effectiveStake)), lotteryPower: status.lotteryPower, - bakerEquityCapital: unwrap(status.bakerEquityCapital?.value), - delegatedCapital: unwrap(status.delegatedCapital?.value), + bakerEquityCapital: CcdAmount.fromProto( + unwrap(status.bakerEquityCapital) + ), + delegatedCapital: CcdAmount.fromProto(unwrap(status.delegatedCapital)), }; } @@ -385,14 +389,14 @@ export function accountInfo(acc: v2.AccountInfo): v1.AccountInfo { ...(aggAmount && { aggregatedAmount: unwrapToHex(aggAmount) }), }; const releaseSchedule = { - total: unwrap(acc.schedule?.total?.value), + total: CcdAmount.fromProto(unwrap(acc.schedule?.total)), schedule: unwrap(acc.schedule?.schedules).map(trRelease), }; const accInfoCommon: v1.AccountInfoSimple = { type: v1.AccountInfoType.Simple, accountAddress: AccountAddress.fromProto(unwrap(acc.address)), accountNonce: SequenceNumber.fromProto(unwrap(acc.sequenceNumber)), - accountAmount: unwrap(acc.amount?.value), + accountAmount: CcdAmount.fromProto(unwrap(acc.amount)), accountIndex: unwrap(acc.index?.value), accountThreshold: unwrap(acc.threshold?.value), accountEncryptionKey: unwrapValToHex(acc.encryptionKey), @@ -446,7 +450,9 @@ function trChainParametersV0(v0: v2.ChainParametersV0): v1.ChainParametersV0 { level2Keys: trAuthorizationsV0(unwrap(v0.level2Keys)), electionDifficulty: trAmountFraction(v0.electionDifficulty?.value), bakerCooldownEpochs: unwrap(v0.bakerCooldownEpochs?.value), - minimumThresholdForBaking: unwrap(v0.minimumThresholdForBaking?.value), + minimumThresholdForBaking: CcdAmount.fromProto( + unwrap(v0.minimumThresholdForBaking) + ), rewardParameters: { version: 0, ...commonRewardParameters, @@ -513,8 +519,8 @@ function trChainParametersV1( transactionCommissionRange: translateCommissionRange( params.poolParameters?.commissionBounds?.transaction ), - minimumEquityCapital: unwrap( - params.poolParameters?.minimumEquityCapital?.value + minimumEquityCapital: CcdAmount.fromProto( + unwrap(params.poolParameters?.minimumEquityCapital) ), capitalBound: trAmountFraction( params.poolParameters?.capitalBound?.value @@ -585,8 +591,8 @@ function trChainParametersV2( transactionCommissionRange: translateCommissionRange( params.poolParameters?.commissionBounds?.transaction ), - minimumEquityCapital: unwrap( - params.poolParameters?.minimumEquityCapital?.value + minimumEquityCapital: CcdAmount.fromProto( + unwrap(params.poolParameters?.minimumEquityCapital) ), capitalBound: trAmountFraction( params.poolParameters?.capitalBound?.value @@ -664,15 +670,19 @@ export function bakerPoolInfo(info: v2.PoolInfoResponse): v1.BakerPoolStatus { poolType: v1.PoolStatusType.BakerPool, bakerId: unwrap(info.baker?.value), bakerAddress: AccountAddress.fromProto(unwrap(info.address)), - bakerEquityCapital: unwrap(info.equityCapital?.value), - delegatedCapital: unwrap(info.delegatedCapital?.value), - delegatedCapitalCap: unwrap(info.delegatedCapitalCap?.value), + bakerEquityCapital: CcdAmount.fromProto(unwrap(info.equityCapital)), + delegatedCapital: CcdAmount.fromProto(unwrap(info.delegatedCapital)), + delegatedCapitalCap: CcdAmount.fromProto( + unwrap(info.delegatedCapitalCap) + ), poolInfo: transPoolInfo(unwrap(info?.poolInfo)), bakerStakePendingChange: transPoolPendingChange( info.equityPendingChange ), currentPaydayStatus: transPaydayStatus(info.currentPaydayInfo), - allPoolTotalCapital: unwrap(info.allPoolTotalCapital?.value), + allPoolTotalCapital: CcdAmount.fromProto( + unwrap(info.allPoolTotalCapital) + ), }; } @@ -681,15 +691,17 @@ export function passiveDelegationInfo( ): v1.PassiveDelegationStatus { return { poolType: v1.PoolStatusType.PassiveDelegation, - delegatedCapital: unwrap(info.delegatedCapital?.value), + delegatedCapital: CcdAmount.fromProto(unwrap(info.delegatedCapital)), commissionRates: trCommissionRates(info.commissionRates), - currentPaydayTransactionFeesEarned: unwrap( - info.currentPaydayTransactionFeesEarned?.value + currentPaydayTransactionFeesEarned: CcdAmount.fromProto( + unwrap(info.currentPaydayTransactionFeesEarned) ), - currentPaydayDelegatedCapital: unwrap( - info.currentPaydayDelegatedCapital?.value + currentPaydayDelegatedCapital: CcdAmount.fromProto( + unwrap(info.currentPaydayDelegatedCapital) + ), + allPoolTotalCapital: CcdAmount.fromProto( + unwrap(info.allPoolTotalCapital) ), - allPoolTotalCapital: unwrap(info.allPoolTotalCapital?.value), }; } @@ -704,13 +716,17 @@ export function tokenomicsInfo(info: v2.TokenomicsInfo): v1.RewardStatus { return { version: 0, protocolVersion: translateProtocolVersion(v0.protocolVersion), - totalAmount: unwrap(v0.totalAmount?.value), - totalEncryptedAmount: unwrap(v0.totalEncryptedAmount?.value), - bakingRewardAccount: unwrap(v0.bakingRewardAccount?.value), - finalizationRewardAccount: unwrap( - v0.finalizationRewardAccount?.value + totalAmount: CcdAmount.fromProto(unwrap(v0.totalAmount)), + totalEncryptedAmount: CcdAmount.fromProto( + unwrap(v0.totalEncryptedAmount) + ), + bakingRewardAccount: CcdAmount.fromProto( + unwrap(v0.bakingRewardAccount) ), - gasAccount: unwrap(v0.gasAccount?.value), + finalizationRewardAccount: CcdAmount.fromProto( + unwrap(v0.finalizationRewardAccount) + ), + gasAccount: CcdAmount.fromProto(unwrap(v0.gasAccount)), }; } case 'v1': { @@ -718,19 +734,25 @@ export function tokenomicsInfo(info: v2.TokenomicsInfo): v1.RewardStatus { return { version: 1, protocolVersion: translateProtocolVersion(v1.protocolVersion), - totalAmount: unwrap(v1.totalAmount?.value), - totalEncryptedAmount: unwrap(v1.totalEncryptedAmount?.value), - bakingRewardAccount: unwrap(v1.bakingRewardAccount?.value), - finalizationRewardAccount: unwrap( - v1.finalizationRewardAccount?.value + totalAmount: CcdAmount.fromProto(unwrap(v1.totalAmount)), + totalEncryptedAmount: CcdAmount.fromProto( + unwrap(v1.totalEncryptedAmount) + ), + bakingRewardAccount: CcdAmount.fromProto( + unwrap(v1.bakingRewardAccount) ), - gasAccount: unwrap(v1.gasAccount?.value), - foundationTransactionRewards: unwrap( - v1.foundationTransactionRewards?.value + finalizationRewardAccount: CcdAmount.fromProto( + unwrap(v1.finalizationRewardAccount) + ), + gasAccount: CcdAmount.fromProto(unwrap(v1.gasAccount)), + foundationTransactionRewards: CcdAmount.fromProto( + unwrap(v1.foundationTransactionRewards) ), nextPaydayTime: trTimestamp(v1.nextPaydayTime), nextPaydayMintRate: unwrap(v1.nextPaydayMintRate), - totalStakedCapital: unwrap(v1.totalStakedCapital?.value), + totalStakedCapital: CcdAmount.fromProto( + unwrap(v1.totalStakedCapital) + ), }; } case undefined: @@ -847,7 +869,7 @@ function trContractTraceElement( unwrap(element.updated.address) ), instigator: trAddress(unwrap(element.updated.instigator)), - amount: unwrap(element.updated.amount?.value), + amount: CcdAmount.fromProto(unwrap(element.updated.amount)), message: Parameter.fromProto(unwrap(element.updated.parameter)), receiveName: ReceiveName.fromProto( unwrap(element.updated.receiveName) @@ -860,7 +882,7 @@ function trContractTraceElement( from: ContractAddress.fromProto( unwrap(element.transferred.sender) ), - amount: unwrap(element.transferred.amount?.value), + amount: CcdAmount.fromProto(unwrap(element.transferred.amount)), to: AccountAddress.fromProto( unwrap(element.transferred.receiver) ), @@ -912,7 +934,7 @@ function trBakerEvent( signKey: unwrapValToHex(keysEvent?.signKey), electionKey: unwrapValToHex(keysEvent?.electionKey), aggregationKey: unwrapValToHex(keysEvent?.aggregationKey), - stake: unwrap(event.bakerAdded.stake?.value), + stake: CcdAmount.fromProto(unwrap(event.bakerAdded.stake)), restakeEarnings: unwrap(event.bakerAdded.restakeEarnings), }; } @@ -926,14 +948,18 @@ function trBakerEvent( return { tag: v1.TransactionEventTag.BakerStakeIncreased, bakerId: unwrap(event.bakerStakeIncreased.bakerId?.value), - newStake: unwrap(event.bakerStakeIncreased.newStake?.value), + newStake: CcdAmount.fromProto( + unwrap(event.bakerStakeIncreased.newStake) + ), account, }; case 'bakerStakeDecreased': return { tag: v1.TransactionEventTag.BakerStakeDecreased, bakerId: unwrap(event.bakerStakeDecreased.bakerId?.value), - newStake: unwrap(event.bakerStakeDecreased.newStake?.value), + newStake: CcdAmount.fromProto( + unwrap(event.bakerStakeDecreased.newStake) + ), account, }; case 'bakerRestakeEarningsUpdated': { @@ -1041,7 +1067,7 @@ function trDelegationEvent( return { tag: v1.TransactionEventTag.DelegationStakeIncreased, delegatorId: unwrap(stakeIncr.delegatorId?.id?.value), - newStake: unwrap(stakeIncr.newStake?.value), + newStake: CcdAmount.fromProto(unwrap(stakeIncr.newStake)), account, }; } @@ -1050,7 +1076,7 @@ function trDelegationEvent( return { tag: v1.TransactionEventTag.DelegationStakeDecreased, delegatorId: unwrap(stakeDecr.delegatorId?.id?.value), - newStake: unwrap(stakeDecr.newStake?.value), + newStake: CcdAmount.fromProto(unwrap(stakeDecr.newStake)), account, }; } @@ -1187,21 +1213,23 @@ function trRejectReason( return { tag: Tag.InvalidInitMethod, contents: { - moduleRef: unwrapValToHex( - reason.invalidInitMethod.moduleRef + moduleRef: ModuleReference.fromProto( + unwrap(reason.invalidInitMethod.moduleRef) + ), + initName: InitName.fromProto( + unwrap(reason.invalidInitMethod.initName) ), - initName: unwrap(reason.invalidInitMethod.initName?.value), }, }; case 'invalidReceiveMethod': return { tag: Tag.InvalidReceiveMethod, contents: { - moduleRef: unwrapValToHex( - reason.invalidReceiveMethod.moduleRef + moduleRef: ModuleReference.fromProto( + unwrap(reason.invalidReceiveMethod.moduleRef) ), - receiveName: unwrap( - reason.invalidReceiveMethod.receiveName?.value + receiveName: ReceiveName.fromProto( + unwrap(reason.invalidReceiveMethod.receiveName) ), }, }; @@ -1222,7 +1250,9 @@ function trRejectReason( tag: Tag.AmountTooLarge, contents: { address: trAddress(unwrap(reason.amountTooLarge.address)), - amount: unwrap(reason.amountTooLarge.amount?.value), + amount: CcdAmount.fromProto( + unwrap(reason.amountTooLarge.amount) + ), }, }; case 'rejectedInit': @@ -1236,9 +1266,13 @@ function trRejectReason( contractAddress: ContractAddress.fromProto( unwrap(reason.rejectedReceive.contractAddress) ), - receiveName: unwrap(reason.rejectedReceive.receiveName?.value), + receiveName: ReceiveName.fromProto( + unwrap(reason.rejectedReceive.receiveName) + ), rejectReason: unwrap(reason.rejectedReceive.rejectReason), - parameter: unwrapValToHex(reason.rejectedReceive.parameter), + parameter: Parameter.fromProto( + unwrap(reason.rejectedReceive.parameter) + ), }; case 'alreadyABaker': return { @@ -1424,8 +1458,8 @@ function trPoolParametersCpv1Update( poolParams.commissionBounds?.finalization ), }, - minimumEquityCapital: unwrap( - poolParams.minimumEquityCapital?.value + minimumEquityCapital: CcdAmount.fromProto( + unwrap(poolParams.minimumEquityCapital) ), capitalBound: trAmountFraction(poolParams.capitalBound?.value), leverageBound: unwrap(poolParams.leverageBound?.value), @@ -1918,7 +1952,7 @@ function trAccountTransactionSummary( address: ContractAddress.fromProto( unwrap(contractInit.address) ), - amount: unwrap(contractInit.amount?.value), + amount: CcdAmount.fromProto(unwrap(contractInit.amount)), initName: InitName.fromProto(unwrap(contractInit.initName)), events: unwrap(contractInit.events.map(unwrapValToHex)), contractVersion: unwrap(contractInit.contractVersion), @@ -1941,7 +1975,9 @@ function trAccountTransactionSummary( case 'accountTransfer': { const transfer: v1.AccountTransferredEvent = { tag: v1.TransactionEventTag.Transferred, - amount: unwrap(effect.accountTransfer.amount?.value), + amount: CcdAmount.fromProto( + unwrap(effect.accountTransfer.amount) + ), to: AccountAddress.fromProto( unwrap(effect.accountTransfer.receiver) ), @@ -2014,7 +2050,7 @@ function trAccountTransactionSummary( ? v1.TransactionEventTag.BakerStakeIncreased : v1.TransactionEventTag.BakerStakeDecreased, bakerId: unwrap(update?.bakerId?.value), - newStake: unwrap(update?.newStake?.value), + newStake: CcdAmount.fromProto(unwrap(update?.newStake)), account: base.sender, }; return { @@ -2067,7 +2103,7 @@ function trAccountTransactionSummary( const added: v1.EncryptedSelfAmountAddedEvent = { tag: v1.TransactionEventTag.EncryptedSelfAmountAdded, account: AccountAddress.fromProto(unwrap(transfer.account)), - amount: unwrap(transfer.amount?.value), + amount: CcdAmount.fromProto(unwrap(transfer.amount)), newAmount: unwrapValToHex(transfer.newAmount), }; return { @@ -2088,7 +2124,7 @@ function trAccountTransactionSummary( const added: v1.AmountAddedByDecryptionEvent = { tag: v1.TransactionEventTag.AmountAddedByDecryption, account: base.sender, - amount: unwrap(transfer.amount?.value), + amount: CcdAmount.fromProto(unwrap(transfer.amount)), }; return { ...base, @@ -2295,10 +2331,8 @@ function trInstanceInfoCommon( info: v2.InstanceInfo_V0 | v2.InstanceInfo_V1 ): Omit { return { - amount: new CcdAmount(unwrap(info.amount?.value)), - sourceModule: ModuleReference.fromBytes( - Buffer.from(unwrap(info.sourceModule?.value)) - ), + amount: CcdAmount.fromProto(unwrap(info.amount)), + sourceModule: ModuleReference.fromProto(unwrap(info.sourceModule)), owner: AccountAddress.fromBuffer(unwrap(info.owner?.value)), methods: info.methods.map(ReceiveName.fromProto), name: InitName.fromProto(unwrap(info.name)), @@ -2416,7 +2450,7 @@ export function delegatorInfo( ): v1.DelegatorInfo { return { account: AccountAddress.fromProto(unwrap(delegatorInfo.account)), - stake: unwrap(delegatorInfo.stake?.value), + stake: CcdAmount.fromProto(unwrap(delegatorInfo.stake)), ...(delegatorInfo.pendingChange && { pendingChange: trPendingChange(delegatorInfo.pendingChange), }), @@ -2650,8 +2684,8 @@ function trAccountAmount( accountAmount: v2.BlockSpecialEvent_AccountAmounts_Entry ): v1.BlockSpecialEventAccountAmount { return { - account: unwrapToBase58(accountAmount.account), - amount: unwrap(accountAmount.amount?.value), + account: AccountAddress.fromProto(unwrap(accountAmount.account)), + amount: CcdAmount.fromProto(unwrap(accountAmount.amount)), }; } @@ -2666,20 +2700,26 @@ export function blockSpecialEvent( bakingRewards: unwrap( event.bakingRewards.bakerRewards ).entries.map(trAccountAmount), - remainder: unwrap(event.bakingRewards.remainder?.value), + remainder: CcdAmount.fromProto( + unwrap(event.bakingRewards.remainder) + ), }; } case 'mint': { return { tag: 'mint', - mintBakingReward: unwrap(event.mint.mintBakingReward?.value), - mintFinalizationReward: unwrap( - event.mint.mintFinalizationReward?.value + mintBakingReward: CcdAmount.fromProto( + unwrap(event.mint.mintBakingReward) ), - mintPlatformDevelopmentCharge: unwrap( - event.mint.mintPlatformDevelopmentCharge?.value + mintFinalizationReward: CcdAmount.fromProto( + unwrap(event.mint.mintFinalizationReward) + ), + mintPlatformDevelopmentCharge: CcdAmount.fromProto( + unwrap(event.mint.mintPlatformDevelopmentCharge) + ), + foundationAccount: AccountAddress.fromProto( + unwrap(event.mint.foundationAccount) ), - foundationAccount: unwrapToBase58(event.mint.foundationAccount), }; } case 'finalizationRewards': { @@ -2689,69 +2729,85 @@ export function blockSpecialEvent( event.finalizationRewards.finalizationRewards?.entries.map( trAccountAmount ), - remainder: unwrap(event.finalizationRewards.remainder?.value), + remainder: CcdAmount.fromProto( + unwrap(event.finalizationRewards.remainder) + ), }; } case 'blockReward': { return { tag: 'blockReward', - transactionFees: unwrap( - event.blockReward.transactionFees?.value + transactionFees: CcdAmount.fromProto( + unwrap(event.blockReward.transactionFees) + ), + oldGasAccount: CcdAmount.fromProto( + unwrap(event.blockReward.oldGasAccount) ), - oldGasAccount: unwrap(event.blockReward.oldGasAccount?.value), - newGasAccount: unwrap(event.blockReward.newGasAccount?.value), - bakerReward: unwrap(event.blockReward.bakerReward?.value), - foundationCharge: unwrap( - event.blockReward.foundationCharge?.value + newGasAccount: CcdAmount.fromProto( + unwrap(event.blockReward.newGasAccount) + ), + bakerReward: CcdAmount.fromProto( + unwrap(event.blockReward.bakerReward) + ), + foundationCharge: CcdAmount.fromProto( + unwrap(event.blockReward.foundationCharge) + ), + baker: AccountAddress.fromProto( + unwrap(event.blockReward.baker) + ), + foundationAccount: AccountAddress.fromProto( + unwrap(event.blockReward.baker) ), - baker: unwrapToBase58(event.blockReward.baker), - foundationAccount: unwrapToBase58(event.blockReward.baker), }; } case 'paydayFoundationReward': { return { tag: 'paydayFoundationReward', - foundationAccount: unwrapToBase58( - event.paydayFoundationReward.foundationAccount + foundationAccount: AccountAddress.fromProto( + unwrap(event.paydayFoundationReward.foundationAccount) ), - developmentCharge: unwrap( - event.paydayFoundationReward.developmentCharge?.value + developmentCharge: CcdAmount.fromProto( + unwrap(event.paydayFoundationReward.developmentCharge) ), }; } case 'paydayAccountReward': { return { tag: 'paydayAccountReward', - account: unwrapToBase58(event.paydayAccountReward.account), - transactionFees: unwrap( - event.paydayAccountReward.transactionFees?.value + account: AccountAddress.fromProto( + unwrap(event.paydayAccountReward.account) + ), + transactionFees: CcdAmount.fromProto( + unwrap(event.paydayAccountReward.transactionFees) ), - bakerReward: unwrap( - event.paydayAccountReward.bakerReward?.value + bakerReward: CcdAmount.fromProto( + unwrap(event.paydayAccountReward.bakerReward) ), - finalizationReward: unwrap( - event.paydayAccountReward.finalizationReward?.value + finalizationReward: CcdAmount.fromProto( + unwrap(event.paydayAccountReward.finalizationReward) ), }; } case 'blockAccrueReward': { return { tag: 'blockAccrueReward', - transactionFees: unwrap( - event.blockAccrueReward.transactionFees?.value + transactionFees: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.transactionFees) ), - oldGasAccount: unwrap( - event.blockAccrueReward.oldGasAccount?.value + oldGasAccount: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.oldGasAccount) ), - newGasAccount: unwrap( - event.blockAccrueReward.newGasAccount?.value + newGasAccount: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.newGasAccount) ), - bakerReward: unwrap(event.blockAccrueReward.bakerReward?.value), - passiveReward: unwrap( - event.blockAccrueReward.passiveReward?.value + bakerReward: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.bakerReward) ), - foundationCharge: unwrap( - event.blockAccrueReward.foundationCharge?.value + passiveReward: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.passiveReward) + ), + foundationCharge: CcdAmount.fromProto( + unwrap(event.blockAccrueReward.foundationCharge) ), baker: unwrap(event.blockAccrueReward.baker?.value), }; @@ -2760,12 +2816,14 @@ export function blockSpecialEvent( const poolOwner = event.paydayPoolReward.poolOwner?.value; return { tag: 'paydayPoolReward', - transactionFees: unwrap( - event.paydayPoolReward.transactionFees?.value + transactionFees: CcdAmount.fromProto( + unwrap(event.paydayPoolReward.transactionFees) + ), + bakerReward: CcdAmount.fromProto( + unwrap(event.paydayPoolReward.bakerReward) ), - bakerReward: unwrap(event.paydayPoolReward.bakerReward?.value), - finalizationReward: unwrap( - event.paydayPoolReward.finalizationReward?.value + finalizationReward: CcdAmount.fromProto( + unwrap(event.paydayPoolReward.finalizationReward) ), ...(poolOwner !== undefined && { poolOwner }), }; diff --git a/packages/sdk/src/pub/types.ts b/packages/sdk/src/pub/types.ts index 9074e03ea..bdfb45ba1 100644 --- a/packages/sdk/src/pub/types.ts +++ b/packages/sdk/src/pub/types.ts @@ -12,10 +12,7 @@ export { export { encodeHexString } from '../serializationHelpers.js'; export { sha256 } from '../hash.js'; -export { CcdAmount } from '../types/ccdAmount.js'; -export { TransactionExpiry } from '../types/transactionExpiry.js'; export { DataBlob } from '../types/DataBlob.js'; -export { ModuleReference } from '../types/moduleReference.js'; export * from '../types/VersionedModuleSource.js'; export { VerifiablePresentation, @@ -62,6 +59,9 @@ import * as ContractAddress from '../types/ContractAddress.js'; import * as EntrypointName from '../types/EntrypointName.js'; import * as Timestamp from '../types/Timestamp.js'; import * as Duration from '../types/Duration.js'; +import * as CcdAmount from '../types/CcdAmount.js'; +import * as TransactionExpiry from '../types/TransactionExpiry.js'; +import * as ModuleReference from '../types/ModuleReference.js'; // These cannot be exported directly as modules because of a bug in an eslint plugin. // https://github.com/import-js/eslint-plugin-import/issues/2289. @@ -82,4 +82,7 @@ export { EntrypointName, Timestamp, Duration, + CcdAmount, + TransactionExpiry, + ModuleReference, }; diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 9933b610e..0117e5e7b 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -15,10 +15,11 @@ import type * as ContractName from './types/ContractName.js'; import type * as ReceiveName from './types/ReceiveName.js'; import type * as SequenceNumber from './types/SequenceNumber.js'; import type * as ReturnValue from './types/ReturnValue.js'; -import { CcdAmount } from './types/ccdAmount.js'; +import type * as CcdAmount from './types/CcdAmount.js'; +import type * as TransactionHash from './types/TransactionHash.js'; +import type * as TransactionExpiry from './types/TransactionExpiry.js'; import { DataBlob } from './types/DataBlob.js'; -import { TransactionExpiry } from './types/transactionExpiry.js'; -import { ModuleReference } from './types/moduleReference.js'; +import type * as ModuleReference from './types/ModuleReference.js'; import { RejectReason } from './types/rejectReason.js'; import { ContractTraceEvent } from './types/transactionEvent.js'; @@ -166,10 +167,10 @@ export interface GenericTransactionSummaryType } export interface BaseTransactionSummary { - sender?: string; - hash: string; + sender?: AccountAddress.Type; + hash: TransactionHash.Type; - cost: bigint; + cost: CcdAmount.Type; energyCost: Energy.Type; index: bigint; } @@ -288,7 +289,7 @@ export interface CooldownParametersV1 { /** Pool parameters used from protocol version 1-3 */ export interface PoolParametersV0 { /** The minimum threshold to stake to become a baker. */ - minimumThresholdForBaking: Amount; + minimumThresholdForBaking: CcdAmount.Type; } /** Pool parameters used from protocol version 4 */ @@ -306,7 +307,7 @@ export interface PoolParametersV1 { /** Fraction of transaction rewards charged by the pool owner. */ transactionCommissionRange: InclusiveRange; /** Minimum equity capital required for a new baker.*/ - minimumEquityCapital: Amount; + minimumEquityCapital: CcdAmount.Type; /** * Maximum fraction of the total staked capital of that a new baker can * have. @@ -481,11 +482,11 @@ export interface KeysWithThreshold { interface RewardStatusCommon { protocolVersion?: bigint; - totalAmount: Amount; - totalEncryptedAmount: Amount; - bakingRewardAccount: Amount; - finalizationRewardAccount: Amount; - gasAccount: Amount; + totalAmount: CcdAmount.Type; + totalEncryptedAmount: CcdAmount.Type; + bakingRewardAccount: CcdAmount.Type; + finalizationRewardAccount: CcdAmount.Type; + gasAccount: CcdAmount.Type; } export interface RewardStatusV0 extends RewardStatusCommon { @@ -494,10 +495,10 @@ export interface RewardStatusV0 extends RewardStatusCommon { export interface RewardStatusV1 extends RewardStatusCommon { version: 1; - foundationTransactionRewards: Amount; + foundationTransactionRewards: CcdAmount.Type; nextPaydayTime: Date; nextPaydayMintRate: MintRate; - totalStakedCapital: Amount; + totalStakedCapital: CcdAmount.Type; protocolVersion: bigint; } @@ -710,7 +711,7 @@ export interface NextAccountNonce { export interface ReleaseSchedule { timestamp: Date; - amount: Amount; + amount: CcdAmount.Type; } export interface ReleaseScheduleWithTransactions extends ReleaseSchedule { @@ -718,16 +719,16 @@ export interface ReleaseScheduleWithTransactions extends ReleaseSchedule { } export interface AccountReleaseSchedule { - total: Amount; + total: CcdAmount.Type; schedule: ReleaseScheduleWithTransactions[]; } export interface AccountEncryptedAmount { - selfAmount: string; + selfAmount: HexString; startIndex: bigint; - incomingAmounts: string[]; + incomingAmounts: HexString[]; numAggregated?: number; - aggregatedAmount?: string; + aggregatedAmount?: HexString; } export interface VerifyKey { @@ -824,7 +825,6 @@ export enum OpenStatusText { ClosedForAll = 'closedForAll', } -export type Amount = bigint; export type BakerId = bigint; export type DelegatorId = bigint; @@ -843,11 +843,11 @@ export interface CommissionRates { export interface CurrentPaydayBakerPoolStatus { blocksBaked: bigint; finalizationLive: boolean; - transactionFeesEarned: Amount; - effectiveStake: Amount; + transactionFeesEarned: CcdAmount.Type; + effectiveStake: CcdAmount.Type; lotteryPower: number; - bakerEquityCapital: Amount; - delegatedCapital: Amount; + bakerEquityCapital: CcdAmount.Type; + delegatedCapital: CcdAmount.Type; } export enum BakerPoolPendingChangeType { @@ -864,7 +864,7 @@ type BakerPoolPendingChangeWrapper< }; export interface BakerPoolPendingChangeReduceBakerCapitalDetails { - bakerEquityCapital: Amount; + bakerEquityCapital: CcdAmount.Type; effectiveTime: Date; } @@ -906,13 +906,13 @@ type PoolStatusWrapper = S & { export interface BakerPoolStatusDetails { bakerId: BakerId; bakerAddress: AccountAddress.Type; - bakerEquityCapital: Amount; - delegatedCapital: Amount; - delegatedCapitalCap: Amount; + bakerEquityCapital: CcdAmount.Type; + delegatedCapital: CcdAmount.Type; + delegatedCapitalCap: CcdAmount.Type; poolInfo: BakerPoolInfo; bakerStakePendingChange: BakerPoolPendingChange; currentPaydayStatus: CurrentPaydayBakerPoolStatus | null; - allPoolTotalCapital: Amount; + allPoolTotalCapital: CcdAmount.Type; } export type BakerPoolStatus = PoolStatusWrapper< @@ -921,11 +921,11 @@ export type BakerPoolStatus = PoolStatusWrapper< >; export interface PassiveDelegationStatusDetails { - delegatedCapital: Amount; + delegatedCapital: CcdAmount.Type; commissionRates: CommissionRates; - currentPaydayTransactionFeesEarned: Amount; - currentPaydayDelegatedCapital: Amount; - allPoolTotalCapital: Amount; + currentPaydayTransactionFeesEarned: CcdAmount.Type; + currentPaydayDelegatedCapital: CcdAmount.Type; + allPoolTotalCapital: CcdAmount.Type; } export type PassiveDelegationStatus = PoolStatusWrapper< @@ -965,7 +965,7 @@ interface AccountBakerDetailsCommon { bakerAggregationVerifyKey: string; bakerElectionVerifyKey: string; bakerSignatureVerifyKey: string; - stakedAmount: bigint; + stakedAmount: CcdAmount.Type; pendingChange?: StakePendingChange; } @@ -984,7 +984,7 @@ export type AccountBakerDetails = AccountBakerDetailsV0 | AccountBakerDetailsV1; export interface AccountDelegationDetails { restakeEarnings: boolean; - stakedAmount: bigint; + stakedAmount: CcdAmount.Type; delegationTarget: DelegationTarget; pendingChange?: StakePendingChange; } @@ -1002,7 +1002,7 @@ export enum AccountInfoType { interface AccountInfoCommon { accountAddress: AccountAddress.Type; accountNonce: SequenceNumber.Type; - accountAmount: bigint; + accountAmount: CcdAmount.Type; accountIndex: bigint; accountThreshold: number; accountEncryptionKey: string; @@ -1052,7 +1052,7 @@ export interface ArInfo { interface DelegatorInfoCommon { account: AccountAddress.Type; - stake: Amount; + stake: CcdAmount.Type; } export interface DelegatorInfo extends DelegatorInfoCommon { pendingChange?: StakePendingChange; @@ -1198,11 +1198,11 @@ export interface VersionedModuleSource { } export interface InitContractPayload { - /** µCCD amount to transfer */ - amount: CcdAmount; + /** CCD amount to transfer */ + amount: CcdAmount.Type; /** Hash of the module on chain */ - moduleRef: ModuleReference; + moduleRef: ModuleReference.Type; /** Name of the contract */ initName: ContractName.Type; @@ -1216,8 +1216,8 @@ export interface InitContractPayload { } export interface UpdateContractPayload { - /** µCCD amount to transfer */ - amount: CcdAmount; + /** CCD amount to transfer */ + amount: CcdAmount.Type; /** Address of contract instance consisting of an index and a subindex */ address: ContractAddress.Type; @@ -1244,12 +1244,12 @@ export interface AccountTransactionHeader { nonce: SequenceNumber.Type; /** expiration of the transaction */ - expiry: TransactionExpiry; + expiry: TransactionExpiry.Type; } export interface SimpleTransferPayload { - /** µCCD amount to transfer */ - amount: CcdAmount; + /** CCD amount to transfer */ + amount: CcdAmount.Type; /** the recipient of the transfer */ toAddress: AccountAddress.Type; @@ -1317,7 +1317,7 @@ export type GenerateBakerKeysOutput = PublicBakerKeys & export interface ConfigureBakerPayload { /* stake to bake. if set to 0, this removes the account as a baker */ - stake?: CcdAmount; + stake?: CcdAmount.Type; /* should earnings from baking be added to staked amount */ restakeEarnings?: boolean; openForDelegation?: OpenStatus; @@ -1330,7 +1330,7 @@ export interface ConfigureBakerPayload { export interface ConfigureDelegationPayload { /* stake to delegate. if set to 0, this removes the account as a delegator */ - stake?: CcdAmount; + stake?: CcdAmount.Type; /* should earnings from delegation be added to staked amount */ restakeEarnings?: boolean; /* determines if the account should use passive delegation, or which specific baker to delegate to */ @@ -1358,9 +1358,9 @@ export interface InstanceInfoCommon { /** Version of the smart contract module. */ version: number; /** Total balance of CCD hold by this instance. */ - amount: CcdAmount; + amount: CcdAmount.Type; /** Module reference of the current module being used by this instance. */ - sourceModule: ModuleReference; + sourceModule: ModuleReference.Type; /** Account used to instantiate this smart contract instance. */ owner: AccountAddress.Type; /** List of receive functions currently exposed by this smart contract. These are of the form '.'. */ @@ -1413,7 +1413,7 @@ export interface InstanceStateKVPair { export interface ContractContext { invoker?: ContractAddress.Type | AccountAddress.Type; contract: ContractAddress.Type; - amount?: CcdAmount; + amount?: CcdAmount.Type; method: ReceiveName.Type; parameter?: Parameter.Type; energy?: Energy.Type; @@ -1438,7 +1438,7 @@ export type InvokeContractResult = | InvokeContractFailedResult; export interface CredentialDeploymentDetails { - expiry: TransactionExpiry; + expiry: TransactionExpiry.Type; unsignedCdi: UnsignedCredentialDeploymentInformation; } @@ -1484,7 +1484,7 @@ export interface CredentialDeploymentInfo extends CredentialDeploymentValues { } export interface SignedCredentialDeploymentDetails { - expiry: TransactionExpiry; + expiry: TransactionExpiry.Type; cdi: CredentialDeploymentInfo; } diff --git a/packages/sdk/src/types/BlockSpecialEvents.ts b/packages/sdk/src/types/BlockSpecialEvents.ts index a548d632c..6b259da8b 100644 --- a/packages/sdk/src/types/BlockSpecialEvents.ts +++ b/packages/sdk/src/types/BlockSpecialEvents.ts @@ -1,4 +1,6 @@ -import { Amount, BakerId, Base58String } from '../types.js'; +import type { BakerId } from '../types.js'; +import * as CcdAmount from './CcdAmount.js'; +import * as AccountAddress from './AccountAddress.js'; export type BlockSpecialEvent = | BlockSpecialEventBakingRewards @@ -15,19 +17,19 @@ export interface BlockSpecialEventBakingRewards { // The amount awarded to each baker. bakingRewards: BlockSpecialEventAccountAmount[]; // The remaining balance of the baker reward account. - remainder: Amount; + remainder: CcdAmount.Type; } export interface BlockSpecialEventMint { tag: 'mint'; // The amount allocated to the banking reward account. - mintBakingReward: Amount; + mintBakingReward: CcdAmount.Type; // The amount allocated to the finalization reward account. - mintFinalizationReward: Amount; + mintFinalizationReward: CcdAmount.Type; // The amount allocated as the platform development charge. - mintPlatformDevelopmentCharge: Amount; + mintPlatformDevelopmentCharge: CcdAmount.Type; // The account to which the platform development charge is paid. - foundationAccount: Base58String; + foundationAccount: AccountAddress.Type; } export interface BlockSpecialEventFinalizationRewards { @@ -35,61 +37,61 @@ export interface BlockSpecialEventFinalizationRewards { // The amount awarded to each finalizer. finalizationRewards?: BlockSpecialEventAccountAmount[]; // The remaining balance of the finalization reward account. - remainder?: Amount; + remainder?: CcdAmount.Type; } export interface BlockSpecialEventBlockReward { tag: 'blockReward'; // The total fees paid for transactions in the block. - transactionFees: Amount; + transactionFees: CcdAmount.Type; // The old balance of the GAS account. - oldGasAccount: Amount; + oldGasAccount: CcdAmount.Type; // The new balance of the GAS account. - newGasAccount: Amount; + newGasAccount: CcdAmount.Type; // The amount awarded to the baker. - bakerReward: Amount; + bakerReward: CcdAmount.Type; // The amount awarded to the foundation. - foundationCharge: Amount; + foundationCharge: CcdAmount.Type; // The baker of the block, who receives the award. - baker: Base58String; + baker: AccountAddress.Type; // The foundation account. - foundationAccount: Base58String; + foundationAccount: AccountAddress.Type; } export interface BlockSpecialEventPaydayFoundationReward { tag: 'paydayFoundationReward'; // The account that got rewarded. - foundationAccount: Base58String; + foundationAccount: AccountAddress.Type; // The transaction fee reward at payday to the account. - developmentCharge: Amount; + developmentCharge: CcdAmount.Type; } export interface BlockSpecialEventPaydayAccountReward { tag: 'paydayAccountReward'; // The account that got rewarded. - account: Base58String; + account: AccountAddress.Type; // The transaction fee reward at payday to the account. - transactionFees: Amount; + transactionFees: CcdAmount.Type; // The baking reward at payday to the account. - bakerReward: Amount; + bakerReward: CcdAmount.Type; // The finalization reward at payday to the account. - finalizationReward: Amount; + finalizationReward: CcdAmount.Type; } export interface BlockSpecialEventBlockAccrueReward { tag: 'blockAccrueReward'; // The total fees paid for transactions in the block. - transactionFees: Amount; + transactionFees: CcdAmount.Type; // The old balance of the GAS account. - oldGasAccount: Amount; + oldGasAccount: CcdAmount.Type; // The new balance of the GAS account. - newGasAccount: Amount; + newGasAccount: CcdAmount.Type; // The amount awarded to the baker. - bakerReward: Amount; + bakerReward: CcdAmount.Type; // The amount awarded to the passive delegators. - passiveReward: Amount; + passiveReward: CcdAmount.Type; // The amount awarded to the foundation. - foundationCharge: Amount; + foundationCharge: CcdAmount.Type; // The baker of the block, who will receive the award. baker: BakerId; } @@ -99,33 +101,33 @@ export interface BlockSpecialEventPaydayPoolReward { // The pool owner (passive delegators when not present). poolOwner?: BakerId; // Accrued transaction fees for pool. - transactionFees: Amount; + transactionFees: CcdAmount.Type; // Accrued baking rewards for pool. - bakerReward: Amount; + bakerReward: CcdAmount.Type; // Accrued finalization rewards for pool. - finalizationReward: Amount; + finalizationReward: CcdAmount.Type; } export interface BlockSpecialEventAccountAmount { // The key type - account: Base58String; + account: AccountAddress.Type; // The value type - amount: Amount; + amount: CcdAmount.Type; } /** - * Gets a list of {@link Base58String} account addresses affected the {@link BlockSpecialEvent}. + * Gets a list of {@link AccountAddress.Type} account addresses affected the {@link BlockSpecialEvent}. * * @param {BlockSpecialEvent} event - The block special event to check. * - * @returns {Base58String[]} List of account addresses affected by the event. + * @returns {AccountAddress.Type[]} List of account addresses affected by the event. */ export function specialEventAffectedAccounts( event: Exclude< BlockSpecialEvent, BlockSpecialEventBlockAccrueReward | BlockSpecialEventPaydayPoolReward > -): Base58String[]; +): AccountAddress.Type[]; export function specialEventAffectedAccounts( event: | BlockSpecialEventBlockAccrueReward @@ -133,10 +135,10 @@ export function specialEventAffectedAccounts( ): never[]; export function specialEventAffectedAccounts( event: BlockSpecialEvent -): Base58String[]; +): AccountAddress.Type[]; export function specialEventAffectedAccounts( event: BlockSpecialEvent -): Base58String[] { +): AccountAddress.Type[] { switch (event.tag) { case 'bakingRewards': return event.bakingRewards.map((br) => br.account); @@ -148,7 +150,7 @@ export function specialEventAffectedAccounts( case 'paydayAccountReward': return [event.account]; case 'blockReward': { - if (event.baker === event.foundationAccount) { + if (AccountAddress.equals(event.baker, event.foundationAccount)) { return [event.baker]; } return [event.baker, event.foundationAccount]; diff --git a/packages/sdk/src/types/CcdAmount.ts b/packages/sdk/src/types/CcdAmount.ts new file mode 100644 index 000000000..a57b7b937 --- /dev/null +++ b/packages/sdk/src/types/CcdAmount.ts @@ -0,0 +1,160 @@ +import { Big, BigSource } from 'big.js'; +import type * as Proto from '../grpc-api/v2/concordium/types.js'; + +const MICRO_CCD_PER_CCD = 1_000_000; + +/** + * Representation of a CCD amount. + * The base unit of CCD is micro CCD, which is the representation + * used on chain. + */ +class CcdAmount { + /** Having a private field prevents similar structured objects to be considered the same type (similar to nominal typing). */ + private __nominal = true; + constructor( + /** Internal representation of Ccd amound in micro Ccd. */ + public readonly microCcdAmount: bigint + ) {} + + toJSON(): string { + return this.microCcdAmount.toString(); + } +} + +/** + * Representation of a CCD amount. + * The base unit of CCD is micro CCD, which is the representation + * used on chain. + */ +export type Type = CcdAmount; + +/** + * Constructs a CcdAmount and checks that it is valid. It accepts a number, string, big, or bigint as parameter. + * It can accept a string as parameter with either a comma or a dot as the decimal separator. + * + * @param microCcdAmount The amount of micro CCD as a number, string, big, or bigint. + * @throws If an invalid micro CCD amount is passed, i.e. any value which is not an unsigned 64-bit integer + */ +export function fromMicroCcd(microCcdAmount: BigSource | bigint): CcdAmount { + // If the input is a "BigSource" assert that the number is whole + if (typeof microCcdAmount !== 'bigint') { + microCcdAmount = newBig(microCcdAmount); + + if (!microCcdAmount.mod(Big(1)).eq(Big(0))) { + throw Error('Can not create CcdAmount from a non-whole number!'); + } + + microCcdAmount = BigInt(microCcdAmount.toFixed()); + } + + if (microCcdAmount < 0n) { + throw new Error( + 'A micro CCD amount must be a non-negative integer but was: ' + + microCcdAmount + ); + } else if (microCcdAmount > 18446744073709551615n) { + throw new Error( + 'A micro CCD amount must be representable as an unsigned 64 bit integer but was: ' + + microCcdAmount + ); + } + + return new CcdAmount(microCcdAmount); +} + +/** + * Create a value representing zero CCD. + * @returns {CcdAmount} A zero amount of CCD + */ +export function zero(): CcdAmount { + return new CcdAmount(0n); +} + +/** + * Creates a CcdAmount from a number, string, big, or bigint. + * + * @param ccd The amount of micro CCD as a number, string, big or bigint. + * @returns The CcdAmount object derived from the ccd input parameter + * @throws If a number is passed with several decimal seperators + * @throws If a negative amount of micro CCD is passed + * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer + */ +export function fromCcd(ccd: BigSource | bigint): CcdAmount { + if (typeof ccd === 'bigint') { + ccd = ccd.toString(); + } + + const microCcd = newBig(ccd).mul(Big(MICRO_CCD_PER_CCD)); + return fromMicroCcd(microCcd); +} + +function newBig(bigSource: BigSource): Big { + if (typeof bigSource === 'string') { + return Big(bigSource.replace(',', '.')); + } + return Big(bigSource); +} + +/** + * Returns the amount of micro CCD as a Big. + * @param {CcdAmount} amount The CCD amount. + * @returns {Big} The amount in micro CCD. + */ +export function toMicroCcd(amount: CcdAmount): Big { + return Big(amount.microCcdAmount.toString()); +} + +/** + * Returns the amount of CCD as a Big. + * @param {CcdAmount} amount The CCD amount. + * @returns The amount of CCD as a Big + */ +export function toCcd(amount: CcdAmount): Big { + return Big(amount.microCcdAmount.toString()).div(Big(MICRO_CCD_PER_CCD)); +} + +/** + * Converts an amount of CCD to micro CCD and asserts that the amount is a valid amount of CCD. + * + * @param ccd The amount of CCD as a number, string, big or bigint. + * @returns The amount of micro CCD as a Big + * @throws If a number is passed with several decimal seperators + * @throws If a negative amount of micro CCD is passed + * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer + */ +export function ccdToMicroCcd(ccd: BigSource | bigint): Big { + return toMicroCcd(fromCcd(ccd)); +} + +/** + * Converts an amount of micro CCD to CCD and asserts that the amount is a valid amount of CCD. + * + * @param microCcd The amount of micro CCD as a number, string, big or bigint. + * @returns The amount of CCD as a Big + * @throws If a number is passed with several decimal seperators + * @throws If a negative amount of micro CCD is passed + * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer + */ +export function microCcdToCcd(microCcd: BigSource | bigint): Big { + return toCcd(fromMicroCcd(microCcd)); +} + +/** + * Convert an amount of CCD from its protobuf encoding. + * @param {Proto.Amount} amount The energy in protobuf. + * @returns {CcdAmount} The energy. + */ +export function fromProto(amount: Proto.Energy): CcdAmount { + return new CcdAmount(amount.value); +} + +/** + * Convert an amount of CCD into its protobuf encoding. + * @param {CcdAmount} amount The CCD amount. + * @returns {Proto.Amount} The protobuf encoding. + */ +export function toProto(amount: CcdAmount): Proto.Amount { + return { + value: amount.microCcdAmount, + }; +} diff --git a/packages/sdk/src/types/ModuleClient.ts b/packages/sdk/src/types/ModuleClient.ts index 90475ec93..a33250241 100644 --- a/packages/sdk/src/types/ModuleClient.ts +++ b/packages/sdk/src/types/ModuleClient.ts @@ -1,8 +1,5 @@ -import { - ContractTransactionMetadata, - getContractUpdateDefaultExpiryDate, -} from '../GenericContract.js'; -import { ModuleReference } from './moduleReference.js'; +import { ContractTransactionMetadata } from '../GenericContract.js'; +import * as ModuleReference from './ModuleReference.js'; import * as BlockHash from './BlockHash.js'; import * as Parameter from './Parameter.js'; import * as TransactionHash from './TransactionHash.js'; @@ -14,8 +11,8 @@ import { } from '../types.js'; import { ConcordiumGRPCClient } from '../grpc/index.js'; import { AccountSigner, signTransaction } from '../signHelpers.js'; -import { CcdAmount } from './ccdAmount.js'; -import { TransactionExpiry } from './transactionExpiry.js'; +import * as CcdAmount from './CcdAmount.js'; +import * as TransactionExpiry from './TransactionExpiry.js'; /** * An update transaction without header. @@ -40,7 +37,7 @@ class ModuleClient { /** The gRPC connection used by this object */ public readonly grpcClient: ConcordiumGRPCClient, /** The reference for this module */ - public readonly moduleReference: ModuleReference + public readonly moduleReference: ModuleReference.Type ) {} } @@ -60,7 +57,7 @@ export type Type = ModuleClient; */ export function createUnchecked( grpcClient: ConcordiumGRPCClient, - moduleReference: ModuleReference + moduleReference: ModuleReference.Type ): ModuleClient { return new ModuleClient(grpcClient, moduleReference); } @@ -78,7 +75,7 @@ export function createUnchecked( */ export async function create( grpcClient: ConcordiumGRPCClient, - moduleReference: ModuleReference + moduleReference: ModuleReference.Type ): Promise { const mod = new ModuleClient(grpcClient, moduleReference); await checkOnChain(mod); @@ -123,7 +120,6 @@ export function getModuleSource( /** * Creates and sends transaction for initializing a smart contract `contractName` with parameter `input`. * - * * @param {ModuleClient} moduleClient The client for a smart contract module on chain. * @param {ContractName.Type} contractName - The name of the smart contract to instantiate (this is without the `init_` prefix). * @param {ContractTransactionMetadata} metadata - Metadata to be used for the transaction (with defaults). @@ -143,7 +139,7 @@ export async function createAndSendInitTransaction( ): Promise { const payload: InitContractPayload = { moduleRef: moduleClient.moduleReference, - amount: new CcdAmount(metadata.amount ?? 0n), + amount: metadata.amount ?? CcdAmount.zero(), initName: contractName, maxContractExecutionEnergy: metadata.energy, param: parameter, @@ -152,9 +148,7 @@ export async function createAndSendInitTransaction( metadata.senderAddress ); const header = { - expiry: new TransactionExpiry( - metadata.expiry ?? getContractUpdateDefaultExpiryDate() - ), + expiry: metadata.expiry ?? TransactionExpiry.futureMinutes(5), nonce: nonce, sender: metadata.senderAddress, }; diff --git a/packages/sdk/src/types/ModuleReference.ts b/packages/sdk/src/types/ModuleReference.ts new file mode 100644 index 000000000..a69f38948 --- /dev/null +++ b/packages/sdk/src/types/ModuleReference.ts @@ -0,0 +1,100 @@ +import type * as Proto from '../grpc-api/v2/concordium/types.js'; +import { Buffer } from 'buffer/index.js'; +import { packBufferWithWord32Length } from '../serializationHelpers.js'; +import { HexString } from '../types.js'; + +/** + * The number of bytes used to represent a block hash. + */ +const moduleReferenceByteLength = 32; + +/** + * Reference to a smart contract module. + */ +class ModuleReference { + constructor( + /** Internal field, the module reference represented as a hex string. */ + public readonly moduleRef: string, + /** Internal field, buffer containing the 32 bytes for the module reference. */ + public readonly decodedModuleRef: Uint8Array + ) {} + + toJSON(): string { + return packBufferWithWord32Length(this.decodedModuleRef).toString( + 'hex' + ); + } +} + +/** + * Reference to a smart contract module. + */ +export type Type = ModuleReference; + +/** + * Create a ModuleReference from a buffer of 32 bytes. + * @param {ArrayBuffer} buffer Buffer containing 32 bytes for the hash. + * @throws If the provided buffer does not contain exactly 32 bytes. + * @returns {ModuleReference} A module reference. + */ +export function fromBuffer(buffer: ArrayBuffer): ModuleReference { + const hex = Buffer.from(buffer).toString('hex'); + if (buffer.byteLength !== moduleReferenceByteLength) { + throw new Error( + 'The provided moduleRef ' + + hex + + ' is invalid as module reference as it does not contain 32 bytes' + ); + } + return new ModuleReference(hex, new Uint8Array(buffer)); +} + +/** + * Create a ModuleReference from a hex string. + * @param {HexString} hex Hex encoding of the module reference. + * @throws If the provided hex encoding does not correspond to a buffer of exactly 32 bytes. + * @returns {ModuleReference} A module reference. + */ +export function fromHexString(moduleRef: HexString) { + if (moduleRef.length !== moduleReferenceByteLength * 2) { + throw new Error( + 'The provided moduleRef ' + + moduleRef + + ' is invalid as its length was not 64' + ); + } + return new ModuleReference( + moduleRef, + new Uint8Array(Buffer.from(moduleRef, 'hex')) + ); +} + +/** + * Convert module reference from its protobuf encoding. + * @param {Proto.ModuleRef} moduleReference The module reference in protobuf. + * @returns {ModuleReference} The module reference. + */ +export function fromProto(moduleReference: Proto.ModuleRef): ModuleReference { + return fromBuffer(moduleReference.value); +} + +/** + * Convert module reference into its protobuf encoding. + * @param {ModuleReference} moduleReference The module reference. + * @returns {Proto.ModuleRef} The protobuf encoding. + */ +export function toProto(moduleReference: ModuleReference): Proto.ModuleRef { + return { + value: moduleReference.decodedModuleRef, + }; +} + +/** + * Check if two module references are the same. + * @param {ModuleReference} left + * @param {ModuleReference} right + * @returns {boolean} True if they are equal. + */ +export function equals(left: ModuleReference, right: ModuleReference): boolean { + return left.moduleRef === right.moduleRef; +} diff --git a/packages/sdk/src/types/TransactionExpiry.ts b/packages/sdk/src/types/TransactionExpiry.ts new file mode 100644 index 000000000..5f26bb029 --- /dev/null +++ b/packages/sdk/src/types/TransactionExpiry.ts @@ -0,0 +1,87 @@ +import { secondsSinceEpoch } from '../util.js'; +import type * as Proto from '../grpc-api/v2/concordium/types.js'; + +/** + * Representation of a transaction expiry date. + */ +class TransactionExpiry { + /** Having a private field prevents similar structured objects to be considered the same type (similar to nominal typing). */ + private __nominal = true; + constructor( + /** Internal representation of expiry. Seconds since unix epoch */ + public readonly expiryEpochSeconds: bigint + ) {} + + toJSON(): number { + return Number(this.expiryEpochSeconds); + } +} + +/** + * Representation of a transaction expiry date. + */ +export type Type = TransactionExpiry; + +/** + * Construct a TransactionExpiry from a number of seconds since unix epoch. + * @param {bigint | number} seconds Number of seconds since unix epoch. + * @throws If provided a negative number. + * @returns The transaction expiry. + */ +export function fromEpochSeconds(seconds: bigint | number): TransactionExpiry { + if (seconds < 0n) { + throw new Error( + 'Invalid transaction expiry: Expiry cannot be before unix epoch.' + ); + } + return new TransactionExpiry(BigInt(seconds)); +} + +/** + * Construct a TransactionExpiry from a Date object. + * @param {Date} expiry The date representing the expiry time. + * @throws If provided the date is from before unix epoch. + * @returns {TransactionExpiry} The transaction expiry. + */ +export function fromDate(expiry: Date): TransactionExpiry { + return fromEpochSeconds(secondsSinceEpoch(expiry)); +} + +/** + * Convert a TransactionExpiry into a Date object. + * @param {TransactionExpiry} expiry A TransactionExpiry to convert. + * @returns {Date} The date object. + */ +export function toDate(expiry: TransactionExpiry): Date { + return new Date(Number(expiry.expiryEpochSeconds) * 1000); +} + +/** + * Construct a TransactionExpiry minutes in the future from the time of calling this function. + * @param {number} minutes The number of minutes in the future to set as the expiry time. + * @returns {TransactionExpiry} The transaction expiry. + */ +export function futureMinutes(minutes: number): TransactionExpiry { + const expiryMillis = Date.now() + minutes * 60 * 1000; + return fromDate(new Date(expiryMillis)); +} + +/** + * Convert expiry from its protobuf encoding. + * @param {Proto.TransactionTime} expiry The expiry in protobuf. + * @returns {TransactionExpiry} The expiry. + */ +export function fromProto(expiry: Proto.TransactionTime): TransactionExpiry { + return new TransactionExpiry(expiry.value); +} + +/** + * Convert expiry into its protobuf encoding. + * @param {TransactionExpiry} expiry The expiry. + * @returns {Proto.TransactionTime} The protobuf encoding. + */ +export function toProto(expiry: TransactionExpiry): Proto.TransactionTime { + return { + value: expiry.expiryEpochSeconds, + }; +} diff --git a/packages/sdk/src/types/VersionedModuleSource.ts b/packages/sdk/src/types/VersionedModuleSource.ts index c74d8435b..0ec38d6b0 100644 --- a/packages/sdk/src/types/VersionedModuleSource.ts +++ b/packages/sdk/src/types/VersionedModuleSource.ts @@ -1,4 +1,4 @@ -import { ModuleReference } from './moduleReference.js'; +import * as ModuleReference from './ModuleReference.js'; import * as H from '../contractHelpers.js'; import { sha256 } from '../hash.js'; import { Buffer } from 'buffer/index.js'; @@ -48,12 +48,12 @@ export function versionedModuleSourceFromBuffer( */ export function calculateModuleReference( moduleSource: VersionedModuleSource -): ModuleReference { +): ModuleReference.Type { const prefix = Buffer.alloc(8); prefix.writeUInt32BE(moduleSource.version, 0); prefix.writeUInt32BE(moduleSource.source.length, 4); const hash = sha256([prefix, moduleSource.source]); - return ModuleReference.fromBytes(hash); + return ModuleReference.fromBuffer(hash); } /** diff --git a/packages/sdk/src/types/ccdAmount.ts b/packages/sdk/src/types/ccdAmount.ts deleted file mode 100644 index e92772e74..000000000 --- a/packages/sdk/src/types/ccdAmount.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { Big, BigSource } from 'big.js'; - -const MICRO_CCD_PER_CCD = 1000000; - -/** - * Representation of a CCD amount. - * The base unit of CCD is micro CCD, which is the representation - * used on chain. - */ -export class CcdAmount { - microCcdAmount: bigint; - - /** - * Constructs a CcdAmount and checks that it is valid. It accepts a number, string, big, or bigint as parameter. - * It can accept a string as parameter with either a comma or a dot as the decimal separator. - * - * @param microCcdAmount The amount of micro CCD as a number, string, big, or bigint. - * @throws If an invalid micro CCD amount is passed, i.e. any value which is not an unsigned 64-bit integer - */ - constructor(microCcdAmount: bigint | BigSource) { - // If the input is a "BigSource" assert that the number is whole - if (typeof microCcdAmount !== 'bigint') { - microCcdAmount = newBig(microCcdAmount); - - if (!microCcdAmount.mod(Big(1)).eq(Big(0))) { - throw Error( - 'Can not create CcdAmount from a non-whole number!' - ); - } - - microCcdAmount = BigInt(microCcdAmount.toFixed()); - } - - if (microCcdAmount < 0n) { - throw new Error( - 'A micro CCD amount must be a non-negative integer but was: ' + - microCcdAmount - ); - } else if (microCcdAmount > 18446744073709551615n) { - throw new Error( - 'A micro CCD amount must be representable as an unsigned 64 bit integer but was: ' + - microCcdAmount - ); - } - - this.microCcdAmount = microCcdAmount; - } - - /** - * Returns the amount of micro CCD as a Big. - * - * @returns The amount of micro CCD as a Big - */ - toMicroCcd(): Big { - return Big(this.microCcdAmount.toString()); - } - - /** - * Returns the amount of CCD as a Big. - * - * @returns The amount of CCD as a Big - */ - toCcd(): Big { - return this.toMicroCcd().div(Big(MICRO_CCD_PER_CCD)); - } - - /** - * Creates a CcdAmount from a number, string, big, or bigint. - * - * @param ccd The amount of micro CCD as a number, string, big or bigint. - * @returns The CcdAmount object derived from the ccd input parameter - * @throws If a number is passed with several decimal seperators - * @throws If a negative amount of micro CCD is passed - * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer - */ - static fromCcd(ccd: BigSource | bigint): CcdAmount { - if (typeof ccd === 'bigint') { - ccd = ccd.toString(); - } - - const microCcd = newBig(ccd).mul(Big(MICRO_CCD_PER_CCD)); - return new CcdAmount(microCcd); - } - - /** - * Converts an amount of CCD to micro CCD and asserts that the amount is a valid amount of CCD. - * - * @param ccd The amount of CCD as a number, string, big or bigint. - * @returns The amount of micro CCD as a Big - * @throws If a number is passed with several decimal seperators - * @throws If a negative amount of micro CCD is passed - * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer - */ - static ccdToMicroCcd(ccd: BigSource | bigint): Big { - return CcdAmount.fromCcd(ccd).toMicroCcd(); - } - - /** - * Converts an amount of micro CCD to CCD and asserts that the amount is a valid amount of CCD. - * - * @param microCcd The amount of micro CCD as a number, string, big or bigint. - * @returns The amount of CCD as a Big - * @throws If a number is passed with several decimal seperators - * @throws If a negative amount of micro CCD is passed - * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer - */ - static microCcdToCcd(microCcd: BigSource | bigint): Big { - return new CcdAmount(microCcd).toCcd(); - } - - toJSON(): string { - return this.microCcdAmount.toString(); - } -} - -function newBig(bigSource: BigSource): Big { - if (typeof bigSource === 'string') { - return Big(bigSource.replace(',', '.')); - } - return Big(bigSource); -} diff --git a/packages/sdk/src/types/chainUpdate.ts b/packages/sdk/src/types/chainUpdate.ts index 7480e22d2..357a8c5a4 100644 --- a/packages/sdk/src/types/chainUpdate.ts +++ b/packages/sdk/src/types/chainUpdate.ts @@ -1,5 +1,4 @@ import type { - Amount, AuthorizationsV0, AuthorizationsV1, Base58String, @@ -19,6 +18,7 @@ import type { } from '../types.js'; import type * as Energy from './Energy.js'; import type * as Duration from './Duration.js'; +import type * as CcdAmount from './CcdAmount.js'; type ChainUpdate = { /** The type of the update */ @@ -272,7 +272,7 @@ export interface CommissionRanges { export interface PoolParameters { passiveCommissions: CommissionRates; commissionBounds: CommissionRanges; - minimumEquityCapital: Amount; + minimumEquityCapital: CcdAmount.Type; capitalBound: number; leverageBound: Fraction; } diff --git a/packages/sdk/src/types/moduleReference.ts b/packages/sdk/src/types/moduleReference.ts deleted file mode 100644 index e8bbbaaf8..000000000 --- a/packages/sdk/src/types/moduleReference.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { Buffer } from 'buffer/index.js'; -import { packBufferWithWord32Length } from '../serializationHelpers.js'; - -/** - * Representation of a module reference, which enforces that it: - * - Hash length exactly 64 - * - Is a valid 64 length hex string - */ -export class ModuleReference { - moduleRef: string; - - decodedModuleRef: Uint8Array; - - constructor(moduleRef: string) { - if (moduleRef.length !== 64) { - throw new Error( - 'The provided moduleRef ' + - moduleRef + - ' is invalid as its length was not 64' - ); - } - try { - this.decodedModuleRef = Buffer.from(moduleRef, 'hex'); - this.moduleRef = moduleRef; - } catch (error) { - throw error; - } - } - - static fromBytes(bytes: ArrayBuffer): ModuleReference { - return new ModuleReference(Buffer.from(bytes).toString('hex')); - } - - toJSON(): string { - return packBufferWithWord32Length( - Buffer.from(this.decodedModuleRef) - ).toString('hex'); - } -} diff --git a/packages/sdk/src/types/rejectReason.ts b/packages/sdk/src/types/rejectReason.ts index a54630536..70f9f4d7c 100644 --- a/packages/sdk/src/types/rejectReason.ts +++ b/packages/sdk/src/types/rejectReason.ts @@ -1,5 +1,10 @@ -import { Address, Base58String, HexString, Amount, BakerId } from '../types.js'; +import { Address, Base58String, HexString, BakerId } from '../types.js'; import type * as ContractAddress from './ContractAddress.js'; +import type * as ReceiveName from './ReceiveName.js'; +import type * as CcdAmount from './CcdAmount.js'; +import type * as Parameter from './Parameter.js'; +import type * as InitName from './InitName.js'; +import type * as ModuleReference from './ModuleReference.js'; /* * An enum containing all the possible reject reasons that can be @@ -70,9 +75,9 @@ export enum RejectReasonTag { export interface RejectedReceive { tag: RejectReasonTag.RejectedReceive; contractAddress: ContractAddress.Type; - receiveName: string; + receiveName: ReceiveName.Type; rejectReason: number; - parameter: HexString; + parameter: Parameter.Type; } export interface RejectedInit { @@ -155,16 +160,16 @@ export interface SimpleRejectReason { export interface InvalidReceiveMethod { tag: RejectReasonTag.InvalidReceiveMethod; contents: { - moduleRef: HexString; - receiveName: string; + moduleRef: ModuleReference.Type; + receiveName: ReceiveName.Type; }; } export interface InvalidInitMethod { tag: RejectReasonTag.InvalidInitMethod; contents: { - moduleRef: HexString; - initName: string; // [moduleRef, initName] + moduleRef: ModuleReference.Type; + initName: InitName.Type; }; } @@ -172,7 +177,7 @@ export interface AmountTooLarge { tag: RejectReasonTag.AmountTooLarge; contents: { address: Address; - amount: Amount; + amount: CcdAmount.Type; }; } diff --git a/packages/sdk/src/types/transactionEvent.ts b/packages/sdk/src/types/transactionEvent.ts index 9e86d468f..689966aa0 100644 --- a/packages/sdk/src/types/transactionEvent.ts +++ b/packages/sdk/src/types/transactionEvent.ts @@ -6,7 +6,6 @@ import type { ModuleRef, HexString, EventDelegationTarget, - Amount, BakerId, DelegatorId, } from '../types.js'; @@ -16,6 +15,7 @@ import type * as AccountAddress from './AccountAddress.js'; import type * as Parameter from './Parameter.js'; import type * as ReceiveName from './ReceiveName.js'; import type * as InitName from './InitName.js'; +import type * as CcdAmount from './CcdAmount.js'; export enum TransactionEventTag { ModuleDeployed = 'ModuleDeployed', @@ -105,7 +105,7 @@ export interface UpdatedEvent { tag: TransactionEventTag.Updated; address: ContractAddress.Type; instigator: Address; - amount: Amount; + amount: CcdAmount.Type; contractVersion: ContractVersion; message: Parameter.Type; receiveName: ReceiveName.Type; @@ -114,7 +114,7 @@ export interface UpdatedEvent { export interface TransferredEvent { tag: TransactionEventTag.Transferred; - amount: Amount; + amount: CcdAmount.Type; to: AccountAddress.Type; from: ContractAddress.Type; } @@ -134,7 +134,7 @@ export interface DataRegisteredEvent { export interface ContractInitializedEvent { tag: TransactionEventTag.ContractInitialized; address: ContractAddress.Type; - amount: Amount; + amount: CcdAmount.Type; initName: InitName.Type; events: HexString[]; contractVersion: ContractVersion; @@ -150,7 +150,7 @@ export interface ModuleDeployedEvent { export interface AccountTransferredEvent { tag: TransactionEventTag.Transferred; - amount: Amount; + amount: CcdAmount.Type; to: AccountAddress.Type; } @@ -173,13 +173,13 @@ export interface AccountCreatedEvent { export interface AmountAddedByDecryptionEvent { tag: TransactionEventTag.AmountAddedByDecryption; account: AccountAddress.Type; - amount: Amount; + amount: CcdAmount.Type; } export interface EncryptedSelfAmountAddedEvent { tag: TransactionEventTag.EncryptedSelfAmountAdded; account: AccountAddress.Type; - amount: Amount; + amount: CcdAmount.Type; newAmount: string; } @@ -247,7 +247,7 @@ export interface DelegationStakeChangedEvent { | TransactionEventTag.DelegationStakeIncreased; delegatorId: DelegatorId; account: AccountAddress.Type; - newStake: bigint; + newStake: CcdAmount.Type; } // Baker Events @@ -259,7 +259,7 @@ export interface BakerAddedEvent { signKey: string; electionKey: string; aggregationKey: string; - stake: bigint; + stake: CcdAmount.Type; restakeEarnings: boolean; } @@ -275,7 +275,7 @@ export interface BakerStakeChangedEvent { | TransactionEventTag.BakerStakeDecreased; bakerId: BakerId; account: AccountAddress.Type; - newStake: bigint; + newStake: CcdAmount.Type; } export interface BakerSetRestakeEarningsEvent { diff --git a/packages/sdk/src/types/transactionExpiry.ts b/packages/sdk/src/types/transactionExpiry.ts deleted file mode 100644 index 1f617dc90..000000000 --- a/packages/sdk/src/types/transactionExpiry.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { secondsSinceEpoch } from '../util.js'; - -/** - * Representation of a transaction expiry date. - * - * A transaction expiry has to be in the future. Note that the concordium-node - * will reject transactions that are too far into the future, currently the default - * value for this rejection is 2 hours. - */ -export class TransactionExpiry { - /** expiry is measured as seconds since epoch */ - expiryEpochSeconds: bigint; - - constructor(expiry: Date, allowExpired = false) { - if (!allowExpired && expiry < new Date()) { - throw new Error( - 'A transaction expiry is not allowed to be in the past: ' + - expiry - ); - } - this.expiryEpochSeconds = secondsSinceEpoch(expiry); - } - - static fromEpochSeconds( - seconds: bigint, - allowExpired = false - ): TransactionExpiry { - return new TransactionExpiry( - new Date(Number(seconds) * 1000), - allowExpired - ); - } - - toJSON(): number { - return Number(this.expiryEpochSeconds); - } -} diff --git a/packages/sdk/src/wasm/credentialDeploymentTransactions.ts b/packages/sdk/src/wasm/credentialDeploymentTransactions.ts index 7c408025d..fdc4b8b35 100644 --- a/packages/sdk/src/wasm/credentialDeploymentTransactions.ts +++ b/packages/sdk/src/wasm/credentialDeploymentTransactions.ts @@ -19,7 +19,7 @@ import { CredentialDeploymentDetails, HexString, } from '../types.js'; -import { TransactionExpiry } from '../types/transactionExpiry.js'; +import * as TransactionExpiry from '../types/TransactionExpiry.js'; import * as AccountAddress from '../types/AccountAddress.js'; import { sha256 } from '../hash.js'; import { ConcordiumHdWallet } from './HdWallet.js'; @@ -106,7 +106,7 @@ export function createCredentialDeploymentTransaction( publicKeys: VerifyKey[], credentialIndex: number, revealedAttributes: AttributeKey[], - expiry: TransactionExpiry + expiry: TransactionExpiry.Type ): CredentialDeploymentTransaction { const unsignedCredentialInfo = createUnsignedCredentialInfo( identity, @@ -215,7 +215,7 @@ export type CredentialInputNoSeed = CredentialInputCommon & { */ export function createCredentialTransaction( input: CredentialInput, - expiry: TransactionExpiry + expiry: TransactionExpiry.Type ): CredentialDeploymentTransaction { const wallet = ConcordiumHdWallet.fromHex(input.seedAsHex, input.net); const publicKey = wallet @@ -282,7 +282,7 @@ export function createCredentialTransaction( */ export function createCredentialTransactionNoSeed( input: CredentialInputNoSeed, - expiry: TransactionExpiry + expiry: TransactionExpiry.Type ): CredentialDeploymentTransaction { const rawRequest = wasm.createUnsignedCredentialV1(JSON.stringify(input)); let info: UnsignedCdiWithRandomness; diff --git a/packages/sdk/test/ci/accountTransactions.test.ts b/packages/sdk/test/ci/accountTransactions.test.ts index 2f8c6d591..ad803b49f 100644 --- a/packages/sdk/test/ci/accountTransactions.test.ts +++ b/packages/sdk/test/ci/accountTransactions.test.ts @@ -1,5 +1,5 @@ import * as AccountAddress from '../../src/types/AccountAddress.js'; -import { TransactionExpiry } from '../../src/types/transactionExpiry.js'; +import * as TransactionExpiry from '../../src/types/TransactionExpiry.js'; import { OpenStatus, AccountTransaction, @@ -18,7 +18,7 @@ test('configureBaker is serialized correctly', async () => { const expectedDigest = 'dcfb92b6e57b1d3e252c52cb8b838f44a33bf8d67301e89753101912f299dffb'; - const expiry = new TransactionExpiry(new Date(1675872215), true); + const expiry = TransactionExpiry.fromDate(new Date(1675872215)); const header: AccountTransactionHeader = { expiry, @@ -27,7 +27,7 @@ test('configureBaker is serialized correctly', async () => { }; const payload: Required = { - stake: new CcdAmount(1000000000n), + stake: CcdAmount.fromMicroCcd(1000000000n), restakeEarnings: true, openForDelegation: OpenStatus.ClosedForAll, keys: { diff --git a/packages/sdk/test/ci/deserialization.test.ts b/packages/sdk/test/ci/deserialization.test.ts index 411ac63a5..328619371 100644 --- a/packages/sdk/test/ci/deserialization.test.ts +++ b/packages/sdk/test/ci/deserialization.test.ts @@ -24,7 +24,7 @@ import { function deserializeAccountTransactionBase( type: AccountTransactionType, payload: AccountTransactionPayload, - expiry = new TransactionExpiry(new Date(Date.now() + 1200000)) + expiry = TransactionExpiry.futureMinutes(20) ) { const header: AccountTransactionHeader = { expiry, @@ -62,7 +62,7 @@ function deserializeAccountTransactionBase( test('test deserialize simpleTransfer ', () => { const payload: SimpleTransferPayload = { - amount: new CcdAmount(5100000n), + amount: CcdAmount.fromMicroCcd(5100000), toAddress: AccountAddress.fromBase58( '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt' ), @@ -72,7 +72,7 @@ test('test deserialize simpleTransfer ', () => { test('test deserialize simpleTransfer with memo ', () => { const payload: SimpleTransferWithMemoPayload = { - amount: new CcdAmount(5100000n), + amount: CcdAmount.fromMicroCcd(5100000), toAddress: AccountAddress.fromBase58( '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt' ), @@ -96,7 +96,7 @@ test('test deserialize registerData ', () => { test('Expired transactions can be deserialized', () => { const payload: SimpleTransferPayload = { - amount: new CcdAmount(5100000n), + amount: CcdAmount.fromMicroCcd(5100000), toAddress: AccountAddress.fromBase58( '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt' ), @@ -104,7 +104,7 @@ test('Expired transactions can be deserialized', () => { deserializeAccountTransactionBase( AccountTransactionType.Transfer, payload, - new TransactionExpiry(new Date(2000, 1), true) + TransactionExpiry.fromDate(new Date(2000, 1)) ); }); diff --git a/packages/sdk/test/ci/serialization.test.ts b/packages/sdk/test/ci/serialization.test.ts index 9a9ed66fc..476ffb7c5 100644 --- a/packages/sdk/test/ci/serialization.test.ts +++ b/packages/sdk/test/ci/serialization.test.ts @@ -1,5 +1,5 @@ import * as AccountAddress from '../../src/types/AccountAddress.js'; -import { CcdAmount } from '../../src/types/ccdAmount.js'; +import * as CcdAmount from '../../src/types/CcdAmount.js'; import { serializeAccountTransactionForSubmission, serializeAccountTransactionSignature, @@ -11,19 +11,19 @@ import { AccountTransactionType, SimpleTransferPayload, } from '../../src/types.js'; -import { TransactionExpiry } from '../../src/types/transactionExpiry.js'; -import { SequenceNumber } from '../../src/index.js'; +import * as TransactionExpiry from '../../src/types/TransactionExpiry.js'; +import * as SequenceNumber from '../../src/types/SequenceNumber.js'; test('fail account transaction serialization if no signatures', () => { const simpleTransferPayload: SimpleTransferPayload = { - amount: new CcdAmount(5100000n), + amount: CcdAmount.fromMicroCcd(5100000n), toAddress: AccountAddress.fromBase58( '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt' ), }; const header: AccountTransactionHeader = { - expiry: new TransactionExpiry(new Date(Date.now() + 1200000)), + expiry: TransactionExpiry.futureMinutes(20), nonce: SequenceNumber.create(1), sender: AccountAddress.fromBase58( '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt' diff --git a/packages/sdk/test/ci/types/blockItemSummary.test.ts b/packages/sdk/test/ci/types/blockItemSummary.test.ts index 5e48c9b51..9f13b1333 100644 --- a/packages/sdk/test/ci/types/blockItemSummary.test.ts +++ b/packages/sdk/test/ci/types/blockItemSummary.test.ts @@ -27,6 +27,7 @@ import { InitName, Parameter, ReceiveName, + CcdAmount, } from '../../../src/index.js'; const chainUpdate: UpdateSummary = { @@ -66,7 +67,7 @@ const contractInit: InitContractSummary & BaseAccountTransactionSummary = { contractInitialized: { tag: TransactionEventTag.ContractInitialized, address: ContractAddress.create(4416), - amount: 0n, + amount: CcdAmount.zero(), initName: InitName.fromStringUnchecked('init_cis2-receive-test'), events: [], contractVersion: 1, @@ -97,7 +98,7 @@ const contractUpdate: UpdateContractSummary & BaseAccountTransactionSummary = { '4UC8o4m8AgTxt5VBFMdLwMCwwJQVJwjesNzW7RPXkACynrULmd' ), }, - amount: 0n, + amount: CcdAmount.zero(), message: Parameter.fromHexString( '0100006400c8d4bb7106a96bfa6f069438270bf9748049c24798b13b08f88fc2f46afb435f0087e3bec61b8db2fb7389b57d2be4f7dd95d1088dfeb6ef7352c13d2b2d27bb490000' ), @@ -125,7 +126,7 @@ const contractUpdate: UpdateContractSummary & BaseAccountTransactionSummary = { '4UC8o4m8AgTxt5VBFMdLwMCwwJQVJwjesNzW7RPXkACynrULmd' ), }, - amount: 0n, + amount: CcdAmount.zero(), message: Parameter.fromHexString( '0100006400c8d4bb7106a96bfa6f069438270bf9748049c24798b13b08f88fc2f46afb435f0087e3bec61b8db2fb7389b57d2be4f7dd95d1088dfeb6ef7352c13d2b2d27bb490000' ), @@ -138,7 +139,7 @@ const contractUpdate: UpdateContractSummary & BaseAccountTransactionSummary = { }, { tag: TransactionEventTag.Transferred, - amount: 0n, + amount: CcdAmount.zero(), to: AccountAddress.fromBase58( '4UC8o4m8AgTxt5VBFMdLwMCwwJQVJwjesNzW7RPXkACynrULmd' ), @@ -146,7 +147,7 @@ const contractUpdate: UpdateContractSummary & BaseAccountTransactionSummary = { }, { tag: TransactionEventTag.Transferred, - amount: 0n, + amount: CcdAmount.zero(), to: AccountAddress.fromBase58( '3ybJ66spZ2xdWF3avgxQb2meouYa7mpvMWNPmUnczU8FoF8cGB' ), @@ -171,10 +172,13 @@ const rejected: FailedTransactionSummary & BaseAccountTransactionSummary = { rejectReason: { tag: RejectReasonTag.RejectedReceive, contractAddress: ContractAddress.create(3496), - receiveName: 'cis2-bridgeable.transfer', + receiveName: ReceiveName.fromStringUnchecked( + 'cis2-bridgeable.transfer' + ), rejectReason: -5, - parameter: - '0100006400c8d4bb7106a96bfa6f069438270bf9748049c24798b13b08f88fc2f46afb435f01271100000000000000000000000000000f006f6e526563656976696e67434953320000', + parameter: Parameter.fromHexString( + '0100006400c8d4bb7106a96bfa6f069438270bf9748049c24798b13b08f88fc2f46afb435f01271100000000000000000000000000000f006f6e526563656976696e67434953320000' + ), }, }; @@ -192,7 +196,7 @@ const transfer: BaseAccountTransactionSummary & TransferSummary = { transactionType: TransactionKindString.Transfer, transfer: { tag: TransactionEventTag.Transferred, - amount: 2000000000n, + amount: CcdAmount.fromCcd(2000), to: AccountAddress.fromBase58( '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' ), @@ -213,7 +217,7 @@ const transferToSelf: BaseAccountTransactionSummary & TransferSummary = { transactionType: TransactionKindString.Transfer, transfer: { tag: TransactionEventTag.Transferred, - amount: 2000000000n, + amount: CcdAmount.fromCcd(2000), to: AccountAddress.fromBase58( '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' ), @@ -263,7 +267,7 @@ const configureDelegation: BaseAccountTransactionSummary & { tag: TransactionEventTag.DelegationStakeIncreased, delegatorId: 2499n, - newStake: 240000000n, + newStake: CcdAmount.fromMicroCcd(240000000n), account: AccountAddress.fromBase58( '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' ), diff --git a/packages/sdk/test/ci/types/blockSpecialEvents.test.ts b/packages/sdk/test/ci/types/blockSpecialEvents.test.ts index 7d33a406a..f3b62df8a 100644 --- a/packages/sdk/test/ci/types/blockSpecialEvents.test.ts +++ b/packages/sdk/test/ci/types/blockSpecialEvents.test.ts @@ -8,99 +8,123 @@ import { BlockSpecialEventPaydayAccountReward, BlockSpecialEventBlockReward, specialEventAffectedAccounts, + CcdAmount, + AccountAddress, } from '../../../src/index.js'; const bakingRewards: BlockSpecialEventBakingRewards = { tag: 'bakingRewards', - remainder: 0n, + remainder: CcdAmount.zero(), bakingRewards: [ { - account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - amount: 400000n, + account: AccountAddress.fromBase58( + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' + ), + amount: CcdAmount.fromMicroCcd(400000), }, { - account: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - amount: 400000n, + account: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), + amount: CcdAmount.fromMicroCcd(400000), }, ], }; const finalizationRewards: BlockSpecialEventFinalizationRewards = { tag: 'finalizationRewards', - remainder: 0n, + remainder: CcdAmount.zero(), finalizationRewards: [ { - account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - amount: 400000n, + account: AccountAddress.fromBase58( + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' + ), + amount: CcdAmount.fromMicroCcd(400000), }, { - account: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - amount: 400000n, + account: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), + amount: CcdAmount.fromMicroCcd(400000), }, ], }; const foundationReward: BlockSpecialEventPaydayFoundationReward = { tag: 'paydayFoundationReward', - developmentCharge: 123n, - foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + developmentCharge: CcdAmount.fromMicroCcd(123), + foundationAccount: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), }; const mint: BlockSpecialEventMint = { tag: 'mint', - mintBakingReward: 0n, - mintFinalizationReward: 0n, - mintPlatformDevelopmentCharge: 0n, - foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + mintBakingReward: CcdAmount.zero(), + mintFinalizationReward: CcdAmount.zero(), + mintPlatformDevelopmentCharge: CcdAmount.zero(), + foundationAccount: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), }; const paydayAccountReward: BlockSpecialEventPaydayAccountReward = { tag: 'paydayAccountReward', - account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - transactionFees: 123n, - bakerReward: 123n, - finalizationReward: 123n, + account: AccountAddress.fromBase58( + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' + ), + transactionFees: CcdAmount.fromMicroCcd(123), + bakerReward: CcdAmount.fromMicroCcd(123), + finalizationReward: CcdAmount.fromMicroCcd(123), }; const foundationBlockReward: BlockSpecialEventBlockReward = { tag: 'blockReward', - transactionFees: 1231241n, - bakerReward: 12314n, - foundationCharge: 12n, - newGasAccount: 1n, - oldGasAccount: 0n, - baker: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + transactionFees: CcdAmount.fromMicroCcd(1231241), + bakerReward: CcdAmount.fromMicroCcd(12314), + foundationCharge: CcdAmount.fromMicroCcd(12), + newGasAccount: CcdAmount.fromMicroCcd(1), + oldGasAccount: CcdAmount.zero(), + baker: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), + foundationAccount: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), }; const blockReward: BlockSpecialEventBlockReward = { tag: 'blockReward', - transactionFees: 1231241n, - bakerReward: 12314n, - foundationCharge: 12n, - newGasAccount: 1n, - oldGasAccount: 0n, - baker: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + transactionFees: CcdAmount.fromMicroCcd(1231241), + bakerReward: CcdAmount.fromMicroCcd(12314), + foundationCharge: CcdAmount.fromMicroCcd(12), + newGasAccount: CcdAmount.fromMicroCcd(1), + oldGasAccount: CcdAmount.zero(), + baker: AccountAddress.fromBase58( + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe' + ), + foundationAccount: AccountAddress.fromBase58( + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV' + ), }; const paydayPoolReward: BlockSpecialEventPaydayPoolReward = { tag: 'paydayPoolReward', poolOwner: 123n, - finalizationReward: 123n, - bakerReward: 12314n, - transactionFees: 1231241n, + finalizationReward: CcdAmount.fromMicroCcd(123), + bakerReward: CcdAmount.fromMicroCcd(12314), + transactionFees: CcdAmount.fromMicroCcd(1231241), }; const accrueReward: BlockSpecialEventBlockAccrueReward = { tag: 'blockAccrueReward', - transactionFees: 1231241n, - bakerReward: 12314n, + transactionFees: CcdAmount.fromMicroCcd(1231241), + bakerReward: CcdAmount.fromMicroCcd(12314), baker: 0n, - foundationCharge: 12n, - newGasAccount: 1n, - oldGasAccount: 0n, - passiveReward: 123n, + foundationCharge: CcdAmount.fromMicroCcd(12), + newGasAccount: CcdAmount.fromMicroCcd(1), + oldGasAccount: CcdAmount.zero(), + passiveReward: CcdAmount.fromMicroCcd(123), }; describe('specialEventAffectedAccounts', () => { @@ -114,41 +138,55 @@ describe('specialEventAffectedAccounts', () => { test('Returns correct list of accounts for events with account payouts', () => { let accounts = specialEventAffectedAccounts(bakingRewards); - expect(accounts).toEqual([ - '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + [ + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + ].map(AccountAddress.fromBase58) + ); accounts = specialEventAffectedAccounts(finalizationRewards); - expect(accounts).toEqual([ - '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + [ + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + ].map(AccountAddress.fromBase58) + ); accounts = specialEventAffectedAccounts(foundationReward); - expect(accounts).toEqual([ - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + ['3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV'].map( + AccountAddress.fromBase58 + ) + ); accounts = specialEventAffectedAccounts(mint); - expect(accounts).toEqual([ - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + ['3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV'].map( + AccountAddress.fromBase58 + ) + ); accounts = specialEventAffectedAccounts(paydayAccountReward); - expect(accounts).toEqual([ - '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - ]); + expect(accounts).toEqual( + ['4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe'].map( + AccountAddress.fromBase58 + ) + ); accounts = specialEventAffectedAccounts(foundationBlockReward); - expect(accounts).toEqual([ - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + ['3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV'].map( + AccountAddress.fromBase58 + ) + ); accounts = specialEventAffectedAccounts(blockReward); - expect(accounts).toEqual([ - '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', - '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', - ]); + expect(accounts).toEqual( + [ + '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe', + '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV', + ].map(AccountAddress.fromBase58) + ); }); }); diff --git a/packages/sdk/test/ci/types/ccdAmount.test.ts b/packages/sdk/test/ci/types/ccdAmount.test.ts index a213535b7..7a0ef3517 100644 --- a/packages/sdk/test/ci/types/ccdAmount.test.ts +++ b/packages/sdk/test/ci/types/ccdAmount.test.ts @@ -29,17 +29,17 @@ describe('To and from ccd as strings', () => { }); test('Returns correct amount of CCD, test 1', () => { - const ccd = new CcdAmount(1000n); - expect(ccd.toCcd()).toEqual(Big('0.001')); + const ccd = CcdAmount.fromMicroCcd(1000); + expect(CcdAmount.toCcd(ccd)).toEqual(Big('0.001')); }); test('Returns correct amount of CCD, test 2', () => { - const ccd = new CcdAmount(123456789n); - expect(ccd.toCcd()).toEqual(Big('123.456789')); + const ccd = CcdAmount.fromMicroCcd(123456789); + expect(CcdAmount.toCcd(ccd)).toEqual(Big('123.456789')); }); test('FromCcd correctly takes comma as a decimal seperator', () => { - expect(CcdAmount.fromCcd('10,000').toCcd()).toEqual(Big('10')); + expect(CcdAmount.toCcd(CcdAmount.fromCcd('10,000'))).toEqual(Big('10')); }); test('CcdAmount constructor correctly rejects multiple comma seperators', () => { @@ -55,7 +55,7 @@ describe('To and from ccd as strings', () => { }); test('toCcd is equal to microCcdToCcd', () => { - const ccd1 = new CcdAmount('1').toCcd(); + const ccd1 = CcdAmount.toCcd(CcdAmount.fromMicroCcd('1')); const ccd2 = CcdAmount.microCcdToCcd('1'); expect(ccd1).toEqual(ccd2); }); diff --git a/packages/sdk/test/client/clientV2.test.ts b/packages/sdk/test/client/clientV2.test.ts index b9be60d9a..99ee3e76e 100644 --- a/packages/sdk/test/client/clientV2.test.ts +++ b/packages/sdk/test/client/clientV2.test.ts @@ -190,7 +190,6 @@ test.each([clientV2, clientWeb])( 'getPassiveDelegationInfo corresponds to getPoolStatus with no bakerId', async (client) => { const status = await client.getPassiveDelegationInfo(testBlockHash); - expect(status).toEqual(expected.passiveDelegationStatus); } ); @@ -253,7 +252,7 @@ test.each([clientV2, clientWeb])('Failed invoke contract', async (client) => { invoker: testAccount, contract: v1.ContractAddress.create(6), method: v1.ReceiveName.fromStringUnchecked('PiggyBank.smash'), - amount: new v1.CcdAmount(0n), + amount: v1.CcdAmount.zero(), parameter: undefined, energy: v1.Energy.create(30000), }, @@ -276,7 +275,7 @@ test.each([clientV2, clientWeb])( invoker: testAccount, contract: v1.ContractAddress.create(6), method: v1.ReceiveName.fromStringUnchecked('PiggyBank.insert'), - amount: new v1.CcdAmount(1n), + amount: v1.CcdAmount.fromMicroCcd(1n), parameter: undefined, energy: v1.Energy.create(30000), }, @@ -294,7 +293,7 @@ test.each([clientV2, clientWeb])( invoker: testAccount, contract: v1.ContractAddress.create(81), method: v1.ReceiveName.fromStringUnchecked('PiggyBank.view'), - amount: new v1.CcdAmount(0n), + amount: v1.CcdAmount.zero(), parameter: undefined, energy: v1.Energy.create(30000), }; @@ -308,11 +307,8 @@ test.each([clientV2, clientWeb])('getModuleSource', async (client) => { const localModuleBytes = getModuleBuffer( 'test/client/resources/piggy_bank.wasm' ); - const moduleRef = new v1.ModuleReference( - Buffer.from( - 'foOYrcQGqX202GnD/XrcgToxg2Z6On2weOuub33OX2Q=', - 'base64' - ).toString('hex') + const moduleRef = v1.ModuleReference.fromBuffer( + Buffer.from('foOYrcQGqX202GnD/XrcgToxg2Z6On2weOuub33OX2Q=', 'base64') ); const localModuleHex = Buffer.from(localModuleBytes); @@ -349,12 +345,12 @@ test.each([clientV2, clientWeb])('sendBlockItem', async (client) => { // Create local transaction const header: v1.AccountTransactionHeader = { - expiry: new v1.TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: v1.TransactionExpiry.futureMinutes(60), nonce: nextNonce.nonce, sender: senderAccount, }; const simpleTransfer: v1.SimpleTransferPayload = { - amount: new v1.CcdAmount(10000000000n), + amount: v1.CcdAmount.fromCcd(10_000), toAddress: testAccount, }; const accountTransaction: v1.AccountTransaction = { @@ -385,12 +381,12 @@ test.each([clientV2, clientWeb])('transactionHash', async (client) => { // Create local transaction const headerLocal: v1.AccountTransactionHeader = { - expiry: new v1.TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: v1.TransactionExpiry.futureMinutes(60), nonce: nextNonce.nonce, sender: senderAccount, }; const simpleTransfer: v1.SimpleTransferPayload = { - amount: new v1.CcdAmount(10000000000n), + amount: v1.CcdAmount.fromCcd(10_000), toAddress: testAccount, }; const transaction: v1.AccountTransaction = { @@ -470,7 +466,7 @@ test.each([clientV2, clientWeb])('createAccount', async (client) => { const identityInput: v1.IdentityInput = getIdentityInput(); const threshold = 1; const credentialIndex = 1; - const expiry = new v1.TransactionExpiry(new Date(Date.now() + 3600000)); + const expiry = v1.TransactionExpiry.futureMinutes(60); const revealedAttributes: v1.AttributeKey[] = []; const publicKeys: v1.VerifyKey[] = [ { @@ -747,7 +743,7 @@ test.each([clientV2, clientWeb])( test.each([clientV2, clientWeb])('getEmbeddedSchema', async (client) => { const contract = v1.ContractAddress.create(4422); - const moduleRef = new v1.ModuleReference( + const moduleRef = v1.ModuleReference.fromHexString( '44434352ddba724930d6b1b09cd58bd1fba6ad9714cf519566d5fe72d80da0d1' ); diff --git a/packages/sdk/test/client/credentialDeployment.test.ts b/packages/sdk/test/client/credentialDeployment.test.ts index 3aa2c6b1b..2f3a1e47c 100644 --- a/packages/sdk/test/client/credentialDeployment.test.ts +++ b/packages/sdk/test/client/credentialDeployment.test.ts @@ -46,7 +46,7 @@ test('test deserialize credentialDeployment ', async () => { // The attributes to reveal on the chain. const revealedAttributes: AttributeKey[] = ['firstName', 'nationality']; - const expiry = new TransactionExpiry(new Date(Date.now() + 3600000)); + const expiry = TransactionExpiry.futureMinutes(60); const credentialDeploymentTransaction: CredentialDeploymentTransaction = createCredentialDeploymentTransaction( identityInput, diff --git a/packages/sdk/test/client/manualTests.test.ts b/packages/sdk/test/client/manualTests.test.ts index 51a9c98b6..b97fc6718 100644 --- a/packages/sdk/test/client/manualTests.test.ts +++ b/packages/sdk/test/client/manualTests.test.ts @@ -21,12 +21,12 @@ describe.skip('Manual test suite', () => { // Create local transaction const header: v1.AccountTransactionHeader = { - expiry: new v1.TransactionExpiry(new Date(Date.now() + 3600000)), + expiry: v1.TransactionExpiry.futureMinutes(60), nonce: nonce, sender: senderAccount, }; const simpleTransfer: v1.SimpleTransferPayload = { - amount: new v1.CcdAmount(100n), + amount: v1.CcdAmount.fromMicroCcd(100), toAddress: testAccount, }; const accountTransaction: v1.AccountTransaction = { diff --git a/packages/sdk/test/client/resources/expectedJsons.ts b/packages/sdk/test/client/resources/expectedJsons.ts index e5ddf3219..c48d25db0 100644 --- a/packages/sdk/test/client/resources/expectedJsons.ts +++ b/packages/sdk/test/client/resources/expectedJsons.ts @@ -17,6 +17,13 @@ import { BlockItemStatus, BlockItemSummary, BlockSpecialEvent, + BlockSpecialEventBakingRewards, + BlockSpecialEventBlockAccrueReward, + BlockSpecialEventBlockReward, + BlockSpecialEventFinalizationRewards, + BlockSpecialEventPaydayAccountReward, + BlockSpecialEventPaydayFoundationReward, + BlockSpecialEventPaydayPoolReward, CcdAmount, ChainParametersV0, ChainParametersV1, @@ -44,9 +51,11 @@ import { NextUpdateSequenceNumbers, OpenStatusText, Parameter, + PassiveDelegationStatus, PendingUpdate, PoolStatusType, ReceiveName, + RejectReason, RejectReasonTag, RejectedReceive, ReturnValue, @@ -235,7 +244,7 @@ export const blockItemStatusTransfer: BlockItemStatus = { ), transactionType: TransactionKindString.Transfer, transfer: { - amount: 1000000n, + amount: CcdAmount.fromMicroCcd(1000000), tag: TransactionEventTag.Transferred, to: AccountAddress.fromBase58( '3BpVX13dw29JruyMzCfde96hoB7DtQ53WMGVDMrmPtuYAbzADj' @@ -250,12 +259,12 @@ export const instanceInfo: InstanceInfo = { owner: AccountAddress.fromBase58( '4Y1c27ZRpRut9av69n3i1uhfeDp4XGuvsm9fkEjFvgpoxXWxQB' ), - amount: new CcdAmount(0n), + amount: CcdAmount.zero(), methods: ['weather.get', 'weather.set'].map( ReceiveName.fromStringUnchecked ), name: InitName.fromStringUnchecked('init_weather'), - sourceModule: new ModuleReference( + sourceModule: ModuleReference.fromHexString( '67d568433bd72e4326241f262213d77f446db8ba03dfba351ae35c1b2e7e5109' ), }; @@ -268,7 +277,7 @@ export const invokeInstanceResponseV0: InvokeContractResult = { { tag: TransactionEventTag.Updated, events: [], - amount: 1n, + amount: CcdAmount.fromMicroCcd(1), address: ContractAddress.create(6), contractVersion: 0, instigator: { @@ -405,31 +414,31 @@ export const delegatorInfoList: DelegatorInfo[] = [ account: AccountAddress.fromBase58( '3uX8g2uzQwBjVSJ6ZDU5cQCKhgsET6kMuRoraQH2ANB9Xa84YR' ), - stake: 40000000000n, + stake: CcdAmount.fromMicroCcd(40_000_000_000), }, { account: AccountAddress.fromBase58( '4mAs6xcFw26fb6u8odkJWoe3fAK8bCJ91BwScUc36DFhh3thwD' ), - stake: 10000000n, + stake: CcdAmount.fromMicroCcd(10_000_000), }, { account: AccountAddress.fromBase58( '3NvUNvVm5puDT2EYbo7hCF3d5AwzzCqKE18Ms6BYkKY9UShdf3' ), - stake: 3000000000n, + stake: CcdAmount.fromMicroCcd(3000_000_000), }, { account: AccountAddress.fromBase58( '3ivPxmqdRk5TX5mKpFshKzrA44bYUW2tg6EwDPvALszNoBGTK9' ), - stake: 33000000n, + stake: CcdAmount.fromMicroCcd(33_000_000), }, { account: AccountAddress.fromBase58( '37tU96v4MQSaEgVP68M3TBRHMwZpgYSGnMer3ta3FJ8wkXtjDQ' ), - stake: 94000000n, + stake: CcdAmount.fromMicroCcd(94_000_000), }, ]; @@ -438,19 +447,19 @@ export const passiveDelegatorInfoList: DelegatorInfo[] = [ account: AccountAddress.fromBase58( '4gCvJ91EeYzsTzwiC7Kr4AcFzSuDmf5wxev7FRzU3uw49WamBm' ), - stake: 1900000000n, + stake: CcdAmount.fromMicroCcd(1_900_000_000), }, { account: AccountAddress.fromBase58( '4mQweXtq3zHwS7CtK5fjWkpJDUvtUSKycNa8xaEbe6kErGeXcL' ), - stake: 1000000000n, + stake: CcdAmount.fromMicroCcd(1_000_000_000), }, { account: AccountAddress.fromBase58( '3irV7FF3BZbz9ejGTm7EHLUi6CQHdJUELDfyhwkHcLqXmQyUfR' ), - stake: 100000000n, + stake: CcdAmount.fromMicroCcd(100_000_000), pendingChange: { effectiveTime: new Date('2022-06-28T11:47:37.750Z'), change: StakePendingChangeType.RemoveStake, @@ -463,13 +472,13 @@ export const passiveDelegatorRewardInfoList: DelegatorRewardPeriodInfo[] = [ account: AccountAddress.fromBase58( '4gCvJ91EeYzsTzwiC7Kr4AcFzSuDmf5wxev7FRzU3uw49WamBm' ), - stake: 1900000000n, + stake: CcdAmount.fromMicroCcd(1_900_000_000), }, { account: AccountAddress.fromBase58( '4mQweXtq3zHwS7CtK5fjWkpJDUvtUSKycNa8xaEbe6kErGeXcL' ), - stake: 1000000000n, + stake: CcdAmount.fromMicroCcd(1_000_000_000), }, ]; @@ -603,12 +612,12 @@ export const seqNums: NextUpdateSequenceNumbers = { export const specialEventList: BlockSpecialEvent[] = [ { tag: 'blockAccrueReward', - transactionFees: 0n, - oldGasAccount: 293604n, - newGasAccount: 219102n, - bakerReward: 74502n, - passiveReward: 0n, - foundationCharge: 0n, + transactionFees: CcdAmount.zero(), + oldGasAccount: CcdAmount.fromMicroCcd(293604), + newGasAccount: CcdAmount.fromMicroCcd(219102), + bakerReward: CcdAmount.fromMicroCcd(74502), + passiveReward: CcdAmount.zero(), + foundationCharge: CcdAmount.zero(), baker: 4n, }, ]; @@ -684,7 +693,7 @@ export const transferToPublicEvent: [ account: AccountAddress.fromBase58( '3BpVX13dw29JruyMzCfde96hoB7DtQ53WMGVDMrmPtuYAbzADj' ), - amount: 1000000n, + amount: CcdAmount.fromMicroCcd(1_000_000), }, ]; @@ -702,7 +711,7 @@ export const configureBaker: BakerEvent[] = [ restakeEarnings: true, signKey: '0055703a2615746700b58e312aa428e5526993d6d3f3f109db92436115d63818', - stake: 15000000000n, + stake: CcdAmount.fromMicroCcd(15000000000n), }, { tag: TransactionEventTag.BakerSetRestakeEarnings, @@ -793,7 +802,7 @@ export const configureDelegation: DelegationEvent[] = [ '3BpVX13dw29JruyMzCfde96hoB7DtQ53WMGVDMrmPtuYAbzADj' ), delegatorId: 2059n, - newStake: 1000000n, + newStake: CcdAmount.fromMicroCcd(1000000n), tag: TransactionEventTag.DelegationStakeIncreased, }, ]; @@ -811,7 +820,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(864), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -836,7 +845,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(864), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -863,7 +872,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(864), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -894,7 +903,7 @@ export const updateEvent: ContractTraceEvent[] = [ tag: TransactionEventTag.Interrupted, }, { - amount: 1000000n, + amount: CcdAmount.fromMicroCcd(1000000n), from: ContractAddress.create(866), tag: TransactionEventTag.Transferred, to: AccountAddress.fromBase58( @@ -908,7 +917,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(866), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -935,7 +944,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(866), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [ 'fd00c0843d00e9f89f76878691716298685f21637d86fd8c98de7baa1d67e0ce11241be00083', @@ -959,7 +968,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(865), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -979,7 +988,7 @@ export const updateEvent: ContractTraceEvent[] = [ }, { address: ContractAddress.create(866), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], instigator: { @@ -1000,7 +1009,7 @@ export const encryptedSelfAmountAddedEvent: EncryptedSelfAmountAddedEvent = { account: AccountAddress.fromBase58( '3BpVX13dw29JruyMzCfde96hoB7DtQ53WMGVDMrmPtuYAbzADj' ), - amount: 10000000n, + amount: CcdAmount.fromMicroCcd(10000000n), newAmount: 'c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000098c71824023d5fb1bca5accb3ac010551e4af7e9988cd0ef309ee37149ef7843af6f294e79b8fcbda9b4f4ed094d66cbc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', tag: TransactionEventTag.EncryptedSelfAmountAdded, @@ -1034,11 +1043,11 @@ export const transferWithScheduleEvent: TransferredWithScheduleEvent = { amount: [ { timestamp: new Date('2023-01-10T12:00:00.919Z'), - amount: 500000n, + amount: CcdAmount.fromMicroCcd(500000n), }, { timestamp: new Date('2023-02-10T12:00:00.919Z'), - amount: 500000n, + amount: CcdAmount.fromMicroCcd(500000n), }, ], }; @@ -1046,7 +1055,7 @@ export const transferWithScheduleEvent: TransferredWithScheduleEvent = { export const contractInitializedEvent: ContractInitializedEvent = { tag: TransactionEventTag.ContractInitialized, address: ContractAddress.create(3132), - amount: 0n, + amount: CcdAmount.zero(), contractVersion: 1, events: [], initName: InitName.fromStringUnchecked('init_CIS2-Fractionalizer'), @@ -1082,7 +1091,7 @@ export const transferWithMemoSummary: BaseAccountTransactionSummary & transactionType: TransactionKindString.TransferWithMemo, transfer: { tag: TransactionEventTag.Transferred, - amount: 250000000n, + amount: CcdAmount.fromMicroCcd(250000000n), to: AccountAddress.fromBase58( '4fxkFceRT3XyUpb4yW3C2c9RnEBhunyNrKprYarr7htKmMvztG' ), @@ -1130,7 +1139,7 @@ export const bakerStakeIncreasedEvent: BakerEvent = { '4JzAXhzJKwG3DGoAbgGhZNnRQqeFdp9zbxv6WUjDbVbyKEie8e' ), bakerId: 525n, - newStake: 14001000000n, + newStake: CcdAmount.fromMicroCcd(14001000000n), tag: TransactionEventTag.BakerStakeIncreased, }; @@ -1155,7 +1164,7 @@ export const bakerStakeDecreasedEvent: BakerEvent = { '4Kmo9keJQaiyAuRM2pRh2xK4e75ph7hp4CzxdFAcRDeQRHfaHT' ), bakerId: 15n, - newStake: 950000000000n, + newStake: CcdAmount.fromMicroCcd(950000000000n), }; export const delegationStakeDecreasedEvent: DelegationEvent = { @@ -1164,160 +1173,218 @@ export const delegationStakeDecreasedEvent: DelegationEvent = { '4mAs6xcFw26fb6u8odkJWoe3fAK8bCJ91BwScUc36DFhh3thwD' ), delegatorId: 57n, - newStake: 10000000n, + newStake: CcdAmount.fromMicroCcd(10000000n), }; export const mintSpecialEvent: BlockSpecialEvent = { tag: 'mint', - mintBakingReward: 12708081798618n, - mintFinalizationReward: 6354040899309n, - mintPlatformDevelopmentCharge: 2118013633103n, - foundationAccount: '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G', + mintBakingReward: CcdAmount.fromMicroCcd(12708081798618n), + mintFinalizationReward: CcdAmount.fromMicroCcd(6354040899309n), + mintPlatformDevelopmentCharge: CcdAmount.fromMicroCcd(2118013633103n), + foundationAccount: AccountAddress.fromBase58( + '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G' + ), }; -export const paydayFoundationRewardSpecialEvent = { - tag: 'paydayFoundationReward', - foundationAccount: '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G', - developmentCharge: 103517862n, -}; +export const paydayFoundationRewardSpecialEvent: BlockSpecialEventPaydayFoundationReward = + { + tag: 'paydayFoundationReward', + foundationAccount: AccountAddress.fromBase58( + '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G' + ), + developmentCharge: CcdAmount.fromMicroCcd(103517862n), + }; -export const paydayPoolRewardSpecialEvent = { +export const paydayPoolRewardSpecialEvent: BlockSpecialEventPaydayPoolReward = { tag: 'paydayPoolReward', - transactionFees: 0n, - bakerReward: 0n, - finalizationReward: 0n, -}; - -export const paydayAccountRewardSpecialEvent = { - tag: 'paydayAccountReward', - account: '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn', - transactionFees: 128913265n, - bakerReward: 1139222197711n, - finalizationReward: 577640081755n, + transactionFees: CcdAmount.zero(), + bakerReward: CcdAmount.zero(), + finalizationReward: CcdAmount.zero(), }; -export const blockAccrueRewardSpecialEvent = { - tag: 'blockAccrueReward', - transactionFees: 0n, - oldGasAccount: 3n, - newGasAccount: 3n, - bakerReward: 0n, - passiveReward: 0n, - foundationCharge: 0n, - baker: 6n, -}; +export const paydayAccountRewardSpecialEvent: BlockSpecialEventPaydayAccountReward = + { + tag: 'paydayAccountReward', + account: AccountAddress.fromBase58( + '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn' + ), + transactionFees: CcdAmount.fromMicroCcd(128913265n), + bakerReward: CcdAmount.fromMicroCcd(1139222197711n), + finalizationReward: CcdAmount.fromMicroCcd(577640081755n), + }; -export const bakingRewardsSpecialEvent = { +export const blockAccrueRewardSpecialEvent: BlockSpecialEventBlockAccrueReward = + { + tag: 'blockAccrueReward', + transactionFees: CcdAmount.zero(), + oldGasAccount: CcdAmount.fromMicroCcd(3n), + newGasAccount: CcdAmount.fromMicroCcd(3n), + bakerReward: CcdAmount.zero(), + passiveReward: CcdAmount.zero(), + foundationCharge: CcdAmount.zero(), + baker: 6n, + }; + +export const bakingRewardsSpecialEvent: BlockSpecialEventBakingRewards = { tag: 'bakingRewards', bakingRewards: [ { - account: '3QK1rxUXV7GRk4Ng7Bs7qnbkdjyBdjzCytpTrSQN7BaJkiEfgZ', - amount: 56740641000n, + account: AccountAddress.fromBase58( + '3QK1rxUXV7GRk4Ng7Bs7qnbkdjyBdjzCytpTrSQN7BaJkiEfgZ' + ), + amount: CcdAmount.fromMicroCcd(56740641000n), }, { - account: '3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini', - amount: 32625868575n, + account: AccountAddress.fromBase58( + '3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini' + ), + amount: CcdAmount.fromMicroCcd(32625868575n), }, { - account: '3gGBYDSpx2zWL3YMcqD48U5jVXYG4pJBDZqeY5CbMMKpxVBbc3', - amount: 39718448700n, + account: AccountAddress.fromBase58( + '3gGBYDSpx2zWL3YMcqD48U5jVXYG4pJBDZqeY5CbMMKpxVBbc3' + ), + amount: CcdAmount.fromMicroCcd(39718448700n), }, { - account: '3ntvNGT6tDuLYiSb5gMJSQAZfLPUJnzoizcFiVRWqLoctuXxpK', - amount: 41136964725n, + account: AccountAddress.fromBase58( + '3ntvNGT6tDuLYiSb5gMJSQAZfLPUJnzoizcFiVRWqLoctuXxpK' + ), + amount: CcdAmount.fromMicroCcd(41136964725n), }, { - account: '3y9DtDUL8xpf8i2yj9k44zMVkf4H1hkpBEQcXbJhrgcwYSGg41', - amount: 35462900625n, + account: AccountAddress.fromBase58( + '3y9DtDUL8xpf8i2yj9k44zMVkf4H1hkpBEQcXbJhrgcwYSGg41' + ), + amount: CcdAmount.fromMicroCcd(35462900625n), }, { - account: '42tFTDWvTmBd7hEacohuCfGFa9TsBKhsmXKeViQ7q7NoY7UadV', - amount: 49648060875n, + account: AccountAddress.fromBase58( + '42tFTDWvTmBd7hEacohuCfGFa9TsBKhsmXKeViQ7q7NoY7UadV' + ), + amount: CcdAmount.fromMicroCcd(49648060875n), }, { - account: '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg', - amount: 51066576900n, + account: AccountAddress.fromBase58( + '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg' + ), + amount: CcdAmount.fromMicroCcd(51066576900n), }, { - account: '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn', - amount: 35462900625n, + account: AccountAddress.fromBase58( + '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn' + ), + amount: CcdAmount.fromMicroCcd(35462900625n), }, { - account: '4AnukgcopMC4crxfL1L9fUYw9MAkoo1yKLvH7eA1NAX7SxgyRY', - amount: 56740641000n, + account: AccountAddress.fromBase58( + '4AnukgcopMC4crxfL1L9fUYw9MAkoo1yKLvH7eA1NAX7SxgyRY' + ), + amount: CcdAmount.fromMicroCcd(56740641000n), }, { - account: '4BTFaHx8CioLi8Xe7YiimpAK1oQMkbx5Wj6B8N7d7NXgmLvEZs', - amount: 66670253175n, + account: AccountAddress.fromBase58( + '4BTFaHx8CioLi8Xe7YiimpAK1oQMkbx5Wj6B8N7d7NXgmLvEZs' + ), + amount: CcdAmount.fromMicroCcd(66670253175n), }, { - account: '4EJJ1hVhbVZT2sR9xPzWUwFcJWK3fPX54z94zskTozFVk8Xd4L', - amount: 60996189075n, + account: AccountAddress.fromBase58( + '4EJJ1hVhbVZT2sR9xPzWUwFcJWK3fPX54z94zskTozFVk8Xd4L' + ), + amount: CcdAmount.fromMicroCcd(60996189075n), }, ], - remainder: 290n, + remainder: CcdAmount.fromMicroCcd(290n), }; -export const finalizationRewardsSpecialEvent = { - tag: 'finalizationRewards', - finalizationRewards: [ - { - account: '3QK1rxUXV7GRk4Ng7Bs7qnbkdjyBdjzCytpTrSQN7BaJkiEfgZ', - amount: 359306692n, - }, - { - account: '3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini', - amount: 359306692n, - }, - { - account: '3gGBYDSpx2zWL3YMcqD48U5jVXYG4pJBDZqeY5CbMMKpxVBbc3', - amount: 359306692n, - }, - { - account: '3ntvNGT6tDuLYiSb5gMJSQAZfLPUJnzoizcFiVRWqLoctuXxpK', - amount: 359306692n, - }, - { - account: '3y9DtDUL8xpf8i2yj9k44zMVkf4H1hkpBEQcXbJhrgcwYSGg41', - amount: 359306692n, - }, - { - account: '42tFTDWvTmBd7hEacohuCfGFa9TsBKhsmXKeViQ7q7NoY7UadV', - amount: 359306692n, - }, - { - account: '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg', - amount: 359306692n, - }, - { - account: '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn', - amount: 359306692n, - }, - { - account: '4AnukgcopMC4crxfL1L9fUYw9MAkoo1yKLvH7eA1NAX7SxgyRY', - amount: 359306692n, - }, - { - account: '4BTFaHx8CioLi8Xe7YiimpAK1oQMkbx5Wj6B8N7d7NXgmLvEZs', - amount: 359306692n, - }, - { - account: '4EJJ1hVhbVZT2sR9xPzWUwFcJWK3fPX54z94zskTozFVk8Xd4L', - amount: 359306692n, - }, - ], - remainder: 4n, -}; +export const finalizationRewardsSpecialEvent: BlockSpecialEventFinalizationRewards = + { + tag: 'finalizationRewards', + finalizationRewards: [ + { + account: AccountAddress.fromBase58( + '3QK1rxUXV7GRk4Ng7Bs7qnbkdjyBdjzCytpTrSQN7BaJkiEfgZ' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '3gGBYDSpx2zWL3YMcqD48U5jVXYG4pJBDZqeY5CbMMKpxVBbc3' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '3ntvNGT6tDuLYiSb5gMJSQAZfLPUJnzoizcFiVRWqLoctuXxpK' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '3y9DtDUL8xpf8i2yj9k44zMVkf4H1hkpBEQcXbJhrgcwYSGg41' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '42tFTDWvTmBd7hEacohuCfGFa9TsBKhsmXKeViQ7q7NoY7UadV' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '48XGRnvQoG92T1AwETvW5pnJ1aRSPMKsWtGdKhTqyiNZzMk3Qn' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '4AnukgcopMC4crxfL1L9fUYw9MAkoo1yKLvH7eA1NAX7SxgyRY' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '4BTFaHx8CioLi8Xe7YiimpAK1oQMkbx5Wj6B8N7d7NXgmLvEZs' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + { + account: AccountAddress.fromBase58( + '4EJJ1hVhbVZT2sR9xPzWUwFcJWK3fPX54z94zskTozFVk8Xd4L' + ), + amount: CcdAmount.fromMicroCcd(359306692n), + }, + ], + remainder: CcdAmount.fromMicroCcd(4n), + }; -export const blockRewardSpecialEvent = { +export const blockRewardSpecialEvent: BlockSpecialEventBlockReward = { tag: 'blockReward', - transactionFees: 0n, - oldGasAccount: 0n, - newGasAccount: 0n, - bakerReward: 0n, - foundationCharge: 0n, - baker: '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg', - foundationAccount: '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg', + transactionFees: CcdAmount.zero(), + oldGasAccount: CcdAmount.zero(), + newGasAccount: CcdAmount.zero(), + bakerReward: CcdAmount.zero(), + foundationCharge: CcdAmount.zero(), + baker: AccountAddress.fromBase58( + '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg' + ), + foundationAccount: AccountAddress.fromBase58( + '44Axe5eHnMkBinX7GKvUm5w6mX83JGdasijhvsMv5ZW2Wmgphg' + ), }; export const insufficientBalanceForDelegationStakeRejectReason = { @@ -1343,7 +1410,7 @@ export const amountTooLargeRejectReason: AmountTooLarge = { '4Qod7UHWmkyz2ahPrWFH1kCqv1cvhT7NtEFbXG7G2soxXSYuMH' ), }, - amount: 2000000000n, + amount: CcdAmount.fromMicroCcd(2000000000n), }, }; @@ -1379,34 +1446,36 @@ export const insufficientBalanceForBakerStakeRejectReason = { export const outOfEnergyRejectReason = { tag: 'OutOfEnergy' }; -export const invalidInitMethodRejectReason = { +export const invalidInitMethodRejectReason: RejectReason = { contents: { - moduleRef: - 'c2ddbce88a7acae8bd610abf46afbdcf6264c8777163b345468b8e6f2ff8660f', - initName: 'init_cis2_nft', + moduleRef: ModuleReference.fromHexString( + 'c2ddbce88a7acae8bd610abf46afbdcf6264c8777163b345468b8e6f2ff8660f' + ), + initName: InitName.fromStringUnchecked('init_cis2_nft'), }, - tag: 'InvalidInitMethod', + tag: RejectReasonTag.InvalidInitMethod, }; export const runtimeFailureRejectReason = { tag: 'RuntimeFailure' }; export const rejectedReceiveRejectReason: RejectedReceive = { contractAddress: ContractAddress.create(2372), - parameter: '', - receiveName: 'auction.finalize', + parameter: Parameter.empty(), + receiveName: ReceiveName.fromStringUnchecked('auction.finalize'), rejectReason: -1, tag: RejectReasonTag.RejectedReceive, }; export const poolClosedRejectReason = { tag: 'PoolClosed' }; -export const invalidReceiveMethodRejectReason = { +export const invalidReceiveMethodRejectReason: RejectReason = { contents: { - moduleRef: - '4065819567755d7d2269acce2a8b0b510cdf30e36f5fb3303be16f8724e9b8b7', - receiveName: 'CIS2-TOKEN.mint', + moduleRef: ModuleReference.fromHexString( + '4065819567755d7d2269acce2a8b0b510cdf30e36f5fb3303be16f8724e9b8b7' + ), + receiveName: ReceiveName.fromStringUnchecked('CIS2-TOKEN.mint'), }, - tag: 'InvalidReceiveMethod', + tag: RejectReasonTag.InvalidReceiveMethod, }; export const transactionFeeCommissionNotInRangeRejectReason = { @@ -1468,8 +1537,8 @@ export const poolWouldBecomeOverDelegatedRejectReason = { export const bakerAccountInfo: AccountInfoBaker = { type: AccountInfoType.Baker, accountNonce: SequenceNumber.create(1), - accountAmount: 7449646704751788n, - accountReleaseSchedule: { total: 0n, schedule: [] }, + accountAmount: CcdAmount.fromMicroCcd(7449646704751788n), + accountReleaseSchedule: { total: CcdAmount.zero(), schedule: [] }, accountCredentials: { '0': { v: 0, @@ -1561,15 +1630,15 @@ export const bakerAccountInfo: AccountInfoBaker = { bakerSignatureVerifyKey: 'c385ccb5c8a0710a162f2c107123744650ff35f00040bfa262d974bfb3c3f8f1', restakeEarnings: true, - stakedAmount: 7349646704751788n, + stakedAmount: CcdAmount.fromMicroCcd(7349646704751788n), }, }; export const delegatorAccountInfo: AccountInfoDelegator = { type: AccountInfoType.Delegator, accountNonce: SequenceNumber.create(11), - accountAmount: 620948501142n, - accountReleaseSchedule: { total: 0n, schedule: [] }, + accountAmount: CcdAmount.fromMicroCcd(620948501142n), + accountReleaseSchedule: { total: CcdAmount.zero(), schedule: [] }, accountCredentials: { '0': { v: 0, @@ -1669,15 +1738,15 @@ export const delegatorAccountInfo: AccountInfoDelegator = { delegateType: DelegationTargetType.PassiveDelegation, }, restakeEarnings: true, - stakedAmount: 620942412516n, + stakedAmount: CcdAmount.fromMicroCcd(620942412516n), }, }; export const credIdAccountInfo: AccountInfoSimple = { type: AccountInfoType.Simple, accountNonce: SequenceNumber.create(19), - accountAmount: 35495453082577742n, - accountReleaseSchedule: { total: 0n, schedule: [] }, + accountAmount: CcdAmount.fromMicroCcd(35495453082577742n), + accountReleaseSchedule: { total: CcdAmount.zero(), schedule: [] }, accountCredentials: { '0': { v: 0, @@ -1755,8 +1824,8 @@ export const credIdAccountInfo: AccountInfoSimple = { export const regularAccountInfo: AccountInfoSimple = { type: AccountInfoType.Simple, accountNonce: SequenceNumber.create(19), - accountAmount: 35495453082577742n, - accountReleaseSchedule: { total: 0n, schedule: [] }, + accountAmount: CcdAmount.fromMicroCcd(35495453082577742n), + accountReleaseSchedule: { total: CcdAmount.zero(), schedule: [] }, accountCredentials: { '0': { v: 0, @@ -1975,7 +2044,7 @@ export const chainParameters: ChainParametersV1 = { finalizationCommissionRange: { min: 1, max: 1 }, bakingCommissionRange: { min: 0.1, max: 0.1 }, transactionCommissionRange: { min: 0.1, max: 0.1 }, - minimumEquityCapital: 14000000000n, + minimumEquityCapital: CcdAmount.fromMicroCcd(14000000000n), capitalBound: 0.1, leverageBound: { numerator: 3n, denominator: 1n }, rewardParameters: { @@ -2147,7 +2216,7 @@ export const oldChainParameters: ChainParametersV0 = { '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G' ), bakerCooldownEpochs: 166n, - minimumThresholdForBaking: 15000000000n, + minimumThresholdForBaking: CcdAmount.fromMicroCcd(15000000000n), rewardParameters: { version: 0, transactionFeeDistribution: { baker: 0.45, gasAccount: 0.45 }, @@ -2176,9 +2245,9 @@ export const bakerPoolStatus: BakerPoolStatus = { bakerAddress: AccountAddress.fromBase58( '3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini' ), - bakerEquityCapital: 7347853372468927n, - delegatedCapital: 0n, - delegatedCapitalCap: 0n, + bakerEquityCapital: CcdAmount.fromMicroCcd(7347853372468927n), + delegatedCapital: CcdAmount.zero(), + delegatedCapitalCap: CcdAmount.zero(), poolInfo: { openStatus: OpenStatusText.OpenForAll, metadataUrl: '', @@ -2194,26 +2263,26 @@ export const bakerPoolStatus: BakerPoolStatus = { currentPaydayStatus: { blocksBaked: 1329n, finalizationLive: true, - transactionFeesEarned: 105169976n, - effectiveStake: 4605214437901336n, + transactionFeesEarned: CcdAmount.fromMicroCcd(105169976n), + effectiveStake: CcdAmount.fromMicroCcd(4605214437901336n), lotteryPower: 0.15552531374613243, - bakerEquityCapital: 7344771840225046n, - delegatedCapital: 0n, + bakerEquityCapital: CcdAmount.fromMicroCcd(7344771840225046n), + delegatedCapital: CcdAmount.zero(), }, - allPoolTotalCapital: 46071942529284135n, + allPoolTotalCapital: CcdAmount.fromMicroCcd(46071942529284135n), }; -export const passiveDelegationStatus = { - poolType: 'PassiveDelegation', - delegatedCapital: 698892529615n, +export const passiveDelegationStatus: PassiveDelegationStatus = { + poolType: PoolStatusType.PassiveDelegation, + delegatedCapital: CcdAmount.fromMicroCcd(698892529615n), commissionRates: { transactionCommission: 0.12, bakingCommission: 0.12, finalizationCommission: 1, }, - currentPaydayTransactionFeesEarned: 24070n, - currentPaydayDelegatedCapital: 698618484955n, - allPoolTotalCapital: 46071942529284135n, + currentPaydayTransactionFeesEarned: CcdAmount.fromMicroCcd(24070n), + currentPaydayDelegatedCapital: CcdAmount.fromMicroCcd(698618484955n), + allPoolTotalCapital: CcdAmount.fromMicroCcd(46071942529284135n), }; export const bakerPoolStatusWithPendingChange: BakerPoolStatus = { @@ -2222,9 +2291,9 @@ export const bakerPoolStatusWithPendingChange: BakerPoolStatus = { bakerAddress: AccountAddress.fromBase58( '4aCoaW3qkQRnY3fUGThQcEMGSPLUEQ7XL9Yagx2UR91QpvtoAe' ), - bakerEquityCapital: 19999999999n, - delegatedCapital: 0n, - delegatedCapitalCap: 39999999998n, + bakerEquityCapital: CcdAmount.fromMicroCcd(19999999999n), + delegatedCapital: CcdAmount.zero(), + delegatedCapitalCap: CcdAmount.fromMicroCcd(39999999998n), poolInfo: { openStatus: OpenStatusText.OpenForAll, metadataUrl: 'b', @@ -2239,7 +2308,7 @@ export const bakerPoolStatusWithPendingChange: BakerPoolStatus = { effectiveTime: new Date('2022-12-08T07:54:00.000Z'), }, currentPaydayStatus: null, - allPoolTotalCapital: 46470271917743628n, + allPoolTotalCapital: CcdAmount.fromMicroCcd(46470271917743628n), }; export const invokeContractResult: InvokeContractResult = { @@ -2257,7 +2326,7 @@ export const invokeContractResult: InvokeContractResult = { '3kBx2h5Y2veb4hZgAJWPrr8RyQESKm5TjzF3ti1QQ4VSYLwK1G' ), }, - amount: 0n, + amount: CcdAmount.zero(), message: Parameter.empty(), receiveName: ReceiveName.fromStringUnchecked('PiggyBank.view'), events: [],