Skip to content

Commit

Permalink
Merge pull request #276 from Concordium/api-more-strict-types
Browse files Browse the repository at this point in the history
Use CcdAmount, TransactionExpiry and ModuleRef in api
  • Loading branch information
limemloh authored Oct 5, 2023
2 parents 065e221 + 4f67e4a commit a04323c
Show file tree
Hide file tree
Showing 47 changed files with 1,180 additions and 826 deletions.
2 changes: 1 addition & 1 deletion examples/ccd-js-gen/wCCD/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const grpcClient = new ConcordiumGRPCNodeClient(
credentials.createInsecure()
);

const wCCDModuleRef = new SDK.ModuleReference(
const wCCDModuleRef = SDK.ModuleReference.fromHexString(
'cc285180b45d7695db75c29dee004d2e81a1383880c9b122399bea809196c98f'
);

Expand Down
8 changes: 6 additions & 2 deletions examples/client/getBlockItemStatus.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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':
Expand Down
2 changes: 1 addition & 1 deletion examples/client/getEmbeddedSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion examples/client/getModuleSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions examples/client/getPassiveDelegationInfo.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions examples/client/getPoolInfo.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion examples/client/invokeContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions examples/common/bakerAdd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ 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 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,
Expand Down
4 changes: 2 additions & 2 deletions examples/common/bakerRemove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
4 changes: 2 additions & 2 deletions examples/common/delegationAdd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
4 changes: 2 additions & 2 deletions examples/common/delegationRemove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion examples/common/deployModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
6 changes: 3 additions & 3 deletions examples/common/simpleTransfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand All @@ -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,
};
}
Expand Down
10 changes: 5 additions & 5 deletions examples/composed-examples/initAndUpdateContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
};
Expand All @@ -107,7 +107,7 @@ const client = new ConcordiumGRPCNodeClient(
);

const initPayload: InitContractPayload = {
amount: new CcdAmount(0n),
amount: CcdAmount.zero(),
moduleRef: moduleRef,
initName: contractName,
param: initParams,
Expand Down Expand Up @@ -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,
};
Expand All @@ -159,7 +159,7 @@ const client = new ConcordiumGRPCNodeClient(
);

const updatePayload: UpdateContractPayload = {
amount: new CcdAmount(0n),
amount: CcdAmount.zero(),
address: unwrap(contractAddress),
receiveName,
message: updateParams,
Expand Down
15 changes: 14 additions & 1 deletion packages/sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(<integer>)` to construct it.
- Use `Timestamp` instead of a bigint. Can be constructed using `Timestamp.fromMillis(<integer>)`.
- Use `Duration` instead of a bigint. Can be constructed using `Duration.fromMillis(<integer>)`.
- Use `CcdAmount` instead of a bigint. Can be constructed using `CcdAmount.fromMicroCcd(<integer>)`.
- Use `TransactionExpiry` instead of a Date object. Can be constructed using `TransactionExpiry.fromDate(<date>)`.
- Use `ModuleReference` instead of a string with hex encoding. Can be constructed using `ModuleReference.fromHexString('<hex-string>')`.

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:
Expand All @@ -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("<hex-string>")` is now `CredentialRegistrationId.fromHexString("<hex-string>")`.
- `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(<integer>)` is now `CcdAmount.fromMicroCcd(<integer>)`.
- 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(<expiry>, <allowExpired>)` is now `TransactionExpiry.fromDate(<expiry>)`, 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("<hex-string>")` is now `ModuleReference.fromHexString("<hex-string>")`.
- 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.

Expand Down
28 changes: 15 additions & 13 deletions packages/sdk/src/GenericContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,22 @@ 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';

/**
* 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;
};
Expand Down Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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;
};

/**
Expand Down Expand Up @@ -334,7 +333,10 @@ class ContractBase<E extends string = string, V extends string = string> {
public createUpdateTransaction<T, J extends SmartContractTypeValues>(
entrypoint: EntrypointName.Type<E>,
serializeInput: (input: T) => ArrayBuffer,
{ amount = 0n, energy }: CreateContractTransactionMetadata,
{
amount = CcdAmount.zero(),
energy,
}: CreateContractTransactionMetadata,
input: T,
inputJsonFormatter?: (input: T) => J
):
Expand All @@ -343,7 +345,7 @@ class ContractBase<E extends string = string, V extends string = string> {
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,
Expand Down Expand Up @@ -408,7 +410,7 @@ class ContractBase<E extends string = string, V extends string = string> {
senderAddress
);
const header = {
expiry: new TransactionExpiry(expiry),
expiry,
nonce: nonce,
sender: senderAddress,
};
Expand Down
6 changes: 3 additions & 3 deletions packages/sdk/src/accountTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Loading

0 comments on commit a04323c

Please sign in to comment.