diff --git a/ADMIN.md b/ADMIN.md index 3960c2cd..53214bc8 100644 --- a/ADMIN.md +++ b/ADMIN.md @@ -51,10 +51,7 @@ describe("my-lib", () => { You need an `import` to avoid considering it a global script file. -6. Docs - -- Add new library to [docs](./scripts/docs.js) generator -- Add readme file of the new library in `package.json` script `docs` to format the generated docs with prettier. +6. Add new library to [docs](./scripts/docs.js) generator. 7. Add the new library to the [build-next](./scripts/build-next) script to tweak version and make dependencies less restrictive when the "next" version is published. diff --git a/package-lock.json b/package-lock.json index 370e2666..c04f1fa4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,8 @@ "packages/sns", "packages/cmc", "packages/ckbtc", - "packages/ic-management" + "packages/ic-management", + "packages/cketh" ], "devDependencies": { "@size-limit/esbuild": "^9.0.0", @@ -774,6 +775,10 @@ "resolved": "packages/ckbtc", "link": true }, + "node_modules/@dfinity/cketh": { + "resolved": "packages/cketh", + "link": true + }, "node_modules/@dfinity/cmc": { "resolved": "packages/cmc", "link": true @@ -7148,6 +7153,17 @@ "@dfinity/utils": "^2.0.0" } }, + "packages/cketh": { + "name": "@dfinity/cketh", + "version": "0.0.1", + "license": "Apache-2.0", + "peerDependencies": { + "@dfinity/agent": "^0.20.2", + "@dfinity/candid": "^0.20.2", + "@dfinity/principal": "^0.20.2", + "@dfinity/utils": "^2.0.0" + } + }, "packages/cmc": { "name": "@dfinity/cmc", "version": "2.1.0", @@ -7788,6 +7804,10 @@ "bech32": "^2.0.0" } }, + "@dfinity/cketh": { + "version": "file:packages/cketh", + "requires": {} + }, "@dfinity/cmc": { "version": "file:packages/cmc", "requires": {} diff --git a/package.json b/package.json index 8cd7fe67..40ca48cd 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ "packages/sns", "packages/cmc", "packages/ckbtc", - "packages/ic-management" + "packages/ic-management", + "packages/cketh" ], "scripts": { "did": "scripts/compile-idl-js", @@ -72,6 +73,17 @@ "@dfinity/utils" ] }, + { + "name": "@dfinity/cketh", + "path": "./packages/cketh/dist/index.js", + "limit": "5 kB", + "ignore": [ + "@dfinity/agent", + "@dfinity/candid", + "@dfinity/principal", + "@dfinity/utils" + ] + }, { "name": "@dfinity/cmc", "path": "./packages/cmc/dist/index.js", diff --git a/packages/ckbtc/README.md b/packages/ckbtc/README.md index b9891d33..d2d05b03 100644 --- a/packages/ckbtc/README.md +++ b/packages/ckbtc/README.md @@ -28,8 +28,6 @@ npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils The features are available through the class `CkBTCCanister`. It has to be instantiated with a canister ID. -e.g. fetching a token metadata. - ```ts import { CkBTCCanister } from "@dfinity/ckbtc"; import { createAgent } from "@dfinity/utils"; diff --git a/packages/cketh/LICENSE b/packages/cketh/LICENSE new file mode 100644 index 00000000..4874b73b --- /dev/null +++ b/packages/cketh/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 DFINITY LLC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/cketh/README.md b/packages/cketh/README.md new file mode 100644 index 00000000..2ed145f5 --- /dev/null +++ b/packages/cketh/README.md @@ -0,0 +1,92 @@ +# cketh-js + +A library for interfacing with [ckETH](https://github.com/dfinity/ic/tree/master/rs/ethereum/cketh/minter) on the Internet Computer. + +[![npm version](https://img.shields.io/npm/v/@dfinity/cketh.svg?logo=npm)](https://www.npmjs.com/package/@dfinity/cketh) [![GitHub license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) + +## Table of contents + +- [Installation](#installation) +- [Usage](#usage) +- [Features](#features) + +## Installation + +You can use `cketh-js` by installing it in your project. + +```bash +npm i @dfinity/cketh +``` + +The bundle needs peer dependencies, be sure that following resources are available in your project as well. + +```bash +npm i @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils +``` + +## Usage + +The features are available through the class `CkETHCanister`. It has to be instantiated with a canister ID. + +```ts +import { CkETHCanister } from "@dfinity/cketh"; +import { createAgent } from "@dfinity/utils"; + +const agent = await createAgent({ + identity, + host: HOST, +}); + +const { getSmartContractAddress } = CkETHCanister.create({ + agent, + canisterId: MY_CKETH_MINTER_CANISTER_ID, +}); + +const address = await getSmartContractAddress({}); +``` + +## Features + +`cketh-js` implements following features: + + + +### :factory: CkETHMinterCanister + +[:link: Source](https://github.com/dfinity/ic-js/tree/main/packages/cketh/src/minter.canister.ts#L8) + +#### Methods + +- [create](#gear-create) +- [getSmartContractAddress](#gear-getsmartcontractaddress) + +##### :gear: create + +| Method | Type | +| -------- | ------------------------------------------------------------------------ | +| `create` | `(options: CkETHMinterCanisterOptions<_SERVICE>) => CkETHMinterCanister` | + +[:link: Source](https://github.com/dfinity/ic-js/tree/main/packages/cketh/src/minter.canister.ts#L9) + +##### :gear: getSmartContractAddress + +The address of the helper smart contract may change in the future when the minter is upgraded. Please verify the address of the helper contract before any important transfer by querying the minter as follows. + +| Method | Type | +| ------------------------- | --------------------------------------------------- | +| `getSmartContractAddress` | `({ certified, }?: QueryParams) => Promise` | + +Parameters: + +- `params`: The parameters to resolve the ckETH smart contract address. +- `params.certified`: query or update call + +[:link: Source](https://github.com/dfinity/ic-js/tree/main/packages/cketh/src/minter.canister.ts#L27) + + + +## Resources + +- [ckETH Minter](https://github.com/dfinity/ic/tree/master/rs/ethereum/cketh/minter) +- ckETH [testnet deployment arguments](https://github.com/dfinity/ic/tree/master/rs/ethereum/cketh/testnet) +- [How to Acquire ckETH](https://medium.com/dfinity/how-to-acquire-cketh-02d863c835fc) blog post by [Jennifer Tran](https://twitter.com/JKim_Tran) diff --git a/packages/cketh/candid/minter.certified.idl.d.ts b/packages/cketh/candid/minter.certified.idl.d.ts new file mode 100644 index 00000000..8e1474b8 --- /dev/null +++ b/packages/cketh/candid/minter.certified.idl.d.ts @@ -0,0 +1,2 @@ +import type { IDL } from "@dfinity/candid"; +export const idlFactory: IDL.InterfaceFactory; diff --git a/packages/cketh/candid/minter.certified.idl.js b/packages/cketh/candid/minter.certified.idl.js new file mode 100644 index 00000000..a601b56c --- /dev/null +++ b/packages/cketh/candid/minter.certified.idl.js @@ -0,0 +1,224 @@ +/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cketh/candid/minter.did */ +export const idlFactory = ({ IDL }) => { + const BlockTag = IDL.Variant({ + 'Safe' : IDL.Null, + 'Finalized' : IDL.Null, + 'Latest' : IDL.Null, + }); + const UpgradeArg = IDL.Record({ + 'next_transaction_nonce' : IDL.Opt(IDL.Nat), + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Opt(IDL.Nat), + 'ethereum_block_height' : IDL.Opt(BlockTag), + }); + const EthereumNetwork = IDL.Variant({ + 'Mainnet' : IDL.Null, + 'Sepolia' : IDL.Null, + }); + const InitArg = IDL.Record({ + 'ethereum_network' : EthereumNetwork, + 'last_scraped_block_number' : IDL.Nat, + 'ecdsa_key_name' : IDL.Text, + 'next_transaction_nonce' : IDL.Nat, + 'ledger_id' : IDL.Principal, + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Nat, + 'ethereum_block_height' : BlockTag, + }); + const MinterArg = IDL.Variant({ + 'UpgradeArg' : UpgradeArg, + 'InitArg' : InitArg, + }); + const Eip1559TransactionPrice = IDL.Record({ + 'max_priority_fee_per_gas' : IDL.Nat, + 'max_fee_per_gas' : IDL.Nat, + 'max_transaction_fee' : IDL.Nat, + 'gas_limit' : IDL.Nat, + }); + const CanisterStatusType = IDL.Variant({ + 'stopped' : IDL.Null, + 'stopping' : IDL.Null, + 'running' : IDL.Null, + }); + const DefiniteCanisterSettings = IDL.Record({ + 'freezing_threshold' : IDL.Nat, + 'controllers' : IDL.Vec(IDL.Principal), + 'memory_allocation' : IDL.Nat, + 'compute_allocation' : IDL.Nat, + }); + const CanisterStatusResponse = IDL.Record({ + 'status' : CanisterStatusType, + 'memory_size' : IDL.Nat, + 'cycles' : IDL.Nat, + 'settings' : DefiniteCanisterSettings, + 'idle_cycles_burned_per_day' : IDL.Nat, + 'module_hash' : IDL.Opt(IDL.Vec(IDL.Nat8)), + }); + const UnsignedTransaction = IDL.Record({ + 'destination' : IDL.Text, + 'value' : IDL.Nat, + 'max_priority_fee_per_gas' : IDL.Nat, + 'data' : IDL.Vec(IDL.Nat8), + 'max_fee_per_gas' : IDL.Nat, + 'chain_id' : IDL.Nat, + 'nonce' : IDL.Nat, + 'gas_limit' : IDL.Nat, + 'access_list' : IDL.Vec( + IDL.Record({ + 'storage_keys' : IDL.Vec(IDL.Vec(IDL.Nat8)), + 'address' : IDL.Text, + }) + ), + }); + const EventSource = IDL.Record({ + 'transaction_hash' : IDL.Text, + 'log_index' : IDL.Nat, + }); + const TransactionReceipt = IDL.Record({ + 'effective_gas_price' : IDL.Nat, + 'status' : IDL.Variant({ 'Success' : IDL.Null, 'Failure' : IDL.Null }), + 'transaction_hash' : IDL.Text, + 'block_hash' : IDL.Text, + 'block_number' : IDL.Nat, + 'gas_used' : IDL.Nat, + }); + const Event = IDL.Record({ + 'timestamp' : IDL.Nat64, + 'payload' : IDL.Variant({ + 'SkippedBlock' : IDL.Record({ 'block_number' : IDL.Nat }), + 'SignedTransaction' : IDL.Record({ + 'raw_transaction' : IDL.Text, + 'withdrawal_id' : IDL.Nat, + }), + 'Upgrade' : UpgradeArg, + 'Init' : InitArg, + 'SyncedToBlock' : IDL.Record({ 'block_number' : IDL.Nat }), + 'AcceptedDeposit' : IDL.Record({ + 'principal' : IDL.Principal, + 'transaction_hash' : IDL.Text, + 'value' : IDL.Nat, + 'log_index' : IDL.Nat, + 'block_number' : IDL.Nat, + 'from_address' : IDL.Text, + }), + 'ReplacedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction' : UnsignedTransaction, + }), + 'MintedCkEth' : IDL.Record({ + 'event_source' : EventSource, + 'mint_block_index' : IDL.Nat, + }), + 'ReimbursedEthWithdrawal' : IDL.Record({ + 'transaction_hash' : IDL.Opt(IDL.Text), + 'withdrawal_id' : IDL.Nat, + 'reimbursed_amount' : IDL.Nat, + 'reimbursed_in_block' : IDL.Nat, + }), + 'CreatedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction' : UnsignedTransaction, + }), + 'InvalidDeposit' : IDL.Record({ + 'event_source' : EventSource, + 'reason' : IDL.Text, + }), + 'AcceptedEthWithdrawalRequest' : IDL.Record({ + 'ledger_burn_index' : IDL.Nat, + 'destination' : IDL.Text, + 'withdrawal_amount' : IDL.Nat, + 'from' : IDL.Principal, + 'created_at' : IDL.Opt(IDL.Nat64), + 'from_subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)), + }), + 'FinalizedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction_receipt' : TransactionReceipt, + }), + }), + }); + const EthTransaction = IDL.Record({ 'transaction_hash' : IDL.Text }); + const TxFinalizedStatus = IDL.Variant({ + 'Success' : EthTransaction, + 'Reimbursed' : IDL.Record({ + 'transaction_hash' : IDL.Text, + 'reimbursed_amount' : IDL.Nat, + 'reimbursed_in_block' : IDL.Nat, + }), + 'PendingReimbursement' : EthTransaction, + }); + const RetrieveEthStatus = IDL.Variant({ + 'NotFound' : IDL.Null, + 'TxFinalized' : TxFinalizedStatus, + 'TxSent' : EthTransaction, + 'TxCreated' : IDL.Null, + 'Pending' : IDL.Null, + }); + const WithdrawalArg = IDL.Record({ + 'recipient' : IDL.Text, + 'amount' : IDL.Nat, + }); + const RetrieveEthRequest = IDL.Record({ 'block_index' : IDL.Nat }); + const WithdrawalError = IDL.Variant({ + 'TemporarilyUnavailable' : IDL.Text, + 'InsufficientAllowance' : IDL.Record({ 'allowance' : IDL.Nat }), + 'AmountTooLow' : IDL.Record({ 'min_withdrawal_amount' : IDL.Nat }), + 'RecipientAddressBlocked' : IDL.Record({ 'address' : IDL.Text }), + 'InsufficientFunds' : IDL.Record({ 'balance' : IDL.Nat }), + }); + return IDL.Service({ + 'eip_1559_transaction_price' : IDL.Func([], [Eip1559TransactionPrice], []), + 'get_canister_status' : IDL.Func([], [CanisterStatusResponse], []), + 'get_events' : IDL.Func( + [IDL.Record({ 'start' : IDL.Nat64, 'length' : IDL.Nat64 })], + [ + IDL.Record({ + 'total_event_count' : IDL.Nat64, + 'events' : IDL.Vec(Event), + }), + ], + [], + ), + 'is_address_blocked' : IDL.Func([IDL.Text], [IDL.Bool], []), + 'minter_address' : IDL.Func([], [IDL.Text], []), + 'retrieve_eth_status' : IDL.Func([IDL.Nat64], [RetrieveEthStatus], []), + 'smart_contract_address' : IDL.Func([], [IDL.Text], []), + 'withdraw_eth' : IDL.Func( + [WithdrawalArg], + [IDL.Variant({ 'Ok' : RetrieveEthRequest, 'Err' : WithdrawalError })], + [], + ), + }); +}; +export const init = ({ IDL }) => { + const BlockTag = IDL.Variant({ + 'Safe' : IDL.Null, + 'Finalized' : IDL.Null, + 'Latest' : IDL.Null, + }); + const UpgradeArg = IDL.Record({ + 'next_transaction_nonce' : IDL.Opt(IDL.Nat), + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Opt(IDL.Nat), + 'ethereum_block_height' : IDL.Opt(BlockTag), + }); + const EthereumNetwork = IDL.Variant({ + 'Mainnet' : IDL.Null, + 'Sepolia' : IDL.Null, + }); + const InitArg = IDL.Record({ + 'ethereum_network' : EthereumNetwork, + 'last_scraped_block_number' : IDL.Nat, + 'ecdsa_key_name' : IDL.Text, + 'next_transaction_nonce' : IDL.Nat, + 'ledger_id' : IDL.Principal, + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Nat, + 'ethereum_block_height' : BlockTag, + }); + const MinterArg = IDL.Variant({ + 'UpgradeArg' : UpgradeArg, + 'InitArg' : InitArg, + }); + return [MinterArg]; +}; diff --git a/packages/cketh/candid/minter.d.ts b/packages/cketh/candid/minter.d.ts new file mode 100644 index 00000000..751fffe8 --- /dev/null +++ b/packages/cketh/candid/minter.d.ts @@ -0,0 +1,187 @@ +import type { ActorMethod } from "@dfinity/agent"; +import type { Principal } from "@dfinity/principal"; + +export type BlockTag = { Safe: null } | { Finalized: null } | { Latest: null }; +export interface CanisterStatusResponse { + status: CanisterStatusType; + memory_size: bigint; + cycles: bigint; + settings: DefiniteCanisterSettings; + idle_cycles_burned_per_day: bigint; + module_hash: [] | [Uint8Array | number[]]; +} +export type CanisterStatusType = + | { stopped: null } + | { stopping: null } + | { running: null }; +export interface DefiniteCanisterSettings { + freezing_threshold: bigint; + controllers: Array; + memory_allocation: bigint; + compute_allocation: bigint; +} +export interface Eip1559TransactionPrice { + max_priority_fee_per_gas: bigint; + max_fee_per_gas: bigint; + max_transaction_fee: bigint; + gas_limit: bigint; +} +export interface EthTransaction { + transaction_hash: string; +} +export type EthereumNetwork = { Mainnet: null } | { Sepolia: null }; +export interface Event { + timestamp: bigint; + payload: + | { SkippedBlock: { block_number: bigint } } + | { + SignedTransaction: { + raw_transaction: string; + withdrawal_id: bigint; + }; + } + | { Upgrade: UpgradeArg } + | { Init: InitArg } + | { SyncedToBlock: { block_number: bigint } } + | { + AcceptedDeposit: { + principal: Principal; + transaction_hash: string; + value: bigint; + log_index: bigint; + block_number: bigint; + from_address: string; + }; + } + | { + ReplacedTransaction: { + withdrawal_id: bigint; + transaction: UnsignedTransaction; + }; + } + | { + MintedCkEth: { + event_source: EventSource; + mint_block_index: bigint; + }; + } + | { + ReimbursedEthWithdrawal: { + transaction_hash: [] | [string]; + withdrawal_id: bigint; + reimbursed_amount: bigint; + reimbursed_in_block: bigint; + }; + } + | { + CreatedTransaction: { + withdrawal_id: bigint; + transaction: UnsignedTransaction; + }; + } + | { InvalidDeposit: { event_source: EventSource; reason: string } } + | { + AcceptedEthWithdrawalRequest: { + ledger_burn_index: bigint; + destination: string; + withdrawal_amount: bigint; + from: Principal; + created_at: [] | [bigint]; + from_subaccount: [] | [Uint8Array | number[]]; + }; + } + | { + FinalizedTransaction: { + withdrawal_id: bigint; + transaction_receipt: TransactionReceipt; + }; + }; +} +export interface EventSource { + transaction_hash: string; + log_index: bigint; +} +export interface InitArg { + ethereum_network: EthereumNetwork; + last_scraped_block_number: bigint; + ecdsa_key_name: string; + next_transaction_nonce: bigint; + ledger_id: Principal; + ethereum_contract_address: [] | [string]; + minimum_withdrawal_amount: bigint; + ethereum_block_height: BlockTag; +} +export type MinterArg = { UpgradeArg: UpgradeArg } | { InitArg: InitArg }; +export interface RetrieveEthRequest { + block_index: bigint; +} +export type RetrieveEthStatus = + | { NotFound: null } + | { TxFinalized: TxFinalizedStatus } + | { TxSent: EthTransaction } + | { TxCreated: null } + | { Pending: null }; +export interface TransactionReceipt { + effective_gas_price: bigint; + status: { Success: null } | { Failure: null }; + transaction_hash: string; + block_hash: string; + block_number: bigint; + gas_used: bigint; +} +export type TxFinalizedStatus = + | { Success: EthTransaction } + | { + Reimbursed: { + transaction_hash: string; + reimbursed_amount: bigint; + reimbursed_in_block: bigint; + }; + } + | { PendingReimbursement: EthTransaction }; +export interface UnsignedTransaction { + destination: string; + value: bigint; + max_priority_fee_per_gas: bigint; + data: Uint8Array | number[]; + max_fee_per_gas: bigint; + chain_id: bigint; + nonce: bigint; + gas_limit: bigint; + access_list: Array<{ + storage_keys: Array; + address: string; + }>; +} +export interface UpgradeArg { + next_transaction_nonce: [] | [bigint]; + ethereum_contract_address: [] | [string]; + minimum_withdrawal_amount: [] | [bigint]; + ethereum_block_height: [] | [BlockTag]; +} +export interface WithdrawalArg { + recipient: string; + amount: bigint; +} +export type WithdrawalError = + | { TemporarilyUnavailable: string } + | { InsufficientAllowance: { allowance: bigint } } + | { AmountTooLow: { min_withdrawal_amount: bigint } } + | { RecipientAddressBlocked: { address: string } } + | { InsufficientFunds: { balance: bigint } }; +export interface _SERVICE { + eip_1559_transaction_price: ActorMethod<[], Eip1559TransactionPrice>; + get_canister_status: ActorMethod<[], CanisterStatusResponse>; + get_events: ActorMethod< + [{ start: bigint; length: bigint }], + { total_event_count: bigint; events: Array } + >; + is_address_blocked: ActorMethod<[string], boolean>; + minter_address: ActorMethod<[], string>; + retrieve_eth_status: ActorMethod<[bigint], RetrieveEthStatus>; + smart_contract_address: ActorMethod<[], string>; + withdraw_eth: ActorMethod< + [WithdrawalArg], + { Ok: RetrieveEthRequest } | { Err: WithdrawalError } + >; +} diff --git a/packages/cketh/candid/minter.did b/packages/cketh/candid/minter.did new file mode 100644 index 00000000..b229cd81 --- /dev/null +++ b/packages/cketh/candid/minter.did @@ -0,0 +1,278 @@ +// Generated from IC repo commit 19e3dc486 (2024-01-02) 'rs/ethereum/cketh/minter/cketh_minter.did' by import-candid +type EthereumNetwork = variant { + // The public Ethereum mainnet. + Mainnet; + // The public Ethereum Sepolia testnet. + Sepolia; +}; + +type CanisterStatusResponse = record { + status : CanisterStatusType; + memory_size : nat; + cycles : nat; + settings : DefiniteCanisterSettings; + idle_cycles_burned_per_day : nat; + module_hash : opt vec nat8; +}; + +type CanisterStatusType = variant { stopped; stopping; running }; + +type DefiniteCanisterSettings = record { + freezing_threshold : nat; + controllers : vec principal; + memory_allocation : nat; + compute_allocation : nat; +}; + +type BlockTag = variant { + /// The latest mined block. + Latest; + + /// The latest safe head block. + Safe; + + /// The latest finalized block. + Finalized; +}; + +// The initialization parameters of the minter canister. +type InitArg = record { + // The minter will interact with this Ethereum network. + ethereum_network : EthereumNetwork; + + // The name of the ECDSA key to use. + // E.g., "dfx_test_key" on the local replica. + ecdsa_key_name : text; + + // Address of the helper smart contract. + ethereum_contract_address : opt text; + + // The principal of the ledger that handles ckETH transfers. + // The default account of the ckETH minter must be configured as + // the minting account of the ledger. + ledger_id : principal; + + // Determine ethereum block height observed by minter. + ethereum_block_height: BlockTag; + + // Minimum amount in Wei that can be withdrawn. + minimum_withdrawal_amount : nat; + + // Nonce of the next transaction to be sent to the Ethereum network. + next_transaction_nonce : nat; + + // Block number to start scrapping from on the Ethereum network. + // Scrapping the logs will resume at `last_scraped_block_number + 1` (inclusive). + last_scraped_block_number : nat; +}; + +type UpgradeArg = record { + // Change the nonce of the next transaction to be sent to the Ethereum network. + next_transaction_nonce : opt nat; + + // Change the minimum amount in Wei that can be withdrawn. + minimum_withdrawal_amount : opt nat; + + // Change the helper smart contract address. + ethereum_contract_address : opt text; + + // Change the ethereum block height observed by the minter. + ethereum_block_height : opt BlockTag; +}; + +type MinterArg = variant { UpgradeArg : UpgradeArg; InitArg : InitArg }; + +// Estimate price of an EIP-1559 transaction +// when converting ckETH to ETH, see https://eips.ethereum.org/EIPS/eip-1559 +type Eip1559TransactionPrice = record { + // Maximum amount of gas transaction is authorized to consume. + gas_limit : nat; + + // Maximum amount of Wei per gas unit that the transaction is willing to pay in total. + // This covers the base fee determined by the network and the `max_priority_fee_per_gas`. + max_fee_per_gas : nat; + + // Maximum amount of Wei per gas unit that the transaction gives to miners + // to incentivize them to include their transaction (priority fee). + max_priority_fee_per_gas : nat; + + // Maximum amount of Wei that can be charged for the transaction, + // computed as `max_fee_per_gas * gas_limit` + max_transaction_fee : nat; +}; + +type EthTransaction = record { transaction_hash : text }; + +// Status of a finalized transaction. +type TxFinalizedStatus = variant { + // Transaction was successful. + Success : EthTransaction; + // Transaction failed, user got reimbursed. + Reimbursed : record { + transaction_hash : text; + reimbursed_amount : nat; + reimbursed_in_block : nat; + }; + // Transaction failed and will be reimbursed, + PendingReimbursement : EthTransaction; +}; + +// Retrieve the status of a withdrawal request. +type RetrieveEthStatus = variant { + // Withdrawal request is not found. + NotFound; + + // Withdrawal request is waiting to be processed. + Pending; + + // Transaction fees were estimated and an Ethereum transaction was created. + // Transaction is not signed yet. + TxCreated; + + // Ethereum transaction was signed and is sent to the network. + TxSent : EthTransaction; + + // Ethereum transaction is finalized. + TxFinalized : TxFinalizedStatus; +}; + +type WithdrawalArg = record { recipient : text; amount : nat }; + +type RetrieveEthRequest = record { block_index : nat }; + +type WithdrawalError = variant { + // The withdrawal amount is too low. + // The payload contains the minimal withdrawal amount. + AmountTooLow : record { min_withdrawal_amount : nat }; + // The ckETH balance of the withdrawal account is too low. + InsufficientFunds : record { balance : nat }; + // The allowance given to the minter is too low. + InsufficientAllowance : record { allowance : nat }; + // Recipient's address is blocked. + // No withdrawal can be made to that address. + RecipientAddressBlocked : record { address : text }; + // The minter is overloaded, retry the request. + // The payload contains a human-readable message explaining what caused the unavailability. + TemporarilyUnavailable : text; +}; + +type EventSource = record { + transaction_hash : text; + log_index : nat; +}; + +type TransactionReceipt = record { + block_hash : text; + block_number : nat; + effective_gas_price : nat; + gas_used : nat; + status : variant { Success; Failure }; + transaction_hash : text; +}; + +type UnsignedTransaction = record { + chain_id : nat; + nonce : nat; + max_priority_fee_per_gas : nat; + max_fee_per_gas : nat; + gas_limit : nat; + destination : text; + value : nat; + data : blob; + access_list : vec record { address : text; storage_keys : vec blob }; +}; + +type Event = record { + timestamp : nat64; + payload : variant { + Init : InitArg; + Upgrade : UpgradeArg; + AcceptedDeposit : record { + transaction_hash : text; + block_number : nat; + log_index : nat; + from_address : text; + value : nat; + "principal" : principal; + }; + InvalidDeposit : record { + event_source : EventSource; + reason : text; + }; + MintedCkEth : record { + event_source: EventSource; + mint_block_index: nat; + }; + SyncedToBlock : record { + block_number : nat; + }; + AcceptedEthWithdrawalRequest : record { + withdrawal_amount : nat; + destination : text; + ledger_burn_index : nat; + from : principal; + from_subaccount : opt blob; + created_at: opt nat64; + }; + CreatedTransaction : record { + withdrawal_id : nat; + transaction : UnsignedTransaction; + }; + SignedTransaction : record { + withdrawal_id : nat; + raw_transaction : text; + }; + ReplacedTransaction : record { + withdrawal_id : nat; + transaction : UnsignedTransaction; + }; + FinalizedTransaction : record { + withdrawal_id : nat; + transaction_receipt : TransactionReceipt; + }; + ReimbursedEthWithdrawal : record { + reimbursed_in_block : nat; + reimbursed_amount : nat; + withdrawal_id : nat; + transaction_hash : opt text; + }; + SkippedBlock : record { + block_number : nat; + }; + }; +}; + +service : (MinterArg) -> { + // Retrieve the Ethereum address controlled by the minter: + // * Deposits will be transferred from the helper smart contract to this address + // * Withdrawals will originate from this address + // IMPORTANT: Do NOT send ETH to this address directly. Use the helper smart contract instead so that the minter + // knows to which IC principal the funds should be deposited. + minter_address : () -> (text); + + // Address of the helper smart contract. + // IMPORTANT: + // * Use this address to send ETH to the minter to convert it to ckETH. + // * In case the smart contract needs to be updated the returned address will change! + // Always check the address before making a transfer. + smart_contract_address : () -> (text) query; + + // Estimate the price of a transaction issued by the minter when converting ckETH to ETH. + eip_1559_transaction_price : () -> (Eip1559TransactionPrice); + + // Withdraw the specified amount in Wei to the given Ethereum address. + // IMPORTANT: The current gas limit is set to 21,000 for a transaction so withdrawals to smart contract addresses will likely fail. + withdraw_eth : (WithdrawalArg) -> (variant { Ok : RetrieveEthRequest; Err : WithdrawalError }); + + // Retrieve the status of a withdrawal request. + retrieve_eth_status : (nat64) -> (RetrieveEthStatus); + + // Check if an address is blocked by the minter. + is_address_blocked : (text) -> (bool) query; + // Retrieve the status of the minter canister. + get_canister_status : () -> (CanisterStatusResponse); + + // Retrive events from the minter's audit log. + // The endpoint can return fewer events than requested to bound the response size. + get_events : (record { start : nat64; length : nat64 }) -> (record { events : vec Event; total_event_count : nat64 }) query; +} diff --git a/packages/cketh/candid/minter.idl.d.ts b/packages/cketh/candid/minter.idl.d.ts new file mode 100644 index 00000000..8e1474b8 --- /dev/null +++ b/packages/cketh/candid/minter.idl.d.ts @@ -0,0 +1,2 @@ +import type { IDL } from "@dfinity/candid"; +export const idlFactory: IDL.InterfaceFactory; diff --git a/packages/cketh/candid/minter.idl.js b/packages/cketh/candid/minter.idl.js new file mode 100644 index 00000000..06512657 --- /dev/null +++ b/packages/cketh/candid/minter.idl.js @@ -0,0 +1,224 @@ +/* Do not edit. Compiled with ./scripts/compile-idl-js from packages/cketh/candid/minter.did */ +export const idlFactory = ({ IDL }) => { + const BlockTag = IDL.Variant({ + 'Safe' : IDL.Null, + 'Finalized' : IDL.Null, + 'Latest' : IDL.Null, + }); + const UpgradeArg = IDL.Record({ + 'next_transaction_nonce' : IDL.Opt(IDL.Nat), + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Opt(IDL.Nat), + 'ethereum_block_height' : IDL.Opt(BlockTag), + }); + const EthereumNetwork = IDL.Variant({ + 'Mainnet' : IDL.Null, + 'Sepolia' : IDL.Null, + }); + const InitArg = IDL.Record({ + 'ethereum_network' : EthereumNetwork, + 'last_scraped_block_number' : IDL.Nat, + 'ecdsa_key_name' : IDL.Text, + 'next_transaction_nonce' : IDL.Nat, + 'ledger_id' : IDL.Principal, + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Nat, + 'ethereum_block_height' : BlockTag, + }); + const MinterArg = IDL.Variant({ + 'UpgradeArg' : UpgradeArg, + 'InitArg' : InitArg, + }); + const Eip1559TransactionPrice = IDL.Record({ + 'max_priority_fee_per_gas' : IDL.Nat, + 'max_fee_per_gas' : IDL.Nat, + 'max_transaction_fee' : IDL.Nat, + 'gas_limit' : IDL.Nat, + }); + const CanisterStatusType = IDL.Variant({ + 'stopped' : IDL.Null, + 'stopping' : IDL.Null, + 'running' : IDL.Null, + }); + const DefiniteCanisterSettings = IDL.Record({ + 'freezing_threshold' : IDL.Nat, + 'controllers' : IDL.Vec(IDL.Principal), + 'memory_allocation' : IDL.Nat, + 'compute_allocation' : IDL.Nat, + }); + const CanisterStatusResponse = IDL.Record({ + 'status' : CanisterStatusType, + 'memory_size' : IDL.Nat, + 'cycles' : IDL.Nat, + 'settings' : DefiniteCanisterSettings, + 'idle_cycles_burned_per_day' : IDL.Nat, + 'module_hash' : IDL.Opt(IDL.Vec(IDL.Nat8)), + }); + const UnsignedTransaction = IDL.Record({ + 'destination' : IDL.Text, + 'value' : IDL.Nat, + 'max_priority_fee_per_gas' : IDL.Nat, + 'data' : IDL.Vec(IDL.Nat8), + 'max_fee_per_gas' : IDL.Nat, + 'chain_id' : IDL.Nat, + 'nonce' : IDL.Nat, + 'gas_limit' : IDL.Nat, + 'access_list' : IDL.Vec( + IDL.Record({ + 'storage_keys' : IDL.Vec(IDL.Vec(IDL.Nat8)), + 'address' : IDL.Text, + }) + ), + }); + const EventSource = IDL.Record({ + 'transaction_hash' : IDL.Text, + 'log_index' : IDL.Nat, + }); + const TransactionReceipt = IDL.Record({ + 'effective_gas_price' : IDL.Nat, + 'status' : IDL.Variant({ 'Success' : IDL.Null, 'Failure' : IDL.Null }), + 'transaction_hash' : IDL.Text, + 'block_hash' : IDL.Text, + 'block_number' : IDL.Nat, + 'gas_used' : IDL.Nat, + }); + const Event = IDL.Record({ + 'timestamp' : IDL.Nat64, + 'payload' : IDL.Variant({ + 'SkippedBlock' : IDL.Record({ 'block_number' : IDL.Nat }), + 'SignedTransaction' : IDL.Record({ + 'raw_transaction' : IDL.Text, + 'withdrawal_id' : IDL.Nat, + }), + 'Upgrade' : UpgradeArg, + 'Init' : InitArg, + 'SyncedToBlock' : IDL.Record({ 'block_number' : IDL.Nat }), + 'AcceptedDeposit' : IDL.Record({ + 'principal' : IDL.Principal, + 'transaction_hash' : IDL.Text, + 'value' : IDL.Nat, + 'log_index' : IDL.Nat, + 'block_number' : IDL.Nat, + 'from_address' : IDL.Text, + }), + 'ReplacedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction' : UnsignedTransaction, + }), + 'MintedCkEth' : IDL.Record({ + 'event_source' : EventSource, + 'mint_block_index' : IDL.Nat, + }), + 'ReimbursedEthWithdrawal' : IDL.Record({ + 'transaction_hash' : IDL.Opt(IDL.Text), + 'withdrawal_id' : IDL.Nat, + 'reimbursed_amount' : IDL.Nat, + 'reimbursed_in_block' : IDL.Nat, + }), + 'CreatedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction' : UnsignedTransaction, + }), + 'InvalidDeposit' : IDL.Record({ + 'event_source' : EventSource, + 'reason' : IDL.Text, + }), + 'AcceptedEthWithdrawalRequest' : IDL.Record({ + 'ledger_burn_index' : IDL.Nat, + 'destination' : IDL.Text, + 'withdrawal_amount' : IDL.Nat, + 'from' : IDL.Principal, + 'created_at' : IDL.Opt(IDL.Nat64), + 'from_subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)), + }), + 'FinalizedTransaction' : IDL.Record({ + 'withdrawal_id' : IDL.Nat, + 'transaction_receipt' : TransactionReceipt, + }), + }), + }); + const EthTransaction = IDL.Record({ 'transaction_hash' : IDL.Text }); + const TxFinalizedStatus = IDL.Variant({ + 'Success' : EthTransaction, + 'Reimbursed' : IDL.Record({ + 'transaction_hash' : IDL.Text, + 'reimbursed_amount' : IDL.Nat, + 'reimbursed_in_block' : IDL.Nat, + }), + 'PendingReimbursement' : EthTransaction, + }); + const RetrieveEthStatus = IDL.Variant({ + 'NotFound' : IDL.Null, + 'TxFinalized' : TxFinalizedStatus, + 'TxSent' : EthTransaction, + 'TxCreated' : IDL.Null, + 'Pending' : IDL.Null, + }); + const WithdrawalArg = IDL.Record({ + 'recipient' : IDL.Text, + 'amount' : IDL.Nat, + }); + const RetrieveEthRequest = IDL.Record({ 'block_index' : IDL.Nat }); + const WithdrawalError = IDL.Variant({ + 'TemporarilyUnavailable' : IDL.Text, + 'InsufficientAllowance' : IDL.Record({ 'allowance' : IDL.Nat }), + 'AmountTooLow' : IDL.Record({ 'min_withdrawal_amount' : IDL.Nat }), + 'RecipientAddressBlocked' : IDL.Record({ 'address' : IDL.Text }), + 'InsufficientFunds' : IDL.Record({ 'balance' : IDL.Nat }), + }); + return IDL.Service({ + 'eip_1559_transaction_price' : IDL.Func([], [Eip1559TransactionPrice], []), + 'get_canister_status' : IDL.Func([], [CanisterStatusResponse], []), + 'get_events' : IDL.Func( + [IDL.Record({ 'start' : IDL.Nat64, 'length' : IDL.Nat64 })], + [ + IDL.Record({ + 'total_event_count' : IDL.Nat64, + 'events' : IDL.Vec(Event), + }), + ], + ['query'], + ), + 'is_address_blocked' : IDL.Func([IDL.Text], [IDL.Bool], ['query']), + 'minter_address' : IDL.Func([], [IDL.Text], []), + 'retrieve_eth_status' : IDL.Func([IDL.Nat64], [RetrieveEthStatus], []), + 'smart_contract_address' : IDL.Func([], [IDL.Text], ['query']), + 'withdraw_eth' : IDL.Func( + [WithdrawalArg], + [IDL.Variant({ 'Ok' : RetrieveEthRequest, 'Err' : WithdrawalError })], + [], + ), + }); +}; +export const init = ({ IDL }) => { + const BlockTag = IDL.Variant({ + 'Safe' : IDL.Null, + 'Finalized' : IDL.Null, + 'Latest' : IDL.Null, + }); + const UpgradeArg = IDL.Record({ + 'next_transaction_nonce' : IDL.Opt(IDL.Nat), + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Opt(IDL.Nat), + 'ethereum_block_height' : IDL.Opt(BlockTag), + }); + const EthereumNetwork = IDL.Variant({ + 'Mainnet' : IDL.Null, + 'Sepolia' : IDL.Null, + }); + const InitArg = IDL.Record({ + 'ethereum_network' : EthereumNetwork, + 'last_scraped_block_number' : IDL.Nat, + 'ecdsa_key_name' : IDL.Text, + 'next_transaction_nonce' : IDL.Nat, + 'ledger_id' : IDL.Principal, + 'ethereum_contract_address' : IDL.Opt(IDL.Text), + 'minimum_withdrawal_amount' : IDL.Nat, + 'ethereum_block_height' : BlockTag, + }); + const MinterArg = IDL.Variant({ + 'UpgradeArg' : UpgradeArg, + 'InitArg' : InitArg, + }); + return [MinterArg]; +}; diff --git a/packages/cketh/esbuild.mjs b/packages/cketh/esbuild.mjs new file mode 100644 index 00000000..f3cda319 --- /dev/null +++ b/packages/cketh/esbuild.mjs @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +import { build } from "../../scripts/esbuild.mjs"; + +build(); diff --git a/packages/cketh/jest.config.js b/packages/cketh/jest.config.js new file mode 100644 index 00000000..e75ede62 --- /dev/null +++ b/packages/cketh/jest.config.js @@ -0,0 +1,7 @@ +const rootJestConfig = require("../../jest.config"); + +module.exports = { + ...rootJestConfig, + setupFiles: [`../../test-setup.ts`], + modulePathIgnorePatterns: ["./dist"], +}; diff --git a/packages/cketh/package.json b/packages/cketh/package.json new file mode 100644 index 00000000..07677d2c --- /dev/null +++ b/packages/cketh/package.json @@ -0,0 +1,46 @@ +{ + "name": "@dfinity/cketh", + "version": "0.0.1", + "description": "A library for interfacing with ckETH.", + "license": "Apache-2.0", + "main": "dist/cjs/index.cjs.js", + "module": "dist/esm/index.js", + "types": "dist/types/index.d.ts", + "files": [ + "dist", + "README.md", + "LICENSE" + ], + "scripts": { + "rmdir": "node ../../scripts/rmdir.mjs", + "ts-declaration": "tsc --emitDeclarationOnly --outDir dist/types", + "build": "npm run rmdir && mkdir -p dist && cp -R candid dist && node esbuild.mjs && npm run ts-declaration", + "prepack": "npm run build", + "test": "jest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dfinity/ic-js.git", + "directory": "packages/cketh" + }, + "bugs": { + "url": "https://github.com/dfinity/ic-js" + }, + "keywords": [ + "internet computer", + "internet-computer", + "ic", + "dfinity", + "ckETH", + "Ethereum", + "minter", + "token" + ], + "homepage": "https://github.com/dfinity/ic-js#readme", + "peerDependencies": { + "@dfinity/agent": "^0.20.2", + "@dfinity/candid": "^0.20.2", + "@dfinity/principal": "^0.20.2", + "@dfinity/utils": "^2.0.0" + } +} diff --git a/packages/cketh/src/index.ts b/packages/cketh/src/index.ts new file mode 100644 index 00000000..5ae2988c --- /dev/null +++ b/packages/cketh/src/index.ts @@ -0,0 +1 @@ +export { CkETHMinterCanister } from "./minter.canister"; diff --git a/packages/cketh/src/minter.canister.spec.ts b/packages/cketh/src/minter.canister.spec.ts new file mode 100644 index 00000000..c7937ac6 --- /dev/null +++ b/packages/cketh/src/minter.canister.spec.ts @@ -0,0 +1,54 @@ +import { ActorSubclass } from "@dfinity/agent"; +import { Principal } from "@dfinity/principal"; +import { mock } from "jest-mock-extended"; +import type { _SERVICE as CkETHMinterService } from "../candid/minter"; +import { CkETHMinterCanister } from "./minter.canister"; +import { + ckETHSmartContractAddressMock, + minterCanisterIdMock, +} from "./mocks/minter.mock"; + +describe("ckETH minter canister", () => { + const minter = ( + service: ActorSubclass, + ): CkETHMinterCanister => + CkETHMinterCanister.create({ + canisterId: minterCanisterIdMock, + certifiedServiceOverride: service, + }); + + const nonCertifiedMinter = ( + service: ActorSubclass, + ): CkETHMinterCanister => + CkETHMinterCanister.create({ + canisterId: minterCanisterIdMock, + serviceOverride: service, + }); + + describe("Smart contract address", () => { + it("should return the helper smart contract address", async () => { + const service = mock>(); + service.smart_contract_address.mockResolvedValue( + ckETHSmartContractAddressMock, + ); + + const canister = minter(service); + + const owner = Principal.fromText("aaaaa-aa"); + const res = await canister.getSmartContractAddress(); + expect(service.smart_contract_address).toBeCalled(); + expect(res).toEqual(ckETHSmartContractAddressMock); + }); + + it("should bubble errors", () => { + const service = mock>(); + service.smart_contract_address.mockImplementation(() => { + throw new Error(); + }); + + const canister = minter(service); + + expect(() => canister.getSmartContractAddress()).toThrowError(); + }); + }); +}); diff --git a/packages/cketh/src/minter.canister.ts b/packages/cketh/src/minter.canister.ts new file mode 100644 index 00000000..80a171b5 --- /dev/null +++ b/packages/cketh/src/minter.canister.ts @@ -0,0 +1,33 @@ +import { idlFactory as certifiedIdlFactory } from "@dfinity/ckbtc/candid/minter.certified.idl"; +import { idlFactory } from "@dfinity/ckbtc/candid/minter.idl"; +import type { QueryParams } from "@dfinity/utils"; +import { Canister, createServices } from "@dfinity/utils"; +import type { _SERVICE as CkETHMinterService } from "../candid/minter"; +import type { CkETHMinterCanisterOptions } from "./types/canister.options"; + +export class CkETHMinterCanister extends Canister { + static create(options: CkETHMinterCanisterOptions) { + const { service, certifiedService, canisterId } = + createServices({ + options, + idlFactory, + certifiedIdlFactory, + }); + + return new CkETHMinterCanister(canisterId, service, certifiedService); + } + + /** + * The address of the helper smart contract may change in the future when the minter is upgraded. Please verify the address of the helper contract before any important transfer by querying the minter as follows. + * + * @param {QueryParams} params The parameters to resolve the ckETH smart contract address. + * @param {boolean} params.certified query or update call + * @returns {Promise} Address of the helper smart contract. + */ + getSmartContractAddress = ({ + certified, + }: QueryParams = {}): Promise => { + const { smart_contract_address } = this.caller({ certified }); + return smart_contract_address(); + }; +} diff --git a/packages/cketh/src/mocks/minter.mock.ts b/packages/cketh/src/mocks/minter.mock.ts new file mode 100644 index 00000000..83f46e3d --- /dev/null +++ b/packages/cketh/src/mocks/minter.mock.ts @@ -0,0 +1,8 @@ +import { Principal } from "@dfinity/principal"; + +export const minterCanisterIdMock: Principal = Principal.fromText( + "sv3dd-oaaaa-aaaar-qacoa-cai", +); + +export const ckETHSmartContractAddressMock = + "0x7574eB42cA208A4f6960ECCAfDF186D627dCC175"; diff --git a/packages/cketh/src/types/canister.options.ts b/packages/cketh/src/types/canister.options.ts new file mode 100644 index 00000000..f6cdb210 --- /dev/null +++ b/packages/cketh/src/types/canister.options.ts @@ -0,0 +1,8 @@ +import type { Principal } from "@dfinity/principal"; +import type { CanisterOptions } from "@dfinity/utils"; + +export interface CkETHMinterCanisterOptions + extends Omit, "canisterId"> { + // The canister's ID is mandatory to instantiate an ckETH minter. + canisterId: Principal; +} diff --git a/packages/cketh/tsconfig.json b/packages/cketh/tsconfig.json new file mode 100644 index 00000000..ca17af18 --- /dev/null +++ b/packages/cketh/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src/**/*", "candid/**/*"] +} diff --git a/scripts/build-next b/scripts/build-next index a807272d..f0d65d24 100755 --- a/scripts/build-next +++ b/scripts/build-next @@ -12,6 +12,7 @@ node ./scripts/update-version.mjs nns node ./scripts/update-version.mjs sns node ./scripts/update-version.mjs cmc node ./scripts/update-version.mjs ckbtc +node ./scripts/update-version.mjs cketh node ./scripts/update-version.mjs ic-management : Now we can build diff --git a/scripts/compile-idl-js b/scripts/compile-idl-js index 43aa6e76..1099f3b8 100755 --- a/scripts/compile-idl-js +++ b/scripts/compile-idl-js @@ -28,6 +28,7 @@ did_files_to_compile() { did_files_to_compile_for_pkg "ledger-icrc" did_files_to_compile_for_pkg "ledger-icp" did_files_to_compile_for_pkg "ckbtc" + did_files_to_compile_for_pkg "cketh" did_files_to_compile_for_pkg "ic-management" } diff --git a/scripts/docs.js b/scripts/docs.js index 84f4ea97..ab6cb143 100644 --- a/scripts/docs.js +++ b/scripts/docs.js @@ -40,6 +40,8 @@ const ckBTCInputFiles = [ "./packages/ckbtc/src/utils/btc.utils.ts", ]; +const ckETHInputFiles = ["./packages/cketh/src/minter.canister.ts"]; + const icMgmtInputFiles = [ "./packages/ic-management/src/ic-management.canister.ts", ]; @@ -94,6 +96,13 @@ generateDocumentation({ buildOptions, }); +generateDocumentation({ + inputFiles: ckETHInputFiles, + outputFile: "./packages/cketh/README.md", + markdownOptions, + buildOptions, +}); + generateDocumentation({ inputFiles: utilsInputFiles, outputFile: "./packages/utils/README.md", diff --git a/scripts/import-candid b/scripts/import-candid index 817e1538..f89b7e5a 100755 --- a/scripts/import-candid +++ b/scripts/import-candid @@ -82,6 +82,9 @@ import_did "rs/rosetta-api/icrc1/index/index.did" "icrc_index.did" "ledger-icrc" mkdir -p packages/ckbtc/candid import_did "rs/bitcoin/ckbtc/minter/ckbtc_minter.did" "minter.did" "ckbtc" +mkdir -p packages/cketh/candid +import_did "rs/ethereum/cketh/minter/cketh_minter.did" "minter.did" "cketh" + mkdir -p packages/ic-management/candid curl https://raw.githubusercontent.com/dfinity/interface-spec/master/spec/_attachments/ic.did -o packages/ic-management/candid/ic-management.did : Fin