diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 35a3c0197..1fff29485 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -96,6 +96,8 @@ jobs: name: 'ic-icp-index-canister' - canister: 'cmc' name: 'cycles-minting-canister' + - canister: 'icrc1_ledger' + name: 'ic-icrc1-ledger' steps: - name: 'Checkout' uses: actions/checkout@v4 diff --git a/Cargo.lock b/Cargo.lock index cf4b39db1..6e2f63b81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -324,6 +324,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base32" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa" + [[package]] name = "base64" version = "0.13.1" @@ -2423,9 +2429,9 @@ dependencies = [ [[package]] name = "ic-stable-structures" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03f3044466a69802de74e710dc0300b706a05696a0531c942ca856751a13b0db" +checksum = "fcaf89c1bc326c72498bcc0cd954f2edf718c018e7c586d2193d701d3c9af29a" dependencies = [ "ic_principal", ] @@ -2541,6 +2547,26 @@ dependencies = [ "thiserror", ] +[[package]] +name = "icrc-ledger-types" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f7f6b54df25295dd0ce2722d583c15e2ee7eec9cef58c10b424feb54561b2" +dependencies = [ + "base32", + "candid", + "crc32fast", + "hex", + "itertools 0.12.1", + "num-bigint 0.4.6", + "num-traits", + "serde", + "serde_bytes", + "sha2 0.10.8", + "strum", + "time", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2597,6 +2623,7 @@ dependencies = [ "hex", "ic-certified-assets", "ic-ledger-types", + "icrc-ledger-types", "itertools 0.13.0", "lazy_static", "num-bigint 0.4.6", @@ -2686,6 +2713,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.13.0" @@ -2828,6 +2864,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "libm" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" + [[package]] name = "libredox" version = "0.1.3" @@ -3152,6 +3194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -4656,6 +4699,7 @@ dependencies = [ "ic-cdk-macros 0.16.0", "ic-ledger-types", "ic-stable-structures", + "icrc-ledger-types", "lazy_static", "num-bigint 0.4.6", "orbit-essentials", diff --git a/Cargo.toml b/Cargo.toml index 73dbcd949..12c521b1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,8 @@ ic-cdk = "0.16.0" ic-cdk-macros = "0.16.0" ic-cdk-timers = "0.9.0" ic-ledger-types = "0.12.0" -ic-stable-structures = "0.6.4" +ic-stable-structures = "0.6.6" +icrc-ledger-types = "0.1.6" ic-utils = "0.38" itertools = "0.13.0" lazy_static = "1.4.0" diff --git a/apps/wallet/package.json b/apps/wallet/package.json index 2e339f6a8..c5fabd067 100644 --- a/apps/wallet/package.json +++ b/apps/wallet/package.json @@ -27,9 +27,11 @@ "@dfinity/agent": "1.4.0", "@dfinity/auth-client": "1.4.0", "@dfinity/candid": "1.4.0", - "@dfinity/didc": "0.0.2", "@dfinity/identity": "1.4.0", "@dfinity/principal": "1.4.0", + "@dfinity/ledger-icrc": "2.3.3", + "@dfinity/utils": "2.3.1", + "@dfinity/didc": "0.0.2", "@mdi/font": "7.4.47", "@mdi/js": "7.4.47", "buffer": "6.0.3", diff --git a/apps/wallet/src/components/ShortenedAddress.vue b/apps/wallet/src/components/ShortenedAddress.vue new file mode 100644 index 000000000..02f39f3d6 --- /dev/null +++ b/apps/wallet/src/components/ShortenedAddress.vue @@ -0,0 +1,20 @@ + + + diff --git a/apps/wallet/src/components/TextOverflow.vue b/apps/wallet/src/components/TextOverflow.vue index 649a5d5af..b0551f2c2 100644 --- a/apps/wallet/src/components/TextOverflow.vue +++ b/apps/wallet/src/components/TextOverflow.vue @@ -13,7 +13,7 @@ const props = withDefaults( text: string; maxLength?: number; overflowText?: string; - overflowPosition?: 'start' | 'middle' | 'end'; + overflowPosition?: 'start' | 'middle' | 'end' | ((input: string) => string); }>(), { maxLength: 18, @@ -40,15 +40,19 @@ const truncatedText = computed(() => { }`; } - const overflowLengthStart = Math.ceil(props.overflowText.length / 2); - const overflowLengthEnd = Math.floor(props.overflowText.length / 2); - const start = Math.ceil((props.maxLength - 1) / 2) - overflowLengthStart; - const end = Math.floor((props.maxLength - 1) / 2) - overflowLengthEnd; + if (props.overflowPosition === 'middle') { + const overflowLengthStart = Math.ceil(props.overflowText.length / 2); + const overflowLengthEnd = Math.floor(props.overflowText.length / 2); + const start = Math.ceil((props.maxLength - 1) / 2) - overflowLengthStart; + const end = Math.floor((props.maxLength - 1) / 2) - overflowLengthEnd; - return `${props.text.slice(0, start)}${props.overflowText}${props.text.slice( - props.text.length - end, - props.text.length, - )}`; + return `${props.text.slice(0, start)}${props.overflowText}${props.text.slice( + props.text.length - end, + props.text.length, + )}`; + } + + return props.overflowPosition(props.text); }); const handleCopy = (event: ClipboardEvent): void => { diff --git a/apps/wallet/src/components/accounts/AccountAssetsCell.vue b/apps/wallet/src/components/accounts/AccountAssetsCell.vue new file mode 100644 index 000000000..da61b97c7 --- /dev/null +++ b/apps/wallet/src/components/accounts/AccountAssetsCell.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/wallet/src/components/accounts/AccountSetupDialog.vue b/apps/wallet/src/components/accounts/AccountSetupDialog.vue index bab9f03ce..4465adc5f 100644 --- a/apps/wallet/src/components/accounts/AccountSetupDialog.vue +++ b/apps/wallet/src/components/accounts/AccountSetupDialog.vue @@ -154,15 +154,15 @@ const saveChangesToExistingAccount = async (accountId: UUID): Promise = changes.configs_permission = [ assertAndReturn(wizard.value.permission.configuration, 'update_access'), ]; + changes.change_assets = []; return station.service.editAccount(changes as EditAccountOperationInput); }; const createNewAccount = async (): Promise => { const changes: Partial = {}; + changes.assets = assertAndReturn(wizard.value.configuration.assets, 'assets'); changes.name = assertAndReturn(wizard.value.configuration.name, 'name'); - changes.blockchain = assertAndReturn(wizard.value.configuration.blockchain, 'blockchain'); - changes.standard = assertAndReturn(wizard.value.configuration.standard, 'standard'); changes.configs_request_policy = wizard.value.request_policy.configurationRule ? [wizard.value.request_policy.configurationRule] : []; diff --git a/apps/wallet/src/components/accounts/AddAccountAssetBtn.vue b/apps/wallet/src/components/accounts/AddAccountAssetBtn.vue new file mode 100644 index 000000000..ef11f0a05 --- /dev/null +++ b/apps/wallet/src/components/accounts/AddAccountAssetBtn.vue @@ -0,0 +1,65 @@ + + diff --git a/apps/wallet/src/components/accounts/AddAccountAssetDialog.spec.ts b/apps/wallet/src/components/accounts/AddAccountAssetDialog.spec.ts new file mode 100644 index 000000000..684fe4c93 --- /dev/null +++ b/apps/wallet/src/components/accounts/AddAccountAssetDialog.spec.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, vi } from 'vitest'; +import { Account, Asset } from '~/generated/station/station.did'; +import { mount } from '~/test.utils'; +import AddAccountAssetDialog from './AddAccountAssetDialog.vue'; +import { BlockchainStandard } from '~/types/chain.types'; +import { useStationStore } from '~/stores/station.store'; +import TokenAutocomplete from '../inputs/TokenAutocomplete.vue'; +import { flushPromises } from '@vue/test-utils'; +import { StationService } from '~/services/station.service'; +import { services } from '~/plugins/services.plugin'; + +vi.mock('~/services/station.service', () => { + const mock: Partial = { + editAccount: vi.fn().mockImplementation(() => Promise.resolve({} as Account)), + }; + + return { + StationService: vi.fn(() => mock), + }; +}); + +const mockAssets: Asset[] = [ + { + id: '1', + blockchain: 'icp', + decimals: 8, + metadata: [], + name: 'Test', + symbol: 'TEST', + standards: [BlockchainStandard.Native], + }, + + { + id: '2', + blockchain: 'icp', + decimals: 8, + metadata: [], + name: 'Test2', + symbol: 'TEST2', + standards: [BlockchainStandard.ICRC1], + }, +]; + +const mockAccount: Account = { + id: '1', + assets: [ + { + asset_id: mockAssets[0].id, + balance: [], + }, + ], + addresses: [], + configs_request_policy: [], + metadata: [], + last_modification_timestamp: '2021-09-01T00:00:00Z', + name: 'Test', + transfer_request_policy: [], +}; + +describe('AddAccountAssetDialog', () => { + it('renders correctly', () => { + const wrapper = mount(AddAccountAssetDialog, { + props: { + account: mockAccount, + + open: true, + attach: true, + }, + }); + + expect(wrapper.exists()).toBe(true); + }); + + it('edits the account when submitted', async () => { + const wrapper = mount(AddAccountAssetDialog, { + props: { + account: { ...mockAccount }, + open: true, + attach: true, + }, + }); + + const station = useStationStore(); + station.configuration.details.supported_assets = mockAssets; + + const submitBtn = wrapper.find('button[data-test-id="add-asset-dialog-save-button"]'); + + const tokenField = wrapper.findComponent(TokenAutocomplete); + + tokenField.vm.$emit('update:modelValue', [mockAssets[1].id]); + + await wrapper.vm.$nextTick(); + await flushPromises(); + + await submitBtn.trigger('click'); + + await wrapper.vm.$nextTick(); + await flushPromises(); + + // check if editAccount was called with the correct asset + expect(services().station.editAccount).toHaveBeenCalledWith( + expect.objectContaining({ + change_assets: [ + { + Change: { + add_assets: [mockAssets[1].id], + remove_assets: [], + }, + }, + ], + }), + ); + + vi.clearAllMocks(); + }); +}); diff --git a/apps/wallet/src/components/accounts/AddAccountAssetDialog.vue b/apps/wallet/src/components/accounts/AddAccountAssetDialog.vue new file mode 100644 index 000000000..7959fc9d8 --- /dev/null +++ b/apps/wallet/src/components/accounts/AddAccountAssetDialog.vue @@ -0,0 +1,137 @@ + + diff --git a/apps/wallet/src/components/accounts/BatchTransfersActionBtn.vue b/apps/wallet/src/components/accounts/BatchTransfersActionBtn.vue index 0ff2cdbe2..35ea1f8a4 100644 --- a/apps/wallet/src/components/accounts/BatchTransfersActionBtn.vue +++ b/apps/wallet/src/components/accounts/BatchTransfersActionBtn.vue @@ -83,7 +83,7 @@ - {{ formatBalance(transfer.amount, account.decimals) }} + {{ formatBalance(transfer.amount, asset.decimals) }} @@ -80,6 +82,7 @@ const input = withDefaults( density?: 'comfortable' | 'compact'; readonly?: boolean; disabled?: boolean; + hideKeys?: string[]; }>(), { modelValue: () => [], @@ -87,6 +90,7 @@ const input = withDefaults( density: 'comfortable', readonly: false, disabled: false, + hideKeys: () => [], }, ); diff --git a/apps/wallet/src/components/inputs/StandardsAutocomplete.spec.ts b/apps/wallet/src/components/inputs/StandardsAutocomplete.spec.ts new file mode 100644 index 000000000..e4e8334f2 --- /dev/null +++ b/apps/wallet/src/components/inputs/StandardsAutocomplete.spec.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { mount } from '~/test.utils'; +import StandardsAutocomplete from './StandardsAutocomplete.vue'; + +describe('StandardsAutocomplete', () => { + it('renders with selected ids', () => { + const wrapper = mount(StandardsAutocomplete, { + props: { + modelValue: ['1'], + blockchain: 'icp', + }, + }); + + expect(wrapper.exists()).toBe(true); + + const autocomplete = wrapper.findComponent({ name: 'VSelect' }); + expect(autocomplete.exists()).toBe(true); + + expect(autocomplete.props('modelValue')).toEqual(['1']); + }); + + it('renders with empty list of standards', async () => { + const wrapper = mount(StandardsAutocomplete, { + props: { + blockchain: 'icp', + }, + }); + const autocomplete = wrapper.findComponent({ name: 'VSelect' }); + + expect(autocomplete.exists()).toBe(true); + + await wrapper.vm.$nextTick(); + + expect(autocomplete.props('items')).toEqual([]); + }); +}); diff --git a/apps/wallet/src/components/inputs/StandardsAutocomplete.vue b/apps/wallet/src/components/inputs/StandardsAutocomplete.vue new file mode 100644 index 000000000..189d1423a --- /dev/null +++ b/apps/wallet/src/components/inputs/StandardsAutocomplete.vue @@ -0,0 +1,74 @@ + + + diff --git a/apps/wallet/src/components/inputs/TokenAutocomplete.vue b/apps/wallet/src/components/inputs/TokenAutocomplete.vue index 9f3d8c35b..d47fb97c5 100644 --- a/apps/wallet/src/components/inputs/TokenAutocomplete.vue +++ b/apps/wallet/src/components/inputs/TokenAutocomplete.vue @@ -3,26 +3,29 @@ v-model="model" :multiple="props.multiple.value" :label="props.label.value" - item-value="value" - item-title="text" + item-value="id" + :item-title="item => `${item.name} (${item.symbol})`" :items="items" :variant="props.variant.value" :density="props.density.value" :readonly="props.readonly.value" :disabled="props.disabled.value" :rules="props.rules.value" + :no-data-text="props.noDataText.value" + data-test-id="token-autocomplete" /> diff --git a/apps/wallet/src/components/request-policies/specifier/AssetSpecifier.vue b/apps/wallet/src/components/request-policies/specifier/AssetSpecifier.vue new file mode 100644 index 000000000..9961411eb --- /dev/null +++ b/apps/wallet/src/components/request-policies/specifier/AssetSpecifier.vue @@ -0,0 +1,91 @@ + + diff --git a/apps/wallet/src/components/request-policies/specifier/SpecifierSelector.vue b/apps/wallet/src/components/request-policies/specifier/SpecifierSelector.vue index 170716ef7..ce9fb54f6 100644 --- a/apps/wallet/src/components/request-policies/specifier/SpecifierSelector.vue +++ b/apps/wallet/src/components/request-policies/specifier/SpecifierSelector.vue @@ -37,6 +37,7 @@ import UserGroupSpecifier from './UserGroupSpecifier.vue'; import UserSpecifier from './UserSpecifier.vue'; import UnsupportedSpecifier from './UnsupportedSpecifier.vue'; import { VAutocomplete } from 'vuetify/components'; +import AssetSpecifier from './AssetSpecifier.vue'; const input = withDefaults( defineProps<{ @@ -70,6 +71,8 @@ const componentsMap: { } = { AddUser: null, AddUserGroup: null, + AddAsset: null, + AddAccount: null, AddRequestPolicy: null, AddAddressBookEntry: null, @@ -83,6 +86,9 @@ const componentsMap: { EditUser: UserSpecifier, EditAddressBookEntry: AddressBookEntrySpecifier, RemoveAddressBookEntry: AddressBookEntrySpecifier, + EditAsset: AssetSpecifier, + RemoveAsset: AssetSpecifier, + // below variants are not supported yet EditPermission: UnsupportedSpecifier, EditRequestPolicy: UnsupportedSpecifier, @@ -247,6 +253,15 @@ watch( case RequestSpecifierEnum.SetDisasterRecovery: model.value = { [specifier.value]: null }; break; + case RequestSpecifierEnum.AddAsset: + model.value = { [specifier.value]: null }; + break; + case RequestSpecifierEnum.EditAsset: + model.value = { [specifier.value]: { Any: null } }; + break; + case RequestSpecifierEnum.RemoveAsset: + model.value = { [specifier.value]: { Any: null } }; + break; default: unreachable(specifier.value); } diff --git a/apps/wallet/src/components/requests/RecentRequests.vue b/apps/wallet/src/components/requests/RecentRequests.vue index 552d8c2f4..232ed0128 100644 --- a/apps/wallet/src/components/requests/RecentRequests.vue +++ b/apps/wallet/src/components/requests/RecentRequests.vue @@ -69,7 +69,7 @@ import RequestList from './RequestList.vue'; const props = withDefaults( defineProps<{ - types: ListRequestsOperationType[]; + types?: ListRequestsOperationType[]; title?: string; limit?: number; sortBy?: ListRequestsArgs['sortBy']; @@ -82,6 +82,7 @@ const props = withDefaults( }>(), { title: undefined, + types: undefined, limit: 3, sortBy: () => ({ expirationDt: 'asc', diff --git a/apps/wallet/src/components/requests/RequestDetailView.vue b/apps/wallet/src/components/requests/RequestDetailView.vue index 7430c72fa..600a0c1ac 100644 --- a/apps/wallet/src/components/requests/RequestDetailView.vue +++ b/apps/wallet/src/components/requests/RequestDetailView.vue @@ -241,6 +241,7 @@ import RequestMetadata from './RequestMetadata.vue'; import RequestStatusChip from './RequestStatusChip.vue'; import AddAccountOperation from './operations/AddAccountOperation.vue'; import AddAddressBookEntryOperation from './operations/AddAddressBookEntryOperation.vue'; +import AddAssetOperation from './operations/AddAssetOperation.vue'; import AddRequestPolicyOperation from './operations/AddRequestPolicyOperation.vue'; import AddUserGroupOperation from './operations/AddUserGroupOperation.vue'; import AddUserOperation from './operations/AddUserOperation.vue'; @@ -258,6 +259,8 @@ import RemoveUserGroupOperation from './operations/RemoveUserGroupOperation.vue' import SystemUpgradeOperation from './operations/SystemUpgradeOperation.vue'; import TransferOperation from './operations/TransferOperation.vue'; import UnsupportedOperation from './operations/UnsupportedOperation.vue'; +import EditAssetOperation from './operations/EditAssetOperation.vue'; +import RemoveAssetOperation from './operations/RemoveAssetOperation.vue'; const i18n = useI18n(); @@ -294,6 +297,9 @@ const componentsMap: { SystemUpgrade: SystemUpgradeOperation, EditPermission: EditPermissionOperation, ManageSystemInfo: ManageSystemInfoOperation, + AddAsset: AddAssetOperation, + EditAsset: EditAssetOperation, + RemoveAsset: RemoveAssetOperation, CallExternalCanister: CallExternalCanisterOperation, ChangeExternalCanister: UnsupportedOperation, CreateExternalCanister: UnsupportedOperation, diff --git a/apps/wallet/src/components/requests/RequestDialog.spec.ts b/apps/wallet/src/components/requests/RequestDialog.spec.ts index fabd7f20c..2626b61e2 100644 --- a/apps/wallet/src/components/requests/RequestDialog.spec.ts +++ b/apps/wallet/src/components/requests/RequestDialog.spec.ts @@ -6,22 +6,34 @@ import { GetRequestResultData, RequestOperation, RequestApproval, + Asset, } from '~/generated/station/station.did'; import { services } from '~/plugins/services.plugin'; import { mount } from '~/test.utils'; import { ExtractOk } from '~/types/helper.types'; import RequestDialog from './RequestDialog.vue'; +const mockAsset: Asset = { + blockchain: 'icp', + decimals: 2, + id: '1', + metadata: [], + name: 'ICP', + symbol: 'ICP', + standards: ['icp_native', 'icrc1'], +}; + const transferOperation1 = { Transfer: { from_account: [ { - address: 'fromaddress1', + addresses: [{ address: 'fromaddress1' }], }, ], input: { to: 'toaddress1', }, + from_asset: mockAsset, }, } as RequestOperation; @@ -29,12 +41,13 @@ const transferOperation2 = { Transfer: { from_account: [ { - address: 'fromaddress2', + addresses: [{ address: 'fromaddress2' }], }, ], input: { to: 'toaddress2', }, + from_asset: mockAsset, }, } as RequestOperation; diff --git a/apps/wallet/src/components/requests/RequestListItem.vue b/apps/wallet/src/components/requests/RequestListItem.vue index fc31661e0..b14947c7f 100644 --- a/apps/wallet/src/components/requests/RequestListItem.vue +++ b/apps/wallet/src/components/requests/RequestListItem.vue @@ -46,6 +46,7 @@ import { KeysOfUnion } from '~/utils/helper.utils'; import RequestStatusChip from './RequestStatusChip.vue'; import ReviewRequestBtn from './ReviewRequestBtn.vue'; import AddAccountOperation from './operations/AddAccountOperation.vue'; +import AddAssetOperation from './operations/AddAssetOperation.vue'; import AddAddressBookEntryOperation from './operations/AddAddressBookEntryOperation.vue'; import AddRequestPolicyOperation from './operations/AddRequestPolicyOperation.vue'; import AddUserGroupOperation from './operations/AddUserGroupOperation.vue'; @@ -64,6 +65,8 @@ import RemoveUserGroupOperation from './operations/RemoveUserGroupOperation.vue' import SystemUpgradeOperation from './operations/SystemUpgradeOperation.vue'; import TransferOperation from './operations/TransferOperation.vue'; import UnsupportedOperation from './operations/UnsupportedOperation.vue'; +import EditAssetOperation from './operations/EditAssetOperation.vue'; +import RemoveAssetOperation from './operations/RemoveAssetOperation.vue'; const props = withDefaults( defineProps<{ @@ -103,6 +106,11 @@ const componentsMap: { EditPermission: EditPermissionOperation, ManageSystemInfo: ManageSystemInfoOperation, CallExternalCanister: CallExternalCanisterOperation, + AddAsset: AddAssetOperation, + EditAsset: EditAssetOperation, + RemoveAsset: RemoveAssetOperation, + + // below variants are not supported yet ChangeExternalCanister: UnsupportedOperation, CreateExternalCanister: UnsupportedOperation, ConfigureExternalCanister: UnsupportedOperation, diff --git a/apps/wallet/src/components/requests/operations/AddAccountOperation.vue b/apps/wallet/src/components/requests/operations/AddAccountOperation.vue index bf57e775f..0068af1f3 100644 --- a/apps/wallet/src/components/requests/operations/AddAccountOperation.vue +++ b/apps/wallet/src/components/requests/operations/AddAccountOperation.vue @@ -6,10 +6,10 @@ {{ accountSetup.configuration.name ?? '-' }} - - + + @@ -24,6 +24,7 @@ import AccountSetupWizard, { import { useDefaultAccountSetupWizardModel } from '~/composables/account.composable'; import { AddAccountOperation, Request } from '~/generated/station/station.did'; import RequestOperationListRow from '../RequestOperationListRow.vue'; +import { useStationStore } from '~/stores/station.store'; const props = withDefaults( defineProps<{ @@ -35,15 +36,22 @@ const props = withDefaults( mode: 'list', }, ); - +const station = useStationStore(); const isListMode = computed(() => props.mode === 'list'); const accountSetup: Ref = ref(useDefaultAccountSetupWizardModel()); +const assetsText = computed(() => + props.operation.input.assets + .map(id => station.configuration.details.supported_assets.find(asset => asset.id === id)) + .filter(a => !!a) + .map(asset => `${asset.name} (${asset.symbol})`) + .join(', '), +); + onBeforeMount(() => { const model: AccountSetupWizardModel = useDefaultAccountSetupWizardModel(); model.configuration.name = props.operation.input.name; - model.configuration.blockchain = props.operation.input.blockchain; - model.configuration.standard = props.operation.input.standard; + model.configuration.assets = props.operation.input.assets; model.request_policy.configurationRule = props.operation.input.configs_request_policy?.[0]; model.request_policy.transferRule = props.operation.input.transfer_request_policy?.[0]; model.permission.configuration = props.operation.input.configs_permission; diff --git a/apps/wallet/src/components/requests/operations/AddAssetOperation.vue b/apps/wallet/src/components/requests/operations/AddAssetOperation.vue new file mode 100644 index 000000000..70d914cd6 --- /dev/null +++ b/apps/wallet/src/components/requests/operations/AddAssetOperation.vue @@ -0,0 +1,52 @@ + + + diff --git a/apps/wallet/src/components/requests/operations/EditAccountOperation.vue b/apps/wallet/src/components/requests/operations/EditAccountOperation.vue index ccdf4c51f..9d07f71db 100644 --- a/apps/wallet/src/components/requests/operations/EditAccountOperation.vue +++ b/apps/wallet/src/components/requests/operations/EditAccountOperation.vue @@ -6,6 +6,22 @@ {{ props.operation.input.name[0] ?? '-' }} + + + + @@ -23,8 +39,10 @@ import { } from '~/composables/account.composable'; import logger from '~/core/logger.core'; import { EditAccountOperation, Request } from '~/generated/station/station.did'; -import { variantIs } from '~/utils/helper.utils'; +import { unreachable, variantIs } from '~/utils/helper.utils'; import RequestOperationListRow from '../RequestOperationListRow.vue'; +import { useI18n } from 'vue-i18n'; +import { useStationStore } from '~/stores/station.store'; const props = withDefaults( defineProps<{ @@ -37,10 +55,60 @@ const props = withDefaults( }, ); +const i18n = useI18n(); + const isListMode = computed(() => props.mode === 'list'); const model: Ref = ref(useDefaultAccountSetupWizardModel()); const loading = ref(false); +const editAssets = computed(() => { + const assets = { + addAssets: '', + replaceAssets: '', + removeAssets: '', + }; + if (props.operation.input.change_assets[0]) { + if (variantIs(props.operation.input.change_assets[0], 'Change')) { + if (props.operation.input.change_assets[0].Change.add_assets.length > 0) { + assets.addAssets = `${i18n.t('requests.types.editaccount.added_assets')}: ${assetIdsToString( + props.operation.input.change_assets[0].Change.add_assets, + )}`; + } + + if (props.operation.input.change_assets[0].Change.remove_assets.length > 0) { + assets.removeAssets = `${i18n.t('requests.types.editaccount.removed_assets')}: ${assetIdsToString( + props.operation.input.change_assets[0].Change.remove_assets, + )}`; + } + } else if (variantIs(props.operation.input.change_assets[0], 'ReplaceWith')) { + assets.replaceAssets = `${i18n.t('requests.types.editaccount.replaced_assets')}: ${assetIdsToString( + props.operation.input.change_assets[0].ReplaceWith.assets, + )}`; + } else { + unreachable(props.operation.input.change_assets[0]); + } + } + + return assets; +}); + +const station = useStationStore(); + +function assetIdsToString(ids: string[]): string { + return ids + .map(id => { + const maybeAsset = station.configuration.details.supported_assets.find( + asset => asset.id == id, + ); + if (maybeAsset) { + return `${maybeAsset.symbol} (${maybeAsset.name})`; + } else { + return id; + } + }) + .join(', '); +} + const fetchDetails = async () => { try { if (loading.value || isListMode.value) { diff --git a/apps/wallet/src/components/requests/operations/EditAddressBookEntryOperation.vue b/apps/wallet/src/components/requests/operations/EditAddressBookEntryOperation.vue index 8feda4535..79d1a5ed4 100644 --- a/apps/wallet/src/components/requests/operations/EditAddressBookEntryOperation.vue +++ b/apps/wallet/src/components/requests/operations/EditAddressBookEntryOperation.vue @@ -19,7 +19,7 @@ - + @@ -35,6 +35,7 @@ import { import { useStationStore } from '~/stores/station.store'; import { variantIs } from '~/utils/helper.utils'; import RequestOperationListRow from '../RequestOperationListRow.vue'; +import { VProgressCircular } from 'vuetify/components'; const props = withDefaults( defineProps<{ diff --git a/apps/wallet/src/components/requests/operations/EditAssetOperation.vue b/apps/wallet/src/components/requests/operations/EditAssetOperation.vue new file mode 100644 index 000000000..85b0b78c7 --- /dev/null +++ b/apps/wallet/src/components/requests/operations/EditAssetOperation.vue @@ -0,0 +1,140 @@ + + + diff --git a/apps/wallet/src/components/requests/operations/EditPermissionOperation.vue b/apps/wallet/src/components/requests/operations/EditPermissionOperation.vue index fca1a296c..277dfd0c0 100644 --- a/apps/wallet/src/components/requests/operations/EditPermissionOperation.vue +++ b/apps/wallet/src/components/requests/operations/EditPermissionOperation.vue @@ -11,7 +11,7 @@ - + diff --git a/apps/wallet/src/components/requests/operations/RemoveAddressBookEntryOperation.vue b/apps/wallet/src/components/requests/operations/RemoveAddressBookEntryOperation.vue index 562582380..676312280 100644 --- a/apps/wallet/src/components/requests/operations/RemoveAddressBookEntryOperation.vue +++ b/apps/wallet/src/components/requests/operations/RemoveAddressBookEntryOperation.vue @@ -7,7 +7,7 @@ - + @@ -22,6 +22,7 @@ import { } from '~/generated/station/station.did'; import { useStationStore } from '~/stores/station.store'; import RequestOperationListRow from '../RequestOperationListRow.vue'; +import { VProgressCircular } from 'vuetify/components'; const props = withDefaults( defineProps<{ diff --git a/apps/wallet/src/components/requests/operations/RemoveAssetOperation.vue b/apps/wallet/src/components/requests/operations/RemoveAssetOperation.vue new file mode 100644 index 000000000..e02a22a9c --- /dev/null +++ b/apps/wallet/src/components/requests/operations/RemoveAssetOperation.vue @@ -0,0 +1,77 @@ + + + diff --git a/apps/wallet/src/components/requests/operations/TransferOperation.vue b/apps/wallet/src/components/requests/operations/TransferOperation.vue index 08542c758..aa23fb3cb 100644 --- a/apps/wallet/src/components/requests/operations/TransferOperation.vue +++ b/apps/wallet/src/components/requests/operations/TransferOperation.vue @@ -18,7 +18,7 @@
- +
- {{ account ? formatBalance(formValue.amount, account.decimals) : '-' }} - {{ account ? account.symbol : '' }} + {{ account ? formatBalance(formValue.amount, asset.decimals) : '-' }} + {{ account ? asset.symbol : '' }}
@@ -46,7 +46,7 @@ :prepend-icon="mdiWallet" readonly /> - + @@ -60,6 +60,9 @@ import { Routes } from '~/configs/routes.config'; import TextOverflow from '~/components/TextOverflow.vue'; import { copyToClipboard } from '~/utils/app.utils'; import { formatBalance } from '~/utils/helper.utils'; +import ShortenedAddress from '~/components/ShortenedAddress.vue'; +import { AddressFormat } from '~/types/chain.types'; +import { detectAddressFormat } from '~/utils/asset.utils'; const props = withDefaults( defineProps<{ @@ -75,6 +78,8 @@ const props = withDefaults( const isListMode = computed(() => props.mode === 'list'); const formValue: Ref> = ref({}); const account = computed(() => props.operation.from_account?.[0]); +const asset = computed(() => props.operation.from_asset); +const format = ref(undefined); onBeforeMount(() => { const transfer: Partial = {}; @@ -89,6 +94,8 @@ onBeforeMount(() => { } transfer.metadata = props.operation.input.metadata; + format.value = detectAddressFormat(props.operation.from_asset.blockchain, transfer.to); + formValue.value = transfer; }); diff --git a/apps/wallet/src/composables/account.composable.ts b/apps/wallet/src/composables/account.composable.ts index 34b7cb944..2699de2e3 100644 --- a/apps/wallet/src/composables/account.composable.ts +++ b/apps/wallet/src/composables/account.composable.ts @@ -7,7 +7,6 @@ import logger from '~/core/logger.core'; import { UUID } from '~/generated/station/station.did'; import { useAppStore } from '~/stores/app.store'; import { useStationStore } from '~/stores/station.store'; -import { BlockchainStandard, BlockchainType, TokenSymbol } from '~/types/chain.types'; import { parseDate } from '~/utils/date.utils'; export type Filters = { @@ -84,9 +83,7 @@ export const useDefaultAccountSetupWizardModel = ({ } = {}): AccountSetupWizardModel => { return { configuration: { - blockchain: BlockchainType.InternetComputer, - standard: BlockchainStandard.Native, - symbol: TokenSymbol.ICP, + assets: [], }, permission: { read: { @@ -147,10 +144,8 @@ export const useLoadAccountSetupWizardModel = async ( configuration: { id: account.id, name: account.name, - blockchain: account.blockchain, lastModified: account.last_modification_timestamp, - standard: account.standard, - symbol: account.symbol, + assets: account.assets.map(accountAsset => accountAsset.asset_id), }, permission: { read, diff --git a/apps/wallet/src/composables/autocomplete.composable.ts b/apps/wallet/src/composables/autocomplete.composable.ts index ee3161c30..8c6a1e3d8 100644 --- a/apps/wallet/src/composables/autocomplete.composable.ts +++ b/apps/wallet/src/composables/autocomplete.composable.ts @@ -101,3 +101,18 @@ export const useAddressBookAutocomplete = () => { return autocomplete; }; + +export const useAssetAutocomplete = () => { + const station = useStationStore(); + + const autocomplete = useAutocomplete(async () => { + const results = await station.service.listAssets({ + limit: 100, + offset: 0, + }); + + return results.assets; + }); + + return autocomplete; +}; diff --git a/apps/wallet/src/composables/request.composable.ts b/apps/wallet/src/composables/request.composable.ts index ed4f0db9a..356ae8fc5 100644 --- a/apps/wallet/src/composables/request.composable.ts +++ b/apps/wallet/src/composables/request.composable.ts @@ -73,6 +73,13 @@ export const useAvailableDomains = ( }); } + if (hasRequiredPrivilege({ anyOf: [Privilege.ListAssets] })) { + domains.value.push({ + id: RequestDomains.Assets, + types: [{ AddAsset: null }, { EditAsset: null }, { RemoveAsset: null }], + }); + } + domains.value.push({ id: RequestDomains.System, types: [ diff --git a/apps/wallet/src/configs/permissions.config.ts b/apps/wallet/src/configs/permissions.config.ts index bb9e198fd..2cfbc5011 100644 --- a/apps/wallet/src/configs/permissions.config.ts +++ b/apps/wallet/src/configs/permissions.config.ts @@ -364,6 +364,48 @@ export const globalPermissions = (): AggregatedResoucePermissions[] => [ ); } + return false; + }, + }, + { + resourceType: ResourceTypeEnum.Asset, + resources: [ + { + action: ResourceActionEnum.List, + resource: { Asset: { List: null } }, + allow: defaultAllowLevels(), + canEdit: false, + }, + { + action: ResourceActionEnum.Create, + resource: { Asset: { Create: null } }, + allow: defaultAllowLevels(), + canEdit: false, + }, + { + action: ResourceActionEnum.Read, + resource: { Asset: { Read: { Any: null } } }, + allow: defaultAllowLevels(), + canEdit: false, + }, + { + action: ResourceActionEnum.Update, + resource: { Asset: { Update: { Any: null } } }, + allow: defaultAllowLevels(), + canEdit: false, + }, + { + action: ResourceActionEnum.Delete, + resource: { Asset: { Delete: { Any: null } } }, + allow: defaultAllowLevels(), + canEdit: false, + }, + ], + match(specifier: Resource, resource: Resource): boolean { + if (variantIs(specifier, 'Asset') && variantIs(resource, 'Asset')) { + return isResourceActionContained(specifier.Asset, resource.Asset); + } + return false; }, }, diff --git a/apps/wallet/src/configs/request-policies.config.ts b/apps/wallet/src/configs/request-policies.config.ts index 0400a4b07..c7bcb37cf 100644 --- a/apps/wallet/src/configs/request-policies.config.ts +++ b/apps/wallet/src/configs/request-policies.config.ts @@ -39,4 +39,7 @@ export const requestSpecifiersIncludedRules = (): Record< [RequestSpecifierEnum.CallExternalCanister]: [...defaultRequestPolicyRules], [RequestSpecifierEnum.FundExternalCanister]: [...defaultRequestPolicyRules], [RequestSpecifierEnum.SetDisasterRecovery]: [...defaultRequestPolicyRules], + [RequestSpecifierEnum.AddAsset]: [...defaultRequestPolicyRules], + [RequestSpecifierEnum.EditAsset]: [...defaultRequestPolicyRules], + [RequestSpecifierEnum.RemoveAsset]: [...defaultRequestPolicyRules], }); diff --git a/apps/wallet/src/configs/routes.config.ts b/apps/wallet/src/configs/routes.config.ts index 29b83872a..bf081c6fd 100644 --- a/apps/wallet/src/configs/routes.config.ts +++ b/apps/wallet/src/configs/routes.config.ts @@ -2,8 +2,10 @@ export enum Routes { Login = 'Login', Error = 'Error', NotFound = 'NotFound', + Dashboard = 'Dashboard', Accounts = 'Accounts', Account = 'Account', + AccountAsset = 'AccountAsset', MySettings = 'MySettings', UserGroups = 'UserGroups', SystemSettings = 'SystemSettings', @@ -14,6 +16,7 @@ export enum Routes { Initialization = 'Initialization', AddStation = 'AddStation', Permissions = 'Permissions', + Assets = 'Assets', ExternalCanisters = 'ExternalCanisters', ExternalCanister = 'ExternalCanister', // Request Pages @@ -31,4 +34,4 @@ export enum RouteStatusCode { } export const defaultLoginRoute = Routes.Login; -export const defaultHomeRoute = Routes.Accounts; +export const defaultHomeRoute = Routes.Dashboard; diff --git a/apps/wallet/src/generated/icp_ledger/icp_ledger.did b/apps/wallet/src/generated/icp_ledger/icp_ledger.did new file mode 100644 index 000000000..c11b9434f --- /dev/null +++ b/apps/wallet/src/generated/icp_ledger/icp_ledger.did @@ -0,0 +1,451 @@ +// This is the official Ledger interface that is guaranteed to be backward compatible. + +// Amount of tokens, measured in 10^-8 of a token. +type Tokens = record { + e8s : nat64; +}; + +// Number of nanoseconds from the UNIX epoch in UTC timezone. +type TimeStamp = record { + timestamp_nanos: nat64; +}; + +// AccountIdentifier is a 32-byte array. +// The first 4 bytes is big-endian encoding of a CRC32 checksum of the last 28 bytes. +type AccountIdentifier = blob; + +// Subaccount is an arbitrary 32-byte byte array. +// Ledger uses subaccounts to compute the source address, which enables one +// principal to control multiple ledger accounts. +type SubAccount = blob; + +// Sequence number of a block produced by the ledger. +type BlockIndex = nat64; + +type Transaction = record { + memo : Memo; + icrc1_memo: opt blob; + operation : opt Operation; + created_at_time : TimeStamp; +}; + +// An arbitrary number associated with a transaction. +// The caller can set it in a `transfer` call as a correlation identifier. +type Memo = nat64; + +// Arguments for the `transfer` call. +type TransferArgs = record { + // Transaction memo. + // See comments for the `Memo` type. + memo: Memo; + // The amount that the caller wants to transfer to the destination address. + amount: Tokens; + // The amount that the caller pays for the transaction. + // Must be 10000 e8s. + fee: Tokens; + // The subaccount from which the caller wants to transfer funds. + // If null, the ledger uses the default (all zeros) subaccount to compute the source address. + // See comments for the `SubAccount` type. + from_subaccount: opt SubAccount; + // The destination account. + // If the transfer is successful, the balance of this address increases by `amount`. + to: AccountIdentifier; + // The point in time when the caller created this request. + // If null, the ledger uses current IC time as the timestamp. + created_at_time: opt TimeStamp; +}; + +type TransferError = variant { + // The fee that the caller specified in the transfer request was not the one that ledger expects. + // The caller can change the transfer fee to the `expected_fee` and retry the request. + BadFee : record { expected_fee : Tokens; }; + // The account specified by the caller doesn't have enough funds. + InsufficientFunds : record { balance: Tokens; }; + // The request is too old. + // The ledger only accepts requests created within 24 hours window. + // This is a non-recoverable error. + TxTooOld : record { allowed_window_nanos: nat64 }; + // The caller specified `created_at_time` that is too far in future. + // The caller can retry the request later. + TxCreatedInFuture : null; + // The ledger has already executed the request. + // `duplicate_of` field is equal to the index of the block containing the original transaction. + TxDuplicate : record { duplicate_of: BlockIndex; } +}; + +type TransferResult = variant { + Ok : BlockIndex; + Err : TransferError; +}; + +// Arguments for the `account_balance` call. +type AccountBalanceArgs = record { + account: AccountIdentifier; +}; + +type TransferFeeArg = record {}; + +type TransferFee = record { + // The fee to pay to perform a transfer + transfer_fee: Tokens; +}; + +type GetBlocksArgs = record { + // The index of the first block to fetch. + start : BlockIndex; + // Max number of blocks to fetch. + length : nat64; +}; + +type Operation = variant { + Mint : record { + to : AccountIdentifier; + amount : Tokens; + }; + Burn : record { + from : AccountIdentifier; + spender : opt AccountIdentifier; + amount : Tokens; + }; + Transfer : record { + from : AccountIdentifier; + to : AccountIdentifier; + amount : Tokens; + fee : Tokens; + }; + Approve : record { + from : AccountIdentifier; + spender : AccountIdentifier; + // This field is deprecated and should not be used. + allowance_e8s : int; + allowance: Tokens; + fee : Tokens; + expires_at : opt TimeStamp; + }; + TransferFrom : record { + from : AccountIdentifier; + to : AccountIdentifier; + spender : AccountIdentifier; + amount : Tokens; + fee : Tokens; + }; +}; + + + +type Block = record { + parent_hash : opt blob; + transaction : Transaction; + timestamp : TimeStamp; +}; + +// A prefix of the block range specified in the [GetBlocksArgs] request. +type BlockRange = record { + // A prefix of the requested block range. + // The index of the first block is equal to [GetBlocksArgs.from]. + // + // Note that the number of blocks might be less than the requested + // [GetBlocksArgs.len] for various reasons, for example: + // + // 1. The query might have hit the replica with an outdated state + // that doesn't have the full block range yet. + // 2. The requested range is too large to fit into a single reply. + // + // NOTE: the list of blocks can be empty if: + // 1. [GetBlocksArgs.len] was zero. + // 2. [GetBlocksArgs.from] was larger than the last block known to the canister. + blocks : vec Block; +}; + +// An error indicating that the arguments passed to [QueryArchiveFn] were invalid. +type QueryArchiveError = variant { + // [GetBlocksArgs.from] argument was smaller than the first block + // served by the canister that received the request. + BadFirstBlockIndex : record { + requested_index : BlockIndex; + first_valid_index : BlockIndex; + }; + + // Reserved for future use. + Other : record { + error_code : nat64; + error_message : text; + }; +}; + +type QueryArchiveResult = variant { + // Successfully fetched zero or more blocks. + Ok : BlockRange; + // The [GetBlocksArgs] request was invalid. + Err : QueryArchiveError; +}; + +// A function that is used for fetching archived ledger blocks. +type QueryArchiveFn = func (GetBlocksArgs) -> (QueryArchiveResult) query; + +// The result of a "query_blocks" call. +// +// The structure of the result is somewhat complicated because the main ledger canister might +// not have all the blocks that the caller requested: One or more "archive" canisters might +// store some of the requested blocks. +// +// Note: as of Q4 2021 when this interface is authored, the IC doesn't support making nested +// query calls within a query call. +type QueryBlocksResponse = record { + // The total number of blocks in the chain. + // If the chain length is positive, the index of the last block is `chain_len - 1`. + chain_length : nat64; + + // System certificate for the hash of the latest block in the chain. + // Only present if `query_blocks` is called in a non-replicated query context. + certificate : opt blob; + + // List of blocks that were available in the ledger when it processed the call. + // + // The blocks form a contiguous range, with the first block having index + // [first_block_index] (see below), and the last block having index + // [first_block_index] + len(blocks) - 1. + // + // The block range can be an arbitrary sub-range of the originally requested range. + blocks : vec Block; + + // The index of the first block in "blocks". + // If the blocks vector is empty, the exact value of this field is not specified. + first_block_index : BlockIndex; + + // Encoding of instructions for fetching archived blocks whose indices fall into the + // requested range. + // + // For each entry `e` in [archived_blocks], `[e.from, e.from + len)` is a sub-range + // of the originally requested block range. + archived_blocks : vec ArchivedBlocksRange; +}; + +type ArchivedBlocksRange = record { + // The index of the first archived block that can be fetched using the callback. + start : BlockIndex; + + // The number of blocks that can be fetch using the callback. + length : nat64; + + // The function that should be called to fetch the archived blocks. + // The range of the blocks accessible using this function is given by [from] + // and [len] fields above. + callback : QueryArchiveFn; +}; + +type ArchivedEncodedBlocksRange = record { + callback : func (GetBlocksArgs) -> ( + variant { Ok : vec blob; Err : QueryArchiveError }, + ) query; + start : nat64; + length : nat64; +}; + +type QueryEncodedBlocksResponse = record { + certificate : opt blob; + blocks : vec blob; + chain_length : nat64; + first_block_index : nat64; + archived_blocks : vec ArchivedEncodedBlocksRange; +}; + +type Archive = record { + canister_id: principal; +}; + +type Archives = record { + archives: vec Archive; +}; + +type Duration = record { + secs: nat64; + nanos: nat32; +}; + +type ArchiveOptions = record { + trigger_threshold : nat64; + num_blocks_to_archive : nat64; + node_max_memory_size_bytes: opt nat64; + max_message_size_bytes: opt nat64; + controller_id: principal; + cycles_for_archive_creation: opt nat64; +}; + +// Account identifier encoded as a 64-byte ASCII hex string. +type TextAccountIdentifier = text; + +// Arguments for the `send_dfx` call. +type SendArgs = record { + memo: Memo; + amount: Tokens; + fee: Tokens; + from_subaccount: opt SubAccount; + to: TextAccountIdentifier; + created_at_time: opt TimeStamp; +}; + +type AccountBalanceArgsDfx = record { + account: TextAccountIdentifier; +}; + +type FeatureFlags = record { + icrc2 : bool; +}; + +type InitArgs = record { + minting_account: TextAccountIdentifier; + icrc1_minting_account: opt Account; + initial_values: vec record {TextAccountIdentifier; Tokens}; + max_message_size_bytes: opt nat64; + transaction_window: opt Duration; + archive_options: opt ArchiveOptions; + send_whitelist: vec principal; + transfer_fee: opt Tokens; + token_symbol: opt text; + token_name: opt text; + feature_flags : opt FeatureFlags; + maximum_number_of_accounts : opt nat64; + accounts_overflow_trim_quantity: opt nat64; +}; + +type Icrc1BlockIndex = nat; +// Number of nanoseconds since the UNIX epoch in UTC timezone. +type Icrc1Timestamp = nat64; +type Icrc1Tokens = nat; + +type Account = record { + owner : principal; + subaccount : opt SubAccount; +}; + +type TransferArg = record { + from_subaccount : opt SubAccount; + to : Account; + amount : Icrc1Tokens; + fee : opt Icrc1Tokens; + memo : opt blob; + created_at_time: opt Icrc1Timestamp; +}; + +type Icrc1TransferError = variant { + BadFee : record { expected_fee : Icrc1Tokens }; + BadBurn : record { min_burn_amount : Icrc1Tokens }; + InsufficientFunds : record { balance : Icrc1Tokens }; + TooOld; + CreatedInFuture : record { ledger_time : nat64 }; + TemporarilyUnavailable; + Duplicate : record { duplicate_of : Icrc1BlockIndex }; + GenericError : record { error_code : nat; message : text }; +}; + +type Icrc1TransferResult = variant { + Ok : Icrc1BlockIndex; + Err : Icrc1TransferError; +}; + +// The value returned from the [icrc1_metadata] endpoint. +type Value = variant { + Nat : nat; + Int : int; + Text : text; + Blob : blob; +}; + +type UpgradeArgs = record { + maximum_number_of_accounts : opt nat64; + icrc1_minting_account : opt Account; + feature_flags : opt FeatureFlags; +}; + +type LedgerCanisterPayload = variant { + Init: InitArgs; + Upgrade: opt UpgradeArgs; +}; + +type ApproveArgs = record { + from_subaccount : opt SubAccount; + spender : Account; + amount : Icrc1Tokens; + expected_allowance : opt Icrc1Tokens; + expires_at : opt TimeStamp; + fee : opt Icrc1Tokens; + memo : opt blob; + created_at_time: opt TimeStamp; +}; + +type ApproveError = variant { + BadFee : record { expected_fee : Icrc1Tokens }; + InsufficientFunds : record { balance : Icrc1Tokens }; + AllowanceChanged : record { current_allowance : Icrc1Tokens }; + Expired : record { ledger_time : nat64 }; + TooOld; + CreatedInFuture : record { ledger_time : nat64 }; + Duplicate : record { duplicate_of : Icrc1BlockIndex }; + TemporarilyUnavailable; + GenericError : record { error_code : nat; message : text }; +}; + +type ApproveResult = variant { + Ok : Icrc1BlockIndex; + Err : ApproveError; +}; + +type AllowanceArgs = record { + account : Account; + spender : Account; +}; + +type Allowance = record { + allowance : Icrc1Tokens; + expires_at : opt TimeStamp; +}; + +service: (LedgerCanisterPayload) -> { + // Transfers tokens from a subaccount of the caller to the destination address. + // The source address is computed from the principal of the caller and the specified subaccount. + // When successful, returns the index of the block containing the transaction. + transfer : (TransferArgs) -> (TransferResult); + + // Returns the amount of Tokens on the specified account. + account_balance : (AccountBalanceArgs) -> (Tokens) query; + + // Returns the current transfer_fee. + transfer_fee : (TransferFeeArg) -> (TransferFee) query; + + // Queries blocks in the specified range. + query_blocks : (GetBlocksArgs) -> (QueryBlocksResponse) query; + + // Queries encoded blocks in the specified range + query_encoded_blocks : (GetBlocksArgs) -> (QueryEncodedBlocksResponse) query; + + // Returns token symbol. + symbol : () -> (record { symbol: text }) query; + + // Returns token name. + name : () -> (record { name: text }) query; + + // Returns token decimals. + decimals : () -> (record { decimals: nat32 }) query; + + // Returns the existing archive canisters information. + archives : () -> (Archives) query; + + send_dfx : (SendArgs) -> (BlockIndex); + account_balance_dfx : (AccountBalanceArgsDfx) -> (Tokens) query; + + // The following methods implement the ICRC-1 Token Standard. + // https://github.com/dfinity/ICRC-1/tree/main/standards/ICRC-1 + icrc1_name : () -> (text) query; + icrc1_symbol : () -> (text) query; + icrc1_decimals : () -> (nat8) query; + icrc1_metadata : () -> (vec record { text; Value }) query; + icrc1_total_supply : () -> (Icrc1Tokens) query; + icrc1_fee : () -> (Icrc1Tokens) query; + icrc1_minting_account : () -> (opt Account) query; + icrc1_balance_of : (Account) -> (Icrc1Tokens) query; + icrc1_transfer : (TransferArg) -> (Icrc1TransferResult); + icrc1_supported_standards : () -> (vec record { name : text; url : text }) query; + icrc2_approve : (ApproveArgs) -> (ApproveResult); + icrc2_allowance : (AllowanceArgs) -> (Allowance) query; +} diff --git a/apps/wallet/src/generated/icp_ledger/icp_ledger.did.d.ts b/apps/wallet/src/generated/icp_ledger/icp_ledger.did.d.ts new file mode 100644 index 000000000..420381746 --- /dev/null +++ b/apps/wallet/src/generated/icp_ledger/icp_ledger.did.d.ts @@ -0,0 +1,248 @@ +import type { Principal } from '@dfinity/principal'; +import type { ActorMethod } from '@dfinity/agent'; +import type { IDL } from '@dfinity/candid'; + +export interface Account { + 'owner' : Principal, + 'subaccount' : [] | [SubAccount], +} +export interface AccountBalanceArgs { 'account' : AccountIdentifier } +export interface AccountBalanceArgsDfx { 'account' : TextAccountIdentifier } +export type AccountIdentifier = Uint8Array | number[]; +export interface Allowance { + 'allowance' : Icrc1Tokens, + 'expires_at' : [] | [TimeStamp], +} +export interface AllowanceArgs { 'account' : Account, 'spender' : Account } +export interface ApproveArgs { + 'fee' : [] | [Icrc1Tokens], + 'memo' : [] | [Uint8Array | number[]], + 'from_subaccount' : [] | [SubAccount], + 'created_at_time' : [] | [TimeStamp], + 'amount' : Icrc1Tokens, + 'expected_allowance' : [] | [Icrc1Tokens], + 'expires_at' : [] | [TimeStamp], + 'spender' : Account, +} +export type ApproveError = { + 'GenericError' : { 'message' : string, 'error_code' : bigint } + } | + { 'TemporarilyUnavailable' : null } | + { 'Duplicate' : { 'duplicate_of' : Icrc1BlockIndex } } | + { 'BadFee' : { 'expected_fee' : Icrc1Tokens } } | + { 'AllowanceChanged' : { 'current_allowance' : Icrc1Tokens } } | + { 'CreatedInFuture' : { 'ledger_time' : bigint } } | + { 'TooOld' : null } | + { 'Expired' : { 'ledger_time' : bigint } } | + { 'InsufficientFunds' : { 'balance' : Icrc1Tokens } }; +export type ApproveResult = { 'Ok' : Icrc1BlockIndex } | + { 'Err' : ApproveError }; +export interface Archive { 'canister_id' : Principal } +export interface ArchiveOptions { + 'num_blocks_to_archive' : bigint, + 'trigger_threshold' : bigint, + 'max_message_size_bytes' : [] | [bigint], + 'cycles_for_archive_creation' : [] | [bigint], + 'node_max_memory_size_bytes' : [] | [bigint], + 'controller_id' : Principal, +} +export interface ArchivedBlocksRange { + 'callback' : QueryArchiveFn, + 'start' : BlockIndex, + 'length' : bigint, +} +export interface ArchivedEncodedBlocksRange { + 'callback' : [Principal, string], + 'start' : bigint, + 'length' : bigint, +} +export interface Archives { 'archives' : Array } +export interface Block { + 'transaction' : Transaction, + 'timestamp' : TimeStamp, + 'parent_hash' : [] | [Uint8Array | number[]], +} +export type BlockIndex = bigint; +export interface BlockRange { 'blocks' : Array } +export interface Duration { 'secs' : bigint, 'nanos' : number } +export interface FeatureFlags { 'icrc2' : boolean } +export interface GetBlocksArgs { 'start' : BlockIndex, 'length' : bigint } +export type Icrc1BlockIndex = bigint; +export type Icrc1Timestamp = bigint; +export type Icrc1Tokens = bigint; +export type Icrc1TransferError = { + 'GenericError' : { 'message' : string, 'error_code' : bigint } + } | + { 'TemporarilyUnavailable' : null } | + { 'BadBurn' : { 'min_burn_amount' : Icrc1Tokens } } | + { 'Duplicate' : { 'duplicate_of' : Icrc1BlockIndex } } | + { 'BadFee' : { 'expected_fee' : Icrc1Tokens } } | + { 'CreatedInFuture' : { 'ledger_time' : bigint } } | + { 'TooOld' : null } | + { 'InsufficientFunds' : { 'balance' : Icrc1Tokens } }; +export type Icrc1TransferResult = { 'Ok' : Icrc1BlockIndex } | + { 'Err' : Icrc1TransferError }; +export interface InitArgs { + 'send_whitelist' : Array, + 'token_symbol' : [] | [string], + 'transfer_fee' : [] | [Tokens], + 'minting_account' : TextAccountIdentifier, + 'maximum_number_of_accounts' : [] | [bigint], + 'accounts_overflow_trim_quantity' : [] | [bigint], + 'transaction_window' : [] | [Duration], + 'max_message_size_bytes' : [] | [bigint], + 'icrc1_minting_account' : [] | [Account], + 'archive_options' : [] | [ArchiveOptions], + 'initial_values' : Array<[TextAccountIdentifier, Tokens]>, + 'token_name' : [] | [string], + 'feature_flags' : [] | [FeatureFlags], +} +export type LedgerCanisterPayload = { 'Upgrade' : [] | [UpgradeArgs] } | + { 'Init' : InitArgs }; +export type Memo = bigint; +export type Operation = { + 'Approve' : { + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'allowance_e8s' : bigint, + 'allowance' : Tokens, + 'expires_at' : [] | [TimeStamp], + 'spender' : AccountIdentifier, + } + } | + { + 'Burn' : { + 'from' : AccountIdentifier, + 'amount' : Tokens, + 'spender' : [] | [AccountIdentifier], + } + } | + { 'Mint' : { 'to' : AccountIdentifier, 'amount' : Tokens } } | + { + 'Transfer' : { + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'amount' : Tokens, + } + } | + { + 'TransferFrom' : { + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'amount' : Tokens, + 'spender' : AccountIdentifier, + } + }; +export type QueryArchiveError = { + 'BadFirstBlockIndex' : { + 'requested_index' : BlockIndex, + 'first_valid_index' : BlockIndex, + } + } | + { 'Other' : { 'error_message' : string, 'error_code' : bigint } }; +export type QueryArchiveFn = ActorMethod<[GetBlocksArgs], QueryArchiveResult>; +export type QueryArchiveResult = { 'Ok' : BlockRange } | + { 'Err' : QueryArchiveError }; +export interface QueryBlocksResponse { + 'certificate' : [] | [Uint8Array | number[]], + 'blocks' : Array, + 'chain_length' : bigint, + 'first_block_index' : BlockIndex, + 'archived_blocks' : Array, +} +export interface QueryEncodedBlocksResponse { + 'certificate' : [] | [Uint8Array | number[]], + 'blocks' : Array, + 'chain_length' : bigint, + 'first_block_index' : bigint, + 'archived_blocks' : Array, +} +export interface SendArgs { + 'to' : TextAccountIdentifier, + 'fee' : Tokens, + 'memo' : Memo, + 'from_subaccount' : [] | [SubAccount], + 'created_at_time' : [] | [TimeStamp], + 'amount' : Tokens, +} +export type SubAccount = Uint8Array | number[]; +export type TextAccountIdentifier = string; +export interface TimeStamp { 'timestamp_nanos' : bigint } +export interface Tokens { 'e8s' : bigint } +export interface Transaction { + 'memo' : Memo, + 'icrc1_memo' : [] | [Uint8Array | number[]], + 'operation' : [] | [Operation], + 'created_at_time' : TimeStamp, +} +export interface TransferArg { + 'to' : Account, + 'fee' : [] | [Icrc1Tokens], + 'memo' : [] | [Uint8Array | number[]], + 'from_subaccount' : [] | [SubAccount], + 'created_at_time' : [] | [Icrc1Timestamp], + 'amount' : Icrc1Tokens, +} +export interface TransferArgs { + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'memo' : Memo, + 'from_subaccount' : [] | [SubAccount], + 'created_at_time' : [] | [TimeStamp], + 'amount' : Tokens, +} +export type TransferError = { + 'TxTooOld' : { 'allowed_window_nanos' : bigint } + } | + { 'BadFee' : { 'expected_fee' : Tokens } } | + { 'TxDuplicate' : { 'duplicate_of' : BlockIndex } } | + { 'TxCreatedInFuture' : null } | + { 'InsufficientFunds' : { 'balance' : Tokens } }; +export interface TransferFee { 'transfer_fee' : Tokens } +export type TransferFeeArg = {}; +export type TransferResult = { 'Ok' : BlockIndex } | + { 'Err' : TransferError }; +export interface UpgradeArgs { + 'maximum_number_of_accounts' : [] | [bigint], + 'icrc1_minting_account' : [] | [Account], + 'feature_flags' : [] | [FeatureFlags], +} +export type Value = { 'Int' : bigint } | + { 'Nat' : bigint } | + { 'Blob' : Uint8Array | number[] } | + { 'Text' : string }; +export interface _SERVICE { + 'account_balance' : ActorMethod<[AccountBalanceArgs], Tokens>, + 'account_balance_dfx' : ActorMethod<[AccountBalanceArgsDfx], Tokens>, + 'archives' : ActorMethod<[], Archives>, + 'decimals' : ActorMethod<[], { 'decimals' : number }>, + 'icrc1_balance_of' : ActorMethod<[Account], Icrc1Tokens>, + 'icrc1_decimals' : ActorMethod<[], number>, + 'icrc1_fee' : ActorMethod<[], Icrc1Tokens>, + 'icrc1_metadata' : ActorMethod<[], Array<[string, Value]>>, + 'icrc1_minting_account' : ActorMethod<[], [] | [Account]>, + 'icrc1_name' : ActorMethod<[], string>, + 'icrc1_supported_standards' : ActorMethod< + [], + Array<{ 'url' : string, 'name' : string }> + >, + 'icrc1_symbol' : ActorMethod<[], string>, + 'icrc1_total_supply' : ActorMethod<[], Icrc1Tokens>, + 'icrc1_transfer' : ActorMethod<[TransferArg], Icrc1TransferResult>, + 'icrc2_allowance' : ActorMethod<[AllowanceArgs], Allowance>, + 'icrc2_approve' : ActorMethod<[ApproveArgs], ApproveResult>, + 'name' : ActorMethod<[], { 'name' : string }>, + 'query_blocks' : ActorMethod<[GetBlocksArgs], QueryBlocksResponse>, + 'query_encoded_blocks' : ActorMethod< + [GetBlocksArgs], + QueryEncodedBlocksResponse + >, + 'send_dfx' : ActorMethod<[SendArgs], BlockIndex>, + 'symbol' : ActorMethod<[], { 'symbol' : string }>, + 'transfer' : ActorMethod<[TransferArgs], TransferResult>, + 'transfer_fee' : ActorMethod<[TransferFeeArg], TransferFee>, +} +export declare const idlFactory: IDL.InterfaceFactory; +export declare const init: (args: { IDL: typeof IDL }) => IDL.Type[]; diff --git a/apps/wallet/src/generated/icp_ledger/icp_ledger.did.js b/apps/wallet/src/generated/icp_ledger/icp_ledger.did.js new file mode 100644 index 000000000..1dc00ee62 --- /dev/null +++ b/apps/wallet/src/generated/icp_ledger/icp_ledger.did.js @@ -0,0 +1,342 @@ +export const idlFactory = ({ IDL }) => { + const SubAccount = IDL.Vec(IDL.Nat8); + const Account = IDL.Record({ + 'owner' : IDL.Principal, + 'subaccount' : IDL.Opt(SubAccount), + }); + const FeatureFlags = IDL.Record({ 'icrc2' : IDL.Bool }); + const UpgradeArgs = IDL.Record({ + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'icrc1_minting_account' : IDL.Opt(Account), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const Tokens = IDL.Record({ 'e8s' : IDL.Nat64 }); + const TextAccountIdentifier = IDL.Text; + const Duration = IDL.Record({ 'secs' : IDL.Nat64, 'nanos' : IDL.Nat32 }); + const ArchiveOptions = IDL.Record({ + 'num_blocks_to_archive' : IDL.Nat64, + 'trigger_threshold' : IDL.Nat64, + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'cycles_for_archive_creation' : IDL.Opt(IDL.Nat64), + 'node_max_memory_size_bytes' : IDL.Opt(IDL.Nat64), + 'controller_id' : IDL.Principal, + }); + const InitArgs = IDL.Record({ + 'send_whitelist' : IDL.Vec(IDL.Principal), + 'token_symbol' : IDL.Opt(IDL.Text), + 'transfer_fee' : IDL.Opt(Tokens), + 'minting_account' : TextAccountIdentifier, + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'transaction_window' : IDL.Opt(Duration), + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'icrc1_minting_account' : IDL.Opt(Account), + 'archive_options' : IDL.Opt(ArchiveOptions), + 'initial_values' : IDL.Vec(IDL.Tuple(TextAccountIdentifier, Tokens)), + 'token_name' : IDL.Opt(IDL.Text), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const LedgerCanisterPayload = IDL.Variant({ + 'Upgrade' : IDL.Opt(UpgradeArgs), + 'Init' : InitArgs, + }); + const AccountIdentifier = IDL.Vec(IDL.Nat8); + const AccountBalanceArgs = IDL.Record({ 'account' : AccountIdentifier }); + const AccountBalanceArgsDfx = IDL.Record({ + 'account' : TextAccountIdentifier, + }); + const Archive = IDL.Record({ 'canister_id' : IDL.Principal }); + const Archives = IDL.Record({ 'archives' : IDL.Vec(Archive) }); + const Icrc1Tokens = IDL.Nat; + const Value = IDL.Variant({ + 'Int' : IDL.Int, + 'Nat' : IDL.Nat, + 'Blob' : IDL.Vec(IDL.Nat8), + 'Text' : IDL.Text, + }); + const Icrc1Timestamp = IDL.Nat64; + const TransferArg = IDL.Record({ + 'to' : Account, + 'fee' : IDL.Opt(Icrc1Tokens), + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'from_subaccount' : IDL.Opt(SubAccount), + 'created_at_time' : IDL.Opt(Icrc1Timestamp), + 'amount' : Icrc1Tokens, + }); + const Icrc1BlockIndex = IDL.Nat; + const Icrc1TransferError = IDL.Variant({ + 'GenericError' : IDL.Record({ + 'message' : IDL.Text, + 'error_code' : IDL.Nat, + }), + 'TemporarilyUnavailable' : IDL.Null, + 'BadBurn' : IDL.Record({ 'min_burn_amount' : Icrc1Tokens }), + 'Duplicate' : IDL.Record({ 'duplicate_of' : Icrc1BlockIndex }), + 'BadFee' : IDL.Record({ 'expected_fee' : Icrc1Tokens }), + 'CreatedInFuture' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'TooOld' : IDL.Null, + 'InsufficientFunds' : IDL.Record({ 'balance' : Icrc1Tokens }), + }); + const Icrc1TransferResult = IDL.Variant({ + 'Ok' : Icrc1BlockIndex, + 'Err' : Icrc1TransferError, + }); + const AllowanceArgs = IDL.Record({ + 'account' : Account, + 'spender' : Account, + }); + const TimeStamp = IDL.Record({ 'timestamp_nanos' : IDL.Nat64 }); + const Allowance = IDL.Record({ + 'allowance' : Icrc1Tokens, + 'expires_at' : IDL.Opt(TimeStamp), + }); + const ApproveArgs = IDL.Record({ + 'fee' : IDL.Opt(Icrc1Tokens), + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'from_subaccount' : IDL.Opt(SubAccount), + 'created_at_time' : IDL.Opt(TimeStamp), + 'amount' : Icrc1Tokens, + 'expected_allowance' : IDL.Opt(Icrc1Tokens), + 'expires_at' : IDL.Opt(TimeStamp), + 'spender' : Account, + }); + const ApproveError = IDL.Variant({ + 'GenericError' : IDL.Record({ + 'message' : IDL.Text, + 'error_code' : IDL.Nat, + }), + 'TemporarilyUnavailable' : IDL.Null, + 'Duplicate' : IDL.Record({ 'duplicate_of' : Icrc1BlockIndex }), + 'BadFee' : IDL.Record({ 'expected_fee' : Icrc1Tokens }), + 'AllowanceChanged' : IDL.Record({ 'current_allowance' : Icrc1Tokens }), + 'CreatedInFuture' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'TooOld' : IDL.Null, + 'Expired' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'InsufficientFunds' : IDL.Record({ 'balance' : Icrc1Tokens }), + }); + const ApproveResult = IDL.Variant({ + 'Ok' : Icrc1BlockIndex, + 'Err' : ApproveError, + }); + const BlockIndex = IDL.Nat64; + const GetBlocksArgs = IDL.Record({ + 'start' : BlockIndex, + 'length' : IDL.Nat64, + }); + const Memo = IDL.Nat64; + const Operation = IDL.Variant({ + 'Approve' : IDL.Record({ + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'allowance_e8s' : IDL.Int, + 'allowance' : Tokens, + 'expires_at' : IDL.Opt(TimeStamp), + 'spender' : AccountIdentifier, + }), + 'Burn' : IDL.Record({ + 'from' : AccountIdentifier, + 'amount' : Tokens, + 'spender' : IDL.Opt(AccountIdentifier), + }), + 'Mint' : IDL.Record({ 'to' : AccountIdentifier, 'amount' : Tokens }), + 'Transfer' : IDL.Record({ + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'amount' : Tokens, + }), + 'TransferFrom' : IDL.Record({ + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'from' : AccountIdentifier, + 'amount' : Tokens, + 'spender' : AccountIdentifier, + }), + }); + const Transaction = IDL.Record({ + 'memo' : Memo, + 'icrc1_memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'operation' : IDL.Opt(Operation), + 'created_at_time' : TimeStamp, + }); + const Block = IDL.Record({ + 'transaction' : Transaction, + 'timestamp' : TimeStamp, + 'parent_hash' : IDL.Opt(IDL.Vec(IDL.Nat8)), + }); + const BlockRange = IDL.Record({ 'blocks' : IDL.Vec(Block) }); + const QueryArchiveError = IDL.Variant({ + 'BadFirstBlockIndex' : IDL.Record({ + 'requested_index' : BlockIndex, + 'first_valid_index' : BlockIndex, + }), + 'Other' : IDL.Record({ + 'error_message' : IDL.Text, + 'error_code' : IDL.Nat64, + }), + }); + const QueryArchiveResult = IDL.Variant({ + 'Ok' : BlockRange, + 'Err' : QueryArchiveError, + }); + const QueryArchiveFn = IDL.Func( + [GetBlocksArgs], + [QueryArchiveResult], + ['query'], + ); + const ArchivedBlocksRange = IDL.Record({ + 'callback' : QueryArchiveFn, + 'start' : BlockIndex, + 'length' : IDL.Nat64, + }); + const QueryBlocksResponse = IDL.Record({ + 'certificate' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'blocks' : IDL.Vec(Block), + 'chain_length' : IDL.Nat64, + 'first_block_index' : BlockIndex, + 'archived_blocks' : IDL.Vec(ArchivedBlocksRange), + }); + const ArchivedEncodedBlocksRange = IDL.Record({ + 'callback' : IDL.Func( + [GetBlocksArgs], + [ + IDL.Variant({ + 'Ok' : IDL.Vec(IDL.Vec(IDL.Nat8)), + 'Err' : QueryArchiveError, + }), + ], + ['query'], + ), + 'start' : IDL.Nat64, + 'length' : IDL.Nat64, + }); + const QueryEncodedBlocksResponse = IDL.Record({ + 'certificate' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'blocks' : IDL.Vec(IDL.Vec(IDL.Nat8)), + 'chain_length' : IDL.Nat64, + 'first_block_index' : IDL.Nat64, + 'archived_blocks' : IDL.Vec(ArchivedEncodedBlocksRange), + }); + const SendArgs = IDL.Record({ + 'to' : TextAccountIdentifier, + 'fee' : Tokens, + 'memo' : Memo, + 'from_subaccount' : IDL.Opt(SubAccount), + 'created_at_time' : IDL.Opt(TimeStamp), + 'amount' : Tokens, + }); + const TransferArgs = IDL.Record({ + 'to' : AccountIdentifier, + 'fee' : Tokens, + 'memo' : Memo, + 'from_subaccount' : IDL.Opt(SubAccount), + 'created_at_time' : IDL.Opt(TimeStamp), + 'amount' : Tokens, + }); + const TransferError = IDL.Variant({ + 'TxTooOld' : IDL.Record({ 'allowed_window_nanos' : IDL.Nat64 }), + 'BadFee' : IDL.Record({ 'expected_fee' : Tokens }), + 'TxDuplicate' : IDL.Record({ 'duplicate_of' : BlockIndex }), + 'TxCreatedInFuture' : IDL.Null, + 'InsufficientFunds' : IDL.Record({ 'balance' : Tokens }), + }); + const TransferResult = IDL.Variant({ + 'Ok' : BlockIndex, + 'Err' : TransferError, + }); + const TransferFeeArg = IDL.Record({}); + const TransferFee = IDL.Record({ 'transfer_fee' : Tokens }); + return IDL.Service({ + 'account_balance' : IDL.Func([AccountBalanceArgs], [Tokens], ['query']), + 'account_balance_dfx' : IDL.Func( + [AccountBalanceArgsDfx], + [Tokens], + ['query'], + ), + 'archives' : IDL.Func([], [Archives], ['query']), + 'decimals' : IDL.Func( + [], + [IDL.Record({ 'decimals' : IDL.Nat32 })], + ['query'], + ), + 'icrc1_balance_of' : IDL.Func([Account], [Icrc1Tokens], ['query']), + 'icrc1_decimals' : IDL.Func([], [IDL.Nat8], ['query']), + 'icrc1_fee' : IDL.Func([], [Icrc1Tokens], ['query']), + 'icrc1_metadata' : IDL.Func( + [], + [IDL.Vec(IDL.Tuple(IDL.Text, Value))], + ['query'], + ), + 'icrc1_minting_account' : IDL.Func([], [IDL.Opt(Account)], ['query']), + 'icrc1_name' : IDL.Func([], [IDL.Text], ['query']), + 'icrc1_supported_standards' : IDL.Func( + [], + [IDL.Vec(IDL.Record({ 'url' : IDL.Text, 'name' : IDL.Text }))], + ['query'], + ), + 'icrc1_symbol' : IDL.Func([], [IDL.Text], ['query']), + 'icrc1_total_supply' : IDL.Func([], [Icrc1Tokens], ['query']), + 'icrc1_transfer' : IDL.Func([TransferArg], [Icrc1TransferResult], []), + 'icrc2_allowance' : IDL.Func([AllowanceArgs], [Allowance], ['query']), + 'icrc2_approve' : IDL.Func([ApproveArgs], [ApproveResult], []), + 'name' : IDL.Func([], [IDL.Record({ 'name' : IDL.Text })], ['query']), + 'query_blocks' : IDL.Func( + [GetBlocksArgs], + [QueryBlocksResponse], + ['query'], + ), + 'query_encoded_blocks' : IDL.Func( + [GetBlocksArgs], + [QueryEncodedBlocksResponse], + ['query'], + ), + 'send_dfx' : IDL.Func([SendArgs], [BlockIndex], []), + 'symbol' : IDL.Func([], [IDL.Record({ 'symbol' : IDL.Text })], ['query']), + 'transfer' : IDL.Func([TransferArgs], [TransferResult], []), + 'transfer_fee' : IDL.Func([TransferFeeArg], [TransferFee], ['query']), + }); +}; +export const init = ({ IDL }) => { + const SubAccount = IDL.Vec(IDL.Nat8); + const Account = IDL.Record({ + 'owner' : IDL.Principal, + 'subaccount' : IDL.Opt(SubAccount), + }); + const FeatureFlags = IDL.Record({ 'icrc2' : IDL.Bool }); + const UpgradeArgs = IDL.Record({ + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'icrc1_minting_account' : IDL.Opt(Account), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const Tokens = IDL.Record({ 'e8s' : IDL.Nat64 }); + const TextAccountIdentifier = IDL.Text; + const Duration = IDL.Record({ 'secs' : IDL.Nat64, 'nanos' : IDL.Nat32 }); + const ArchiveOptions = IDL.Record({ + 'num_blocks_to_archive' : IDL.Nat64, + 'trigger_threshold' : IDL.Nat64, + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'cycles_for_archive_creation' : IDL.Opt(IDL.Nat64), + 'node_max_memory_size_bytes' : IDL.Opt(IDL.Nat64), + 'controller_id' : IDL.Principal, + }); + const InitArgs = IDL.Record({ + 'send_whitelist' : IDL.Vec(IDL.Principal), + 'token_symbol' : IDL.Opt(IDL.Text), + 'transfer_fee' : IDL.Opt(Tokens), + 'minting_account' : TextAccountIdentifier, + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'transaction_window' : IDL.Opt(Duration), + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'icrc1_minting_account' : IDL.Opt(Account), + 'archive_options' : IDL.Opt(ArchiveOptions), + 'initial_values' : IDL.Vec(IDL.Tuple(TextAccountIdentifier, Tokens)), + 'token_name' : IDL.Opt(IDL.Text), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const LedgerCanisterPayload = IDL.Variant({ + 'Upgrade' : IDL.Opt(UpgradeArgs), + 'Init' : InitArgs, + }); + return [LedgerCanisterPayload]; +}; diff --git a/apps/wallet/src/generated/icp_ledger/index.d.ts b/apps/wallet/src/generated/icp_ledger/index.d.ts new file mode 100644 index 000000000..513ca9e74 --- /dev/null +++ b/apps/wallet/src/generated/icp_ledger/index.d.ts @@ -0,0 +1,50 @@ +import type { + ActorSubclass, + HttpAgentOptions, + ActorConfig, + Agent, +} from "@dfinity/agent"; +import type { Principal } from "@dfinity/principal"; +import type { IDL } from "@dfinity/candid"; + +import { _SERVICE } from './icp_ledger.did'; + +export declare const idlFactory: IDL.InterfaceFactory; +export declare const canisterId: string; + +export declare interface CreateActorOptions { + /** + * @see {@link Agent} + */ + agent?: Agent; + /** + * @see {@link HttpAgentOptions} + */ + agentOptions?: HttpAgentOptions; + /** + * @see {@link ActorConfig} + */ + actorOptions?: ActorConfig; +} + +/** + * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister. + * @constructs {@link ActorSubClass} + * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to + * @param {CreateActorOptions} options - see {@link CreateActorOptions} + * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions + * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent + * @see {@link HttpAgentOptions} + * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor + * @see {@link ActorConfig} + */ +export declare const createActor: ( + canisterId: string | Principal, + options?: CreateActorOptions +) => ActorSubclass<_SERVICE>; + +/** + * Intialized Actor using default settings, ready to talk to a canister using its candid interface + * @constructs {@link ActorSubClass} + */ +export declare const icp_ledger: ActorSubclass<_SERVICE>; diff --git a/apps/wallet/src/generated/icp_ledger/index.js b/apps/wallet/src/generated/icp_ledger/index.js new file mode 100644 index 000000000..e0f474543 --- /dev/null +++ b/apps/wallet/src/generated/icp_ledger/index.js @@ -0,0 +1,40 @@ +import { Actor, HttpAgent } from "@dfinity/agent"; + +// Imports and re-exports candid interface +import { idlFactory } from "./icp_ledger.did.js"; +export { idlFactory } from "./icp_ledger.did.js"; + +/* CANISTER_ID is replaced by webpack based on node environment + * Note: canister environment variable will be standardized as + * process.env.CANISTER_ID_ + * beginning in dfx 0.15.0 + */ +export const canisterId = + process.env.CANISTER_ID_ICP_LEDGER; + +export const createActor = (canisterId, options = {}) => { + const agent = options.agent || new HttpAgent({ ...options.agentOptions }); + + if (options.agent && options.agentOptions) { + console.warn( + "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent." + ); + } + + // Fetch root key for certificate validation during development + if (process.env.DFX_NETWORK !== "ic") { + agent.fetchRootKey().catch((err) => { + console.warn( + "Unable to fetch root key. Check to ensure that your local replica is running" + ); + console.error(err); + }); + } + + // Creates an actor with using the candid interface and the HttpAgent + return Actor.createActor(idlFactory, { + agent, + canisterId, + ...options.actorOptions, + }); +}; diff --git a/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did new file mode 100644 index 000000000..5cc7429a6 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did @@ -0,0 +1,143 @@ +type Tokens = nat; + +type InitArg = record { + ledger_id: principal; +}; + +type UpgradeArg = record { + ledger_id: opt principal; +}; + +type IndexArg = variant { + Init: InitArg; + Upgrade: UpgradeArg; +}; + +type GetBlocksRequest = record { + start : nat; + length : nat; +}; + +type Value = variant { + Blob : blob; + Text : text; + Nat : nat; + Nat64: nat64; + Int : int; + Array : vec Value; + Map : Map; +}; + +type Map = vec record { text; Value }; + +type Block = Value; + +type GetBlocksResponse = record { + chain_length: nat64; + blocks: vec Block; +}; + +type BlockIndex = nat; + +type SubAccount = blob; + +type Account = record { owner : principal; subaccount : opt SubAccount }; + +type Transaction = record { + burn : opt Burn; + kind : text; + mint : opt Mint; + approve : opt Approve; + timestamp : nat64; + transfer : opt Transfer; +}; + +type Approve = record { + fee : opt nat; + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + expected_allowance : opt nat; + expires_at : opt nat64; + spender : Account; +}; + +type Burn = record { + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + spender : opt Account; +}; + +type Mint = record { + to : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; +}; + +type Transfer = record { + to : Account; + fee : opt nat; + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + spender : opt Account; +}; + +type GetAccountTransactionsArgs = record { + account : Account; + // The txid of the last transaction seen by the client. + // If None then the results will start from the most recent + // txid. + start : opt BlockIndex; + // Maximum number of transactions to fetch. + max_results : nat; +}; + +type TransactionWithId = record { + id : BlockIndex; + transaction : Transaction; +}; + +type GetTransactions = record { + balance : Tokens; + transactions : vec TransactionWithId; + // The txid of the oldest transaction the account has + oldest_tx_id : opt BlockIndex; +}; + +type GetTransactionsErr = record { + message : text; +}; + +type GetTransactionsResult = variant { + Ok : GetTransactions; + Err : GetTransactionsErr; +}; + +type ListSubaccountsArgs = record { + owner: principal; + start: opt SubAccount; +}; + +type Status = record { + num_blocks_synced : BlockIndex; +}; + +type FeeCollectorRanges = record { + ranges : vec record { Account; vec record { BlockIndex; BlockIndex } }; +} + +service : (index_arg: opt IndexArg) -> { + get_account_transactions : (GetAccountTransactionsArgs) -> (GetTransactionsResult) query; + get_blocks : (GetBlocksRequest) -> (GetBlocksResponse) query; + get_fee_collectors_ranges : () -> (FeeCollectorRanges) query; + icrc1_balance_of : (Account) -> (Tokens) query; + ledger_id : () -> (principal) query; + list_subaccounts : (ListSubaccountsArgs) -> (vec SubAccount) query; + status : () -> (Status) query; +} diff --git a/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.d.ts b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.d.ts new file mode 100644 index 000000000..9a93a9a71 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.d.ts @@ -0,0 +1,108 @@ +import type { Principal } from '@dfinity/principal'; +import type { ActorMethod } from '@dfinity/agent'; +import type { IDL } from '@dfinity/candid'; + +export interface Account { + 'owner' : Principal, + 'subaccount' : [] | [SubAccount], +} +export interface Approve { + 'fee' : [] | [bigint], + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'expected_allowance' : [] | [bigint], + 'expires_at' : [] | [bigint], + 'spender' : Account, +} +export type Block = Value; +export type BlockIndex = bigint; +export interface Burn { + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'spender' : [] | [Account], +} +export interface FeeCollectorRanges { + 'ranges' : Array<[Account, Array<[BlockIndex, BlockIndex]>]>, +} +export interface GetAccountTransactionsArgs { + 'max_results' : bigint, + 'start' : [] | [BlockIndex], + 'account' : Account, +} +export interface GetBlocksRequest { 'start' : bigint, 'length' : bigint } +export interface GetBlocksResponse { + 'blocks' : Array, + 'chain_length' : bigint, +} +export interface GetTransactions { + 'balance' : Tokens, + 'transactions' : Array, + 'oldest_tx_id' : [] | [BlockIndex], +} +export interface GetTransactionsErr { 'message' : string } +export type GetTransactionsResult = { 'Ok' : GetTransactions } | + { 'Err' : GetTransactionsErr }; +export type IndexArg = { 'Upgrade' : UpgradeArg } | + { 'Init' : InitArg }; +export interface InitArg { 'ledger_id' : Principal } +export interface ListSubaccountsArgs { + 'owner' : Principal, + 'start' : [] | [SubAccount], +} +export type Map = Array<[string, Value]>; +export interface Mint { + 'to' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, +} +export interface Status { 'num_blocks_synced' : BlockIndex } +export type SubAccount = Uint8Array | number[]; +export type Tokens = bigint; +export interface Transaction { + 'burn' : [] | [Burn], + 'kind' : string, + 'mint' : [] | [Mint], + 'approve' : [] | [Approve], + 'timestamp' : bigint, + 'transfer' : [] | [Transfer], +} +export interface TransactionWithId { + 'id' : BlockIndex, + 'transaction' : Transaction, +} +export interface Transfer { + 'to' : Account, + 'fee' : [] | [bigint], + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'spender' : [] | [Account], +} +export interface UpgradeArg { 'ledger_id' : [] | [Principal] } +export type Value = { 'Int' : bigint } | + { 'Map' : Map } | + { 'Nat' : bigint } | + { 'Nat64' : bigint } | + { 'Blob' : Uint8Array | number[] } | + { 'Text' : string } | + { 'Array' : Array }; +export interface _SERVICE { + 'get_account_transactions' : ActorMethod< + [GetAccountTransactionsArgs], + GetTransactionsResult + >, + 'get_blocks' : ActorMethod<[GetBlocksRequest], GetBlocksResponse>, + 'get_fee_collectors_ranges' : ActorMethod<[], FeeCollectorRanges>, + 'icrc1_balance_of' : ActorMethod<[Account], Tokens>, + 'ledger_id' : ActorMethod<[], Principal>, + 'list_subaccounts' : ActorMethod<[ListSubaccountsArgs], Array>, + 'status' : ActorMethod<[], Status>, +} +export declare const idlFactory: IDL.InterfaceFactory; +export declare const init: (args: { IDL: typeof IDL }) => IDL.Type[]; diff --git a/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.js b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.js new file mode 100644 index 000000000..0374e7632 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_index/icrc1_index_canister.did.js @@ -0,0 +1,126 @@ +export const idlFactory = ({ IDL }) => { + const Value = IDL.Rec(); + const UpgradeArg = IDL.Record({ 'ledger_id' : IDL.Opt(IDL.Principal) }); + const InitArg = IDL.Record({ 'ledger_id' : IDL.Principal }); + const IndexArg = IDL.Variant({ 'Upgrade' : UpgradeArg, 'Init' : InitArg }); + const BlockIndex = IDL.Nat; + const SubAccount = IDL.Vec(IDL.Nat8); + const Account = IDL.Record({ + 'owner' : IDL.Principal, + 'subaccount' : IDL.Opt(SubAccount), + }); + const GetAccountTransactionsArgs = IDL.Record({ + 'max_results' : IDL.Nat, + 'start' : IDL.Opt(BlockIndex), + 'account' : Account, + }); + const Tokens = IDL.Nat; + const Burn = IDL.Record({ + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'spender' : IDL.Opt(Account), + }); + const Mint = IDL.Record({ + 'to' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + }); + const Approve = IDL.Record({ + 'fee' : IDL.Opt(IDL.Nat), + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'expected_allowance' : IDL.Opt(IDL.Nat), + 'expires_at' : IDL.Opt(IDL.Nat64), + 'spender' : Account, + }); + const Transfer = IDL.Record({ + 'to' : Account, + 'fee' : IDL.Opt(IDL.Nat), + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'spender' : IDL.Opt(Account), + }); + const Transaction = IDL.Record({ + 'burn' : IDL.Opt(Burn), + 'kind' : IDL.Text, + 'mint' : IDL.Opt(Mint), + 'approve' : IDL.Opt(Approve), + 'timestamp' : IDL.Nat64, + 'transfer' : IDL.Opt(Transfer), + }); + const TransactionWithId = IDL.Record({ + 'id' : BlockIndex, + 'transaction' : Transaction, + }); + const GetTransactions = IDL.Record({ + 'balance' : Tokens, + 'transactions' : IDL.Vec(TransactionWithId), + 'oldest_tx_id' : IDL.Opt(BlockIndex), + }); + const GetTransactionsErr = IDL.Record({ 'message' : IDL.Text }); + const GetTransactionsResult = IDL.Variant({ + 'Ok' : GetTransactions, + 'Err' : GetTransactionsErr, + }); + const GetBlocksRequest = IDL.Record({ + 'start' : IDL.Nat, + 'length' : IDL.Nat, + }); + const Map = IDL.Vec(IDL.Tuple(IDL.Text, Value)); + Value.fill( + IDL.Variant({ + 'Int' : IDL.Int, + 'Map' : Map, + 'Nat' : IDL.Nat, + 'Nat64' : IDL.Nat64, + 'Blob' : IDL.Vec(IDL.Nat8), + 'Text' : IDL.Text, + 'Array' : IDL.Vec(Value), + }) + ); + const Block = Value; + const GetBlocksResponse = IDL.Record({ + 'blocks' : IDL.Vec(Block), + 'chain_length' : IDL.Nat64, + }); + const FeeCollectorRanges = IDL.Record({ + 'ranges' : IDL.Vec( + IDL.Tuple(Account, IDL.Vec(IDL.Tuple(BlockIndex, BlockIndex))) + ), + }); + const ListSubaccountsArgs = IDL.Record({ + 'owner' : IDL.Principal, + 'start' : IDL.Opt(SubAccount), + }); + const Status = IDL.Record({ 'num_blocks_synced' : BlockIndex }); + return IDL.Service({ + 'get_account_transactions' : IDL.Func( + [GetAccountTransactionsArgs], + [GetTransactionsResult], + ['query'], + ), + 'get_blocks' : IDL.Func([GetBlocksRequest], [GetBlocksResponse], ['query']), + 'get_fee_collectors_ranges' : IDL.Func([], [FeeCollectorRanges], ['query']), + 'icrc1_balance_of' : IDL.Func([Account], [Tokens], ['query']), + 'ledger_id' : IDL.Func([], [IDL.Principal], ['query']), + 'list_subaccounts' : IDL.Func( + [ListSubaccountsArgs], + [IDL.Vec(SubAccount)], + ['query'], + ), + 'status' : IDL.Func([], [Status], ['query']), + }); +}; +export const init = ({ IDL }) => { + const UpgradeArg = IDL.Record({ 'ledger_id' : IDL.Opt(IDL.Principal) }); + const InitArg = IDL.Record({ 'ledger_id' : IDL.Principal }); + const IndexArg = IDL.Variant({ 'Upgrade' : UpgradeArg, 'Init' : InitArg }); + return [IDL.Opt(IndexArg)]; +}; diff --git a/apps/wallet/src/generated/icrc1_index/index.d.ts b/apps/wallet/src/generated/icrc1_index/index.d.ts new file mode 100644 index 000000000..b5d550620 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_index/index.d.ts @@ -0,0 +1,50 @@ +import type { + ActorSubclass, + HttpAgentOptions, + ActorConfig, + Agent, +} from "@dfinity/agent"; +import type { Principal } from "@dfinity/principal"; +import type { IDL } from "@dfinity/candid"; + +import { _SERVICE } from './icrc1_index_canister.did'; + +export declare const idlFactory: IDL.InterfaceFactory; +export declare const canisterId: string; + +export declare interface CreateActorOptions { + /** + * @see {@link Agent} + */ + agent?: Agent; + /** + * @see {@link HttpAgentOptions} + */ + agentOptions?: HttpAgentOptions; + /** + * @see {@link ActorConfig} + */ + actorOptions?: ActorConfig; +} + +/** + * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister. + * @constructs {@link ActorSubClass} + * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to + * @param {CreateActorOptions} options - see {@link CreateActorOptions} + * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions + * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent + * @see {@link HttpAgentOptions} + * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor + * @see {@link ActorConfig} + */ +export declare const createActor: ( + canisterId: string | Principal, + options?: CreateActorOptions +) => ActorSubclass<_SERVICE>; + +/** + * Intialized Actor using default settings, ready to talk to a canister using its candid interface + * @constructs {@link ActorSubClass} + */ +export declare const icrc1_index_canister: ActorSubclass<_SERVICE>; diff --git a/apps/wallet/src/generated/icrc1_index/index.js b/apps/wallet/src/generated/icrc1_index/index.js new file mode 100644 index 000000000..084e136d6 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_index/index.js @@ -0,0 +1,40 @@ +import { Actor, HttpAgent } from "@dfinity/agent"; + +// Imports and re-exports candid interface +import { idlFactory } from "./icrc1_index_canister.did.js"; +export { idlFactory } from "./icrc1_index_canister.did.js"; + +/* CANISTER_ID is replaced by webpack based on node environment + * Note: canister environment variable will be standardized as + * process.env.CANISTER_ID_ + * beginning in dfx 0.15.0 + */ +export const canisterId = + process.env.CANISTER_ID_ICRC1_INDEX_CANISTER; + +export const createActor = (canisterId, options = {}) => { + const agent = options.agent || new HttpAgent({ ...options.agentOptions }); + + if (options.agent && options.agentOptions) { + console.warn( + "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent." + ); + } + + // Fetch root key for certificate validation during development + if (process.env.DFX_NETWORK !== "ic") { + agent.fetchRootKey().catch((err) => { + console.warn( + "Unable to fetch root key. Check to ensure that your local replica is running" + ); + console.error(err); + }); + } + + // Creates an actor with using the candid interface and the HttpAgent + return Actor.createActor(idlFactory, { + agent, + canisterId, + ...options.actorOptions, + }); +}; diff --git a/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did new file mode 100644 index 000000000..1efe7f6fb --- /dev/null +++ b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did @@ -0,0 +1,379 @@ +type BlockIndex = nat; +type Subaccount = blob; +// Number of nanoseconds since the UNIX epoch in UTC timezone. +type Timestamp = nat64; +// Number of nanoseconds between two [Timestamp]s. +type Duration = nat64; +type Tokens = nat; +type TxIndex = nat; +type Allowance = record { allowance : nat; expires_at : opt nat64 }; +type AllowanceArgs = record { account : Account; spender : Account }; +type Approve = record { + fee : opt nat; + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + expected_allowance : opt nat; + expires_at : opt nat64; + spender : Account; +}; +type ApproveArgs = record { + fee : opt nat; + memo : opt vec nat8; + from_subaccount : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + expected_allowance : opt nat; + expires_at : opt nat64; + spender : Account; +}; +type ApproveError = variant { + GenericError : record { message : text; error_code : nat }; + TemporarilyUnavailable; + Duplicate : record { duplicate_of : nat }; + BadFee : record { expected_fee : nat }; + AllowanceChanged : record { current_allowance : nat }; + CreatedInFuture : record { ledger_time : nat64 }; + TooOld; + Expired : record { ledger_time : nat64 }; + InsufficientFunds : record { balance : nat }; +}; +type ApproveResult = variant { Ok : nat; Err : ApproveError }; + +type HttpRequest = record { + url : text; + method : text; + body : vec nat8; + headers : vec record { text; text }; +}; +type HttpResponse = record { + body : vec nat8; + headers : vec record { text; text }; + status_code : nat16; +}; + +type Account = record { + owner : principal; + subaccount : opt Subaccount; +}; + +type TransferArg = record { + from_subaccount : opt Subaccount; + to : Account; + amount : Tokens; + fee : opt Tokens; + memo : opt blob; + created_at_time: opt Timestamp; +}; + +type TransferError = variant { + BadFee : record { expected_fee : Tokens }; + BadBurn : record { min_burn_amount : Tokens }; + InsufficientFunds : record { balance : Tokens }; + TooOld; + CreatedInFuture : record { ledger_time : nat64 }; + TemporarilyUnavailable; + Duplicate : record { duplicate_of : BlockIndex }; + GenericError : record { error_code : nat; message : text }; +}; + +type TransferResult = variant { + Ok : BlockIndex; + Err : TransferError; +}; + +// The value returned from the [icrc1_metadata] endpoint. +type MetadataValue = variant { + Nat : nat; + Int : int; + Text : text; + Blob : blob; +}; + +type FeatureFlags = record { + icrc2 : bool; +}; + +// The initialization parameters of the Ledger +type InitArgs = record { + minting_account : Account; + fee_collector_account : opt Account; + transfer_fee : nat; + decimals : opt nat8; + max_memo_length : opt nat16; + token_symbol : text; + token_name : text; + metadata : vec record { text; MetadataValue }; + initial_balances : vec record { Account; nat }; + feature_flags : opt FeatureFlags; + maximum_number_of_accounts : opt nat64; + accounts_overflow_trim_quantity : opt nat64; + archive_options : record { + num_blocks_to_archive : nat64; + max_transactions_per_response : opt nat64; + trigger_threshold : nat64; + max_message_size_bytes : opt nat64; + cycles_for_archive_creation : opt nat64; + node_max_memory_size_bytes : opt nat64; + controller_id : principal; + }; +}; + +type ChangeFeeCollector = variant { + Unset; SetTo: Account; +}; + +type UpgradeArgs = record { + metadata : opt vec record { text; MetadataValue }; + token_symbol : opt text; + token_name : opt text; + transfer_fee : opt nat; + change_fee_collector : opt ChangeFeeCollector; + max_memo_length : opt nat16; + feature_flags : opt FeatureFlags; + maximum_number_of_accounts: opt nat64; + accounts_overflow_trim_quantity: opt nat64; +}; + +type LedgerArg = variant { + Init: InitArgs; + Upgrade: opt UpgradeArgs; +}; + +type GetTransactionsRequest = record { + // The index of the first tx to fetch. + start : TxIndex; + // The number of transactions to fetch. + length : nat; +}; + +type GetTransactionsResponse = record { + // The total number of transactions in the log. + log_length : nat; + + // List of transaction that were available in the ledger when it processed the call. + // + // The transactions form a contiguous range, with the first transaction having index + // [first_index] (see below), and the last transaction having index + // [first_index] + len(transactions) - 1. + // + // The transaction range can be an arbitrary sub-range of the originally requested range. + transactions : vec Transaction; + + // The index of the first transaction in [transactions]. + // If the transaction vector is empty, the exact value of this field is not specified. + first_index : TxIndex; + + // Encoding of instructions for fetching archived transactions whose indices fall into the + // requested range. + // + // For each entry `e` in [archived_transactions], `[e.from, e.from + len)` is a sub-range + // of the originally requested transaction range. + archived_transactions : vec record { + // The index of the first archived transaction you can fetch using the [callback]. + start : TxIndex; + + // The number of transactions you can fetch using the callback. + length : nat; + + // The function you should call to fetch the archived transactions. + // The range of the transaction accessible using this function is given by [from] + // and [len] fields above. + callback : QueryArchiveFn; + }; +}; + + +// A prefix of the transaction range specified in the [GetTransactionsRequest] request. +type TransactionRange = record { + // A prefix of the requested transaction range. + // The index of the first transaction is equal to [GetTransactionsRequest.from]. + // + // Note that the number of transactions might be less than the requested + // [GetTransactionsRequest.length] for various reasons, for example: + // + // 1. The query might have hit the replica with an outdated state + // that doesn't have the whole range yet. + // 2. The requested range is too large to fit into a single reply. + // + // NOTE: the list of transactions can be empty if: + // + // 1. [GetTransactionsRequest.length] was zero. + // 2. [GetTransactionsRequest.from] was larger than the last transaction known to + // the canister. + transactions : vec Transaction; +}; + +// A function for fetching archived transaction. +type QueryArchiveFn = func (GetTransactionsRequest) -> (TransactionRange) query; + +type Transaction = record { + burn : opt Burn; + kind : text; + mint : opt Mint; + approve : opt Approve; + timestamp : nat64; + transfer : opt Transfer; +}; + +type Burn = record { + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + spender : opt Account; +}; + +type Mint = record { + to : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; +}; + +type Transfer = record { + to : Account; + fee : opt nat; + from : Account; + memo : opt vec nat8; + created_at_time : opt nat64; + amount : nat; + spender : opt Account; +}; + +type Value = variant { + Blob : blob; + Text : text; + Nat : nat; + Nat64: nat64; + Int : int; + Array : vec Value; + Map : Map; +}; + +type Map = vec record { text; Value }; + +type Block = Value; + +type GetBlocksArgs = record { + // The index of the first block to fetch. + start : BlockIndex; + // Max number of blocks to fetch. + length : nat; +}; + +// A prefix of the block range specified in the [GetBlocksArgs] request. +type BlockRange = record { + // A prefix of the requested block range. + // The index of the first block is equal to [GetBlocksArgs.start]. + // + // Note that the number of blocks might be less than the requested + // [GetBlocksArgs.length] for various reasons, for example: + // + // 1. The query might have hit the replica with an outdated state + // that doesn't have the whole range yet. + // 2. The requested range is too large to fit into a single reply. + // + // NOTE: the list of blocks can be empty if: + // + // 1. [GetBlocksArgs.length] was zero. + // 2. [GetBlocksArgs.start] was larger than the last block known to + // the canister. + blocks : vec Block; +}; + +// A function for fetching archived blocks. +type QueryBlockArchiveFn = func (GetBlocksArgs) -> (BlockRange) query; + +// The result of a "get_blocks" call. +type GetBlocksResponse = record { + // The index of the first block in "blocks". + // If the blocks vector is empty, the exact value of this field is not specified. + first_index : BlockIndex; + + // The total number of blocks in the chain. + // If the chain length is positive, the index of the last block is `chain_len - 1`. + chain_length : nat64; + + // System certificate for the hash of the latest block in the chain. + // Only present if `get_blocks` is called in a non-replicated query context. + certificate : opt blob; + + // List of blocks that were available in the ledger when it processed the call. + // + // The blocks form a contiguous range, with the first block having index + // [first_block_index] (see below), and the last block having index + // [first_block_index] + len(blocks) - 1. + // + // The block range can be an arbitrary sub-range of the originally requested range. + blocks : vec Block; + + // Encoding of instructions for fetching archived blocks. + archived_blocks : vec record { + // The index of the first archived block. + start : BlockIndex; + + // The number of blocks that can be fetched. + length : nat; + + // Callback to fetch the archived blocks. + callback : QueryBlockArchiveFn; + }; +}; + +// Certificate for the block at `block_index`. +type DataCertificate = record { + certificate : opt blob; + hash_tree : blob; +}; + +type StandardRecord = record { url : text; name : text }; + +type TransferFromArgs = record { + spender_subaccount : opt Subaccount; + from : Account; + to : Account; + amount : Tokens; + fee : opt Tokens; + memo : opt blob; + created_at_time: opt Timestamp; +}; + +type TransferFromResult = variant { + Ok : BlockIndex; + Err : TransferFromError; +}; + +type TransferFromError = variant { + BadFee : record { expected_fee : Tokens }; + BadBurn : record { min_burn_amount : Tokens }; + InsufficientFunds : record { balance : Tokens }; + InsufficientAllowance : record { allowance : Tokens }; + TooOld; + CreatedInFuture : record { ledger_time : nat64 }; + Duplicate : record { duplicate_of : BlockIndex }; + TemporarilyUnavailable; + GenericError : record { error_code : nat; message : text }; +}; + +service : (ledger_arg : LedgerArg) -> { + get_transactions : (GetTransactionsRequest) -> (GetTransactionsResponse) query; + get_blocks : (GetBlocksArgs) -> (GetBlocksResponse) query; + get_data_certificate : () -> (DataCertificate) query; + + icrc1_name : () -> (text) query; + icrc1_symbol : () -> (text) query; + icrc1_decimals : () -> (nat8) query; + icrc1_metadata : () -> (vec record { text; MetadataValue }) query; + icrc1_total_supply : () -> (Tokens) query; + icrc1_fee : () -> (Tokens) query; + icrc1_minting_account : () -> (opt Account) query; + icrc1_balance_of : (Account) -> (Tokens) query; + icrc1_transfer : (TransferArg) -> (TransferResult); + icrc1_supported_standards : () -> (vec StandardRecord) query; + + icrc2_approve : (ApproveArgs) -> (ApproveResult); + icrc2_allowance : (AllowanceArgs) -> (Allowance) query; + icrc2_transfer_from : (TransferFromArgs) -> (TransferFromResult); +} diff --git a/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.d.ts b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.d.ts new file mode 100644 index 000000000..5a6ef4b78 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.d.ts @@ -0,0 +1,245 @@ +import type { Principal } from '@dfinity/principal'; +import type { ActorMethod } from '@dfinity/agent'; +import type { IDL } from '@dfinity/candid'; + +export interface Account { + 'owner' : Principal, + 'subaccount' : [] | [Subaccount], +} +export interface Allowance { + 'allowance' : bigint, + 'expires_at' : [] | [bigint], +} +export interface AllowanceArgs { 'account' : Account, 'spender' : Account } +export interface Approve { + 'fee' : [] | [bigint], + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'expected_allowance' : [] | [bigint], + 'expires_at' : [] | [bigint], + 'spender' : Account, +} +export interface ApproveArgs { + 'fee' : [] | [bigint], + 'memo' : [] | [Uint8Array | number[]], + 'from_subaccount' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'expected_allowance' : [] | [bigint], + 'expires_at' : [] | [bigint], + 'spender' : Account, +} +export type ApproveError = { + 'GenericError' : { 'message' : string, 'error_code' : bigint } + } | + { 'TemporarilyUnavailable' : null } | + { 'Duplicate' : { 'duplicate_of' : bigint } } | + { 'BadFee' : { 'expected_fee' : bigint } } | + { 'AllowanceChanged' : { 'current_allowance' : bigint } } | + { 'CreatedInFuture' : { 'ledger_time' : bigint } } | + { 'TooOld' : null } | + { 'Expired' : { 'ledger_time' : bigint } } | + { 'InsufficientFunds' : { 'balance' : bigint } }; +export type ApproveResult = { 'Ok' : bigint } | + { 'Err' : ApproveError }; +export type Block = Value; +export type BlockIndex = bigint; +export interface BlockRange { 'blocks' : Array } +export interface Burn { + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'spender' : [] | [Account], +} +export type ChangeFeeCollector = { 'SetTo' : Account } | + { 'Unset' : null }; +export interface DataCertificate { + 'certificate' : [] | [Uint8Array | number[]], + 'hash_tree' : Uint8Array | number[], +} +export type Duration = bigint; +export interface FeatureFlags { 'icrc2' : boolean } +export interface GetBlocksArgs { 'start' : BlockIndex, 'length' : bigint } +export interface GetBlocksResponse { + 'certificate' : [] | [Uint8Array | number[]], + 'first_index' : BlockIndex, + 'blocks' : Array, + 'chain_length' : bigint, + 'archived_blocks' : Array< + { + 'callback' : QueryBlockArchiveFn, + 'start' : BlockIndex, + 'length' : bigint, + } + >, +} +export interface GetTransactionsRequest { 'start' : TxIndex, 'length' : bigint } +export interface GetTransactionsResponse { + 'first_index' : TxIndex, + 'log_length' : bigint, + 'transactions' : Array, + 'archived_transactions' : Array< + { 'callback' : QueryArchiveFn, 'start' : TxIndex, 'length' : bigint } + >, +} +export interface HttpRequest { + 'url' : string, + 'method' : string, + 'body' : Uint8Array | number[], + 'headers' : Array<[string, string]>, +} +export interface HttpResponse { + 'body' : Uint8Array | number[], + 'headers' : Array<[string, string]>, + 'status_code' : number, +} +export interface InitArgs { + 'decimals' : [] | [number], + 'token_symbol' : string, + 'transfer_fee' : bigint, + 'metadata' : Array<[string, MetadataValue]>, + 'minting_account' : Account, + 'initial_balances' : Array<[Account, bigint]>, + 'maximum_number_of_accounts' : [] | [bigint], + 'accounts_overflow_trim_quantity' : [] | [bigint], + 'fee_collector_account' : [] | [Account], + 'archive_options' : { + 'num_blocks_to_archive' : bigint, + 'max_transactions_per_response' : [] | [bigint], + 'trigger_threshold' : bigint, + 'max_message_size_bytes' : [] | [bigint], + 'cycles_for_archive_creation' : [] | [bigint], + 'node_max_memory_size_bytes' : [] | [bigint], + 'controller_id' : Principal, + }, + 'max_memo_length' : [] | [number], + 'token_name' : string, + 'feature_flags' : [] | [FeatureFlags], +} +export type LedgerArg = { 'Upgrade' : [] | [UpgradeArgs] } | + { 'Init' : InitArgs }; +export type Map = Array<[string, Value]>; +export type MetadataValue = { 'Int' : bigint } | + { 'Nat' : bigint } | + { 'Blob' : Uint8Array | number[] } | + { 'Text' : string }; +export interface Mint { + 'to' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, +} +export type QueryArchiveFn = ActorMethod< + [GetTransactionsRequest], + TransactionRange +>; +export type QueryBlockArchiveFn = ActorMethod<[GetBlocksArgs], BlockRange>; +export interface StandardRecord { 'url' : string, 'name' : string } +export type Subaccount = Uint8Array | number[]; +export type Timestamp = bigint; +export type Tokens = bigint; +export interface Transaction { + 'burn' : [] | [Burn], + 'kind' : string, + 'mint' : [] | [Mint], + 'approve' : [] | [Approve], + 'timestamp' : bigint, + 'transfer' : [] | [Transfer], +} +export interface TransactionRange { 'transactions' : Array } +export interface Transfer { + 'to' : Account, + 'fee' : [] | [bigint], + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [bigint], + 'amount' : bigint, + 'spender' : [] | [Account], +} +export interface TransferArg { + 'to' : Account, + 'fee' : [] | [Tokens], + 'memo' : [] | [Uint8Array | number[]], + 'from_subaccount' : [] | [Subaccount], + 'created_at_time' : [] | [Timestamp], + 'amount' : Tokens, +} +export type TransferError = { + 'GenericError' : { 'message' : string, 'error_code' : bigint } + } | + { 'TemporarilyUnavailable' : null } | + { 'BadBurn' : { 'min_burn_amount' : Tokens } } | + { 'Duplicate' : { 'duplicate_of' : BlockIndex } } | + { 'BadFee' : { 'expected_fee' : Tokens } } | + { 'CreatedInFuture' : { 'ledger_time' : bigint } } | + { 'TooOld' : null } | + { 'InsufficientFunds' : { 'balance' : Tokens } }; +export interface TransferFromArgs { + 'to' : Account, + 'fee' : [] | [Tokens], + 'spender_subaccount' : [] | [Subaccount], + 'from' : Account, + 'memo' : [] | [Uint8Array | number[]], + 'created_at_time' : [] | [Timestamp], + 'amount' : Tokens, +} +export type TransferFromError = { + 'GenericError' : { 'message' : string, 'error_code' : bigint } + } | + { 'TemporarilyUnavailable' : null } | + { 'InsufficientAllowance' : { 'allowance' : Tokens } } | + { 'BadBurn' : { 'min_burn_amount' : Tokens } } | + { 'Duplicate' : { 'duplicate_of' : BlockIndex } } | + { 'BadFee' : { 'expected_fee' : Tokens } } | + { 'CreatedInFuture' : { 'ledger_time' : bigint } } | + { 'TooOld' : null } | + { 'InsufficientFunds' : { 'balance' : Tokens } }; +export type TransferFromResult = { 'Ok' : BlockIndex } | + { 'Err' : TransferFromError }; +export type TransferResult = { 'Ok' : BlockIndex } | + { 'Err' : TransferError }; +export type TxIndex = bigint; +export interface UpgradeArgs { + 'token_symbol' : [] | [string], + 'transfer_fee' : [] | [bigint], + 'metadata' : [] | [Array<[string, MetadataValue]>], + 'maximum_number_of_accounts' : [] | [bigint], + 'accounts_overflow_trim_quantity' : [] | [bigint], + 'change_fee_collector' : [] | [ChangeFeeCollector], + 'max_memo_length' : [] | [number], + 'token_name' : [] | [string], + 'feature_flags' : [] | [FeatureFlags], +} +export type Value = { 'Int' : bigint } | + { 'Map' : Map } | + { 'Nat' : bigint } | + { 'Nat64' : bigint } | + { 'Blob' : Uint8Array | number[] } | + { 'Text' : string } | + { 'Array' : Array }; +export interface _SERVICE { + 'get_blocks' : ActorMethod<[GetBlocksArgs], GetBlocksResponse>, + 'get_data_certificate' : ActorMethod<[], DataCertificate>, + 'get_transactions' : ActorMethod< + [GetTransactionsRequest], + GetTransactionsResponse + >, + 'icrc1_balance_of' : ActorMethod<[Account], Tokens>, + 'icrc1_decimals' : ActorMethod<[], number>, + 'icrc1_fee' : ActorMethod<[], Tokens>, + 'icrc1_metadata' : ActorMethod<[], Array<[string, MetadataValue]>>, + 'icrc1_minting_account' : ActorMethod<[], [] | [Account]>, + 'icrc1_name' : ActorMethod<[], string>, + 'icrc1_supported_standards' : ActorMethod<[], Array>, + 'icrc1_symbol' : ActorMethod<[], string>, + 'icrc1_total_supply' : ActorMethod<[], Tokens>, + 'icrc1_transfer' : ActorMethod<[TransferArg], TransferResult>, + 'icrc2_allowance' : ActorMethod<[AllowanceArgs], Allowance>, + 'icrc2_approve' : ActorMethod<[ApproveArgs], ApproveResult>, + 'icrc2_transfer_from' : ActorMethod<[TransferFromArgs], TransferFromResult>, +} +export declare const idlFactory: IDL.InterfaceFactory; +export declare const init: (args: { IDL: typeof IDL }) => IDL.Type[]; diff --git a/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.js b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.js new file mode 100644 index 000000000..d5c422e15 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_ledger/icrc1_ledger_canister.did.js @@ -0,0 +1,342 @@ +export const idlFactory = ({ IDL }) => { + const Value = IDL.Rec(); + const MetadataValue = IDL.Variant({ + 'Int' : IDL.Int, + 'Nat' : IDL.Nat, + 'Blob' : IDL.Vec(IDL.Nat8), + 'Text' : IDL.Text, + }); + const Subaccount = IDL.Vec(IDL.Nat8); + const Account = IDL.Record({ + 'owner' : IDL.Principal, + 'subaccount' : IDL.Opt(Subaccount), + }); + const ChangeFeeCollector = IDL.Variant({ + 'SetTo' : Account, + 'Unset' : IDL.Null, + }); + const FeatureFlags = IDL.Record({ 'icrc2' : IDL.Bool }); + const UpgradeArgs = IDL.Record({ + 'token_symbol' : IDL.Opt(IDL.Text), + 'transfer_fee' : IDL.Opt(IDL.Nat), + 'metadata' : IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, MetadataValue))), + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'change_fee_collector' : IDL.Opt(ChangeFeeCollector), + 'max_memo_length' : IDL.Opt(IDL.Nat16), + 'token_name' : IDL.Opt(IDL.Text), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const InitArgs = IDL.Record({ + 'decimals' : IDL.Opt(IDL.Nat8), + 'token_symbol' : IDL.Text, + 'transfer_fee' : IDL.Nat, + 'metadata' : IDL.Vec(IDL.Tuple(IDL.Text, MetadataValue)), + 'minting_account' : Account, + 'initial_balances' : IDL.Vec(IDL.Tuple(Account, IDL.Nat)), + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'fee_collector_account' : IDL.Opt(Account), + 'archive_options' : IDL.Record({ + 'num_blocks_to_archive' : IDL.Nat64, + 'max_transactions_per_response' : IDL.Opt(IDL.Nat64), + 'trigger_threshold' : IDL.Nat64, + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'cycles_for_archive_creation' : IDL.Opt(IDL.Nat64), + 'node_max_memory_size_bytes' : IDL.Opt(IDL.Nat64), + 'controller_id' : IDL.Principal, + }), + 'max_memo_length' : IDL.Opt(IDL.Nat16), + 'token_name' : IDL.Text, + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const LedgerArg = IDL.Variant({ + 'Upgrade' : IDL.Opt(UpgradeArgs), + 'Init' : InitArgs, + }); + const BlockIndex = IDL.Nat; + const GetBlocksArgs = IDL.Record({ + 'start' : BlockIndex, + 'length' : IDL.Nat, + }); + const Map = IDL.Vec(IDL.Tuple(IDL.Text, Value)); + Value.fill( + IDL.Variant({ + 'Int' : IDL.Int, + 'Map' : Map, + 'Nat' : IDL.Nat, + 'Nat64' : IDL.Nat64, + 'Blob' : IDL.Vec(IDL.Nat8), + 'Text' : IDL.Text, + 'Array' : IDL.Vec(Value), + }) + ); + const Block = Value; + const BlockRange = IDL.Record({ 'blocks' : IDL.Vec(Block) }); + const QueryBlockArchiveFn = IDL.Func( + [GetBlocksArgs], + [BlockRange], + ['query'], + ); + const GetBlocksResponse = IDL.Record({ + 'certificate' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'first_index' : BlockIndex, + 'blocks' : IDL.Vec(Block), + 'chain_length' : IDL.Nat64, + 'archived_blocks' : IDL.Vec( + IDL.Record({ + 'callback' : QueryBlockArchiveFn, + 'start' : BlockIndex, + 'length' : IDL.Nat, + }) + ), + }); + const DataCertificate = IDL.Record({ + 'certificate' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'hash_tree' : IDL.Vec(IDL.Nat8), + }); + const TxIndex = IDL.Nat; + const GetTransactionsRequest = IDL.Record({ + 'start' : TxIndex, + 'length' : IDL.Nat, + }); + const Burn = IDL.Record({ + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'spender' : IDL.Opt(Account), + }); + const Mint = IDL.Record({ + 'to' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + }); + const Approve = IDL.Record({ + 'fee' : IDL.Opt(IDL.Nat), + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'expected_allowance' : IDL.Opt(IDL.Nat), + 'expires_at' : IDL.Opt(IDL.Nat64), + 'spender' : Account, + }); + const Transfer = IDL.Record({ + 'to' : Account, + 'fee' : IDL.Opt(IDL.Nat), + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'spender' : IDL.Opt(Account), + }); + const Transaction = IDL.Record({ + 'burn' : IDL.Opt(Burn), + 'kind' : IDL.Text, + 'mint' : IDL.Opt(Mint), + 'approve' : IDL.Opt(Approve), + 'timestamp' : IDL.Nat64, + 'transfer' : IDL.Opt(Transfer), + }); + const TransactionRange = IDL.Record({ + 'transactions' : IDL.Vec(Transaction), + }); + const QueryArchiveFn = IDL.Func( + [GetTransactionsRequest], + [TransactionRange], + ['query'], + ); + const GetTransactionsResponse = IDL.Record({ + 'first_index' : TxIndex, + 'log_length' : IDL.Nat, + 'transactions' : IDL.Vec(Transaction), + 'archived_transactions' : IDL.Vec( + IDL.Record({ + 'callback' : QueryArchiveFn, + 'start' : TxIndex, + 'length' : IDL.Nat, + }) + ), + }); + const Tokens = IDL.Nat; + const StandardRecord = IDL.Record({ 'url' : IDL.Text, 'name' : IDL.Text }); + const Timestamp = IDL.Nat64; + const TransferArg = IDL.Record({ + 'to' : Account, + 'fee' : IDL.Opt(Tokens), + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'from_subaccount' : IDL.Opt(Subaccount), + 'created_at_time' : IDL.Opt(Timestamp), + 'amount' : Tokens, + }); + const TransferError = IDL.Variant({ + 'GenericError' : IDL.Record({ + 'message' : IDL.Text, + 'error_code' : IDL.Nat, + }), + 'TemporarilyUnavailable' : IDL.Null, + 'BadBurn' : IDL.Record({ 'min_burn_amount' : Tokens }), + 'Duplicate' : IDL.Record({ 'duplicate_of' : BlockIndex }), + 'BadFee' : IDL.Record({ 'expected_fee' : Tokens }), + 'CreatedInFuture' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'TooOld' : IDL.Null, + 'InsufficientFunds' : IDL.Record({ 'balance' : Tokens }), + }); + const TransferResult = IDL.Variant({ + 'Ok' : BlockIndex, + 'Err' : TransferError, + }); + const AllowanceArgs = IDL.Record({ + 'account' : Account, + 'spender' : Account, + }); + const Allowance = IDL.Record({ + 'allowance' : IDL.Nat, + 'expires_at' : IDL.Opt(IDL.Nat64), + }); + const ApproveArgs = IDL.Record({ + 'fee' : IDL.Opt(IDL.Nat), + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'from_subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(IDL.Nat64), + 'amount' : IDL.Nat, + 'expected_allowance' : IDL.Opt(IDL.Nat), + 'expires_at' : IDL.Opt(IDL.Nat64), + 'spender' : Account, + }); + const ApproveError = IDL.Variant({ + 'GenericError' : IDL.Record({ + 'message' : IDL.Text, + 'error_code' : IDL.Nat, + }), + 'TemporarilyUnavailable' : IDL.Null, + 'Duplicate' : IDL.Record({ 'duplicate_of' : IDL.Nat }), + 'BadFee' : IDL.Record({ 'expected_fee' : IDL.Nat }), + 'AllowanceChanged' : IDL.Record({ 'current_allowance' : IDL.Nat }), + 'CreatedInFuture' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'TooOld' : IDL.Null, + 'Expired' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'InsufficientFunds' : IDL.Record({ 'balance' : IDL.Nat }), + }); + const ApproveResult = IDL.Variant({ 'Ok' : IDL.Nat, 'Err' : ApproveError }); + const TransferFromArgs = IDL.Record({ + 'to' : Account, + 'fee' : IDL.Opt(Tokens), + 'spender_subaccount' : IDL.Opt(Subaccount), + 'from' : Account, + 'memo' : IDL.Opt(IDL.Vec(IDL.Nat8)), + 'created_at_time' : IDL.Opt(Timestamp), + 'amount' : Tokens, + }); + const TransferFromError = IDL.Variant({ + 'GenericError' : IDL.Record({ + 'message' : IDL.Text, + 'error_code' : IDL.Nat, + }), + 'TemporarilyUnavailable' : IDL.Null, + 'InsufficientAllowance' : IDL.Record({ 'allowance' : Tokens }), + 'BadBurn' : IDL.Record({ 'min_burn_amount' : Tokens }), + 'Duplicate' : IDL.Record({ 'duplicate_of' : BlockIndex }), + 'BadFee' : IDL.Record({ 'expected_fee' : Tokens }), + 'CreatedInFuture' : IDL.Record({ 'ledger_time' : IDL.Nat64 }), + 'TooOld' : IDL.Null, + 'InsufficientFunds' : IDL.Record({ 'balance' : Tokens }), + }); + const TransferFromResult = IDL.Variant({ + 'Ok' : BlockIndex, + 'Err' : TransferFromError, + }); + return IDL.Service({ + 'get_blocks' : IDL.Func([GetBlocksArgs], [GetBlocksResponse], ['query']), + 'get_data_certificate' : IDL.Func([], [DataCertificate], ['query']), + 'get_transactions' : IDL.Func( + [GetTransactionsRequest], + [GetTransactionsResponse], + ['query'], + ), + 'icrc1_balance_of' : IDL.Func([Account], [Tokens], ['query']), + 'icrc1_decimals' : IDL.Func([], [IDL.Nat8], ['query']), + 'icrc1_fee' : IDL.Func([], [Tokens], ['query']), + 'icrc1_metadata' : IDL.Func( + [], + [IDL.Vec(IDL.Tuple(IDL.Text, MetadataValue))], + ['query'], + ), + 'icrc1_minting_account' : IDL.Func([], [IDL.Opt(Account)], ['query']), + 'icrc1_name' : IDL.Func([], [IDL.Text], ['query']), + 'icrc1_supported_standards' : IDL.Func( + [], + [IDL.Vec(StandardRecord)], + ['query'], + ), + 'icrc1_symbol' : IDL.Func([], [IDL.Text], ['query']), + 'icrc1_total_supply' : IDL.Func([], [Tokens], ['query']), + 'icrc1_transfer' : IDL.Func([TransferArg], [TransferResult], []), + 'icrc2_allowance' : IDL.Func([AllowanceArgs], [Allowance], ['query']), + 'icrc2_approve' : IDL.Func([ApproveArgs], [ApproveResult], []), + 'icrc2_transfer_from' : IDL.Func( + [TransferFromArgs], + [TransferFromResult], + [], + ), + }); +}; +export const init = ({ IDL }) => { + const MetadataValue = IDL.Variant({ + 'Int' : IDL.Int, + 'Nat' : IDL.Nat, + 'Blob' : IDL.Vec(IDL.Nat8), + 'Text' : IDL.Text, + }); + const Subaccount = IDL.Vec(IDL.Nat8); + const Account = IDL.Record({ + 'owner' : IDL.Principal, + 'subaccount' : IDL.Opt(Subaccount), + }); + const ChangeFeeCollector = IDL.Variant({ + 'SetTo' : Account, + 'Unset' : IDL.Null, + }); + const FeatureFlags = IDL.Record({ 'icrc2' : IDL.Bool }); + const UpgradeArgs = IDL.Record({ + 'token_symbol' : IDL.Opt(IDL.Text), + 'transfer_fee' : IDL.Opt(IDL.Nat), + 'metadata' : IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, MetadataValue))), + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'change_fee_collector' : IDL.Opt(ChangeFeeCollector), + 'max_memo_length' : IDL.Opt(IDL.Nat16), + 'token_name' : IDL.Opt(IDL.Text), + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const InitArgs = IDL.Record({ + 'decimals' : IDL.Opt(IDL.Nat8), + 'token_symbol' : IDL.Text, + 'transfer_fee' : IDL.Nat, + 'metadata' : IDL.Vec(IDL.Tuple(IDL.Text, MetadataValue)), + 'minting_account' : Account, + 'initial_balances' : IDL.Vec(IDL.Tuple(Account, IDL.Nat)), + 'maximum_number_of_accounts' : IDL.Opt(IDL.Nat64), + 'accounts_overflow_trim_quantity' : IDL.Opt(IDL.Nat64), + 'fee_collector_account' : IDL.Opt(Account), + 'archive_options' : IDL.Record({ + 'num_blocks_to_archive' : IDL.Nat64, + 'max_transactions_per_response' : IDL.Opt(IDL.Nat64), + 'trigger_threshold' : IDL.Nat64, + 'max_message_size_bytes' : IDL.Opt(IDL.Nat64), + 'cycles_for_archive_creation' : IDL.Opt(IDL.Nat64), + 'node_max_memory_size_bytes' : IDL.Opt(IDL.Nat64), + 'controller_id' : IDL.Principal, + }), + 'max_memo_length' : IDL.Opt(IDL.Nat16), + 'token_name' : IDL.Text, + 'feature_flags' : IDL.Opt(FeatureFlags), + }); + const LedgerArg = IDL.Variant({ + 'Upgrade' : IDL.Opt(UpgradeArgs), + 'Init' : InitArgs, + }); + return [LedgerArg]; +}; diff --git a/apps/wallet/src/generated/icrc1_ledger/index.d.ts b/apps/wallet/src/generated/icrc1_ledger/index.d.ts new file mode 100644 index 000000000..bff346fcc --- /dev/null +++ b/apps/wallet/src/generated/icrc1_ledger/index.d.ts @@ -0,0 +1,50 @@ +import type { + ActorSubclass, + HttpAgentOptions, + ActorConfig, + Agent, +} from "@dfinity/agent"; +import type { Principal } from "@dfinity/principal"; +import type { IDL } from "@dfinity/candid"; + +import { _SERVICE } from './icrc1_ledger_canister.did'; + +export declare const idlFactory: IDL.InterfaceFactory; +export declare const canisterId: string; + +export declare interface CreateActorOptions { + /** + * @see {@link Agent} + */ + agent?: Agent; + /** + * @see {@link HttpAgentOptions} + */ + agentOptions?: HttpAgentOptions; + /** + * @see {@link ActorConfig} + */ + actorOptions?: ActorConfig; +} + +/** + * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister. + * @constructs {@link ActorSubClass} + * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to + * @param {CreateActorOptions} options - see {@link CreateActorOptions} + * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions + * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent + * @see {@link HttpAgentOptions} + * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor + * @see {@link ActorConfig} + */ +export declare const createActor: ( + canisterId: string | Principal, + options?: CreateActorOptions +) => ActorSubclass<_SERVICE>; + +/** + * Intialized Actor using default settings, ready to talk to a canister using its candid interface + * @constructs {@link ActorSubClass} + */ +export declare const icrc1_ledger_canister: ActorSubclass<_SERVICE>; diff --git a/apps/wallet/src/generated/icrc1_ledger/index.js b/apps/wallet/src/generated/icrc1_ledger/index.js new file mode 100644 index 000000000..a5df8d522 --- /dev/null +++ b/apps/wallet/src/generated/icrc1_ledger/index.js @@ -0,0 +1,40 @@ +import { Actor, HttpAgent } from "@dfinity/agent"; + +// Imports and re-exports candid interface +import { idlFactory } from "./icrc1_ledger_canister.did.js"; +export { idlFactory } from "./icrc1_ledger_canister.did.js"; + +/* CANISTER_ID is replaced by webpack based on node environment + * Note: canister environment variable will be standardized as + * process.env.CANISTER_ID_ + * beginning in dfx 0.15.0 + */ +export const canisterId = + process.env.CANISTER_ID_ICRC1_LEDGER_CANISTER; + +export const createActor = (canisterId, options = {}) => { + const agent = options.agent || new HttpAgent({ ...options.agentOptions }); + + if (options.agent && options.agentOptions) { + console.warn( + "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent." + ); + } + + // Fetch root key for certificate validation during development + if (process.env.DFX_NETWORK !== "ic") { + agent.fetchRootKey().catch((err) => { + console.warn( + "Unable to fetch root key. Check to ensure that your local replica is running" + ); + console.error(err); + }); + } + + // Creates an actor with using the candid interface and the HttpAgent + return Actor.createActor(idlFactory, { + agent, + canisterId, + ...options.actorOptions, + }); +}; diff --git a/apps/wallet/src/generated/station/station.did b/apps/wallet/src/generated/station/station.did index a2fbdbd4f..ad4c9c2d4 100644 --- a/apps/wallet/src/generated/station/station.did +++ b/apps/wallet/src/generated/station/station.did @@ -59,6 +59,9 @@ type RequestSpecifier = variant { EditUserGroup : ResourceIds; RemoveUserGroup : ResourceIds; ManageSystemInfo; + AddAsset; + EditAsset : ResourceIds; + RemoveAsset : ResourceIds; }; // A record type that can be used to represent a percentage of users that are required to approve a rule. @@ -322,6 +325,10 @@ type RequestApproval = record { type TransferOperationInput = record { // The account id to use for the transaction. from_account_id : UUID; + // The asset id to transfer. + from_asset_id : UUID; + // The standard to use for the transfer. + with_standard : text; // The amount to transfer. amount : nat; // The destination address of the transaction (e.g. "1BvBMSE..."). @@ -342,6 +349,8 @@ type TransferOperationInput = record { type TransferOperation = record { // The account to use for the transaction. from_account : opt Account; + // The asset to use for the transaction. + from_asset : Asset; // The network to use for the transaction. network : Network; // The input to the request to transfer funds. @@ -352,12 +361,27 @@ type TransferOperation = record { fee : opt nat; }; +// Mutate the list of assets. +type ChangeAssets = variant { + // Replace all current assets with the specified list. + ReplaceWith : record { + assets : vec UUID; + }; + // Change the list of assets by adding and removing assets. + Change : record { + add_assets : vec UUID; + remove_assets : vec UUID; + }; +}; + // Input type for editing an account through a request. type EditAccountOperationInput = record { // The account id that will be edited. account_id : UUID; // A friendly name for the account (e.g. "My Account"). name : opt text; + // Mutate the list of assets. + change_assets : opt ChangeAssets; // Who can read the account information. read_permission : opt Allow; // Who can request configuration changes to the account. @@ -379,10 +403,8 @@ type EditAccountOperation = record { type AddAccountOperationInput = record { // A friendly name for the account (e.g. "My Account"). name : text; - // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; - // The asset standard for this account (e.g. `native`, `erc20`, etc.). - standard : text; + // The assets to add to the account. + assets : vec UUID; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; // Who can read the account information. @@ -417,6 +439,8 @@ type AddAddressBookEntryOperationInput = record { address_owner : text; // The actual address. address : text; + // The format of the address, eg. icp_account_identifier + address_format : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // Metadata associated with the address book entry (e.g. `{"kyc": "true"}`). @@ -922,6 +946,12 @@ type RequestOperation = variant { RemoveRequestPolicy : RemoveRequestPolicyOperation; // An operation for managing system info. ManageSystemInfo : ManageSystemInfoOperation; + // An operation for adding a new asset. + AddAsset : AddAssetOperation; + // An operation for editing an existing asset. + EditAsset : EditAssetOperation; + // An operation for removing an existing asset. + RemoveAsset : RemoveAssetOperation; }; type RequestOperationInput = variant { @@ -971,6 +1001,12 @@ type RequestOperationInput = variant { RemoveRequestPolicy : RemoveRequestPolicyOperationInput; // An operation for managing system info. ManageSystemInfo : ManageSystemInfoOperationInput; + // An operation for adding a new asset. + AddAsset : AddAssetOperationInput; + // An operation for editing an existing asset. + EditAsset : EditAssetOperationInput; + // An operation for removing an existing asset. + RemoveAsset : RemoveAssetOperationInput; }; type RequestOperationType = variant { @@ -1020,6 +1056,12 @@ type RequestOperationType = variant { RemoveRequestPolicy; // And operation for managing system info. ManageSystemInfo; + // An operation for adding a new asset. + AddAsset; + // An operation for editing an existing asset. + EditAsset; + // An operation for removing an existing asset. + RemoveAsset; }; // The schedule for executing a transaction of a given transfer. @@ -1170,6 +1212,12 @@ type ListRequestsOperationType = variant { ManageSystemInfo; // An operation for setting disaster recovery config. SetDisasterRecovery; + // An operation for adding an asset. + AddAsset; + // An operation for editing an asset. + EditAsset; + // An operation for removing an asset. + RemoveAsset; }; // The direction to use for sorting. @@ -1549,21 +1597,15 @@ type AccountCallerPrivileges = record { type Account = record { // The internal account id. id : UUID; - // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; - // The asset symbol, e.g. "ICP" or "BTC". - symbol : AssetSymbol; - // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string - // with spaces replaced with underscores. - standard : text; - // The address of the account (e.g. "0x1234"). - address : text; - // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). - decimals : nat32; + + // The list of assets supported by this account. + assets : vec AccountAsset; + + // The list of addresses associated with the account. + addresses : vec AccountAddress; + // A friendly name for the account. name : text; - // Account balance when available. - balance : opt AccountBalanceInfo; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; // The transfer approval policy for the account. @@ -1578,6 +1620,25 @@ type Account = record { last_modification_timestamp : TimestampRFC3339; }; +// The seed used to derive the addresses of the account. +type AccountSeed = blob; + +// Record type to describe an address of an account. +type AccountAddress = record { + // The address. + address : text; + // The format of the address, eg. icp_account_identifier. + format : text; +}; + +// Record type to describe an asset of an account. +type AccountAsset = record { + // The asset id. + asset_id : UUID; + // The balance of the asset. + balance : opt AccountBalance; +}; + // Input type for getting a account. type GetAccountInput = record { // The account id to retrieve. @@ -1600,12 +1661,19 @@ type GetAccountResult = variant { type AccountBalance = record { // The account id. account_id : UUID; + // The asset id. + asset_id : UUID; // The balance of the account. balance : nat; // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). decimals : nat32; // The time at which the balance was last updated. last_update_timestamp : TimestampRFC3339; + // The state of balance query: + // - `fresh`: The balance was recently updated and is considered fresh. + // - `stale`: The balance may be out of date. + // - `stale_refreshing`: The balance may be out of date but it is being refreshed in the background. + query_state : text; }; // Input type for getting a account balance. @@ -1619,7 +1687,7 @@ type FetchAccountBalancesResult = variant { // The result data for a successful execution. Ok : record { // The account balance that was retrieved. - balances : vec AccountBalance; + balances : vec opt AccountBalance; }; // The error that occurred (e.g. the user does not have the necessary permissions). Err : Error; @@ -1652,6 +1720,8 @@ type AddressBookEntry = record { address_owner : text; // The actual address. address : text; + // The address format (e.g. "icp_account_identifier"). + address_format : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // Metadata associated with the address book entry (e.g. `{"kyc": "true"}`). @@ -1691,6 +1761,8 @@ type ListAddressBookEntriesInput = record { blockchain : opt text; // The labels to search for, if provided only address book entries with the given labels will be returned. labels : opt vec text; + // The address formats to search for. + address_formats : opt vec text; // The pagination parameters. paginate : opt PaginationInput; }; @@ -1723,19 +1795,41 @@ type AssetMetadata = record { // A record type that can be used to represent an asset in the station. type Asset = record { + // The internal asset id. + id : UUID; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string // with spaces replaced with underscores. - standard : text; + standards : vec text; // The asset symbol, e.g. "ICP" or "BTC". symbol : AssetSymbol; // The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) name : text; - // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`), - // also, in the case of non-native assets, it can contain other required - // information (e.g. `{"address": "0x1234"}`). + // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). metadata : vec AssetMetadata; + // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). + decimals : nat32; +}; + +// Describes a standard suported by a blockchain. +type StandardData = record { + // The standard name. + standard : text; + // Required metadata fields for the standard (e.g. `["ledger_canister_id"]`). + required_metadata_fields : vec text; + // Supported operations for the standard (e.g. `["transfer", "list_transfers", "balance"]`). + supported_operations : vec text; + // Supported address formats of the standard. + supported_address_formats : vec text; +}; + +// Describes a blockchain and its standards supported by the station. +type SupportedBlockchain = record { + // The blockchain name. + blockchain : text; + // The supported standards for the blockchain. + supported_standards : vec StandardData; }; // A record type that is used to show the current capabilities of the station. @@ -1746,6 +1840,8 @@ type Capabilities = record { version : text; // The list of supported assets. supported_assets : vec Asset; + // The list of supported blockchains and standards. + supported_blockchains : vec SupportedBlockchain; }; // Result type for getting the current config. @@ -2014,6 +2110,7 @@ type Resource = variant { System : SystemResourceAction; User : UserResourceAction; UserGroup : ResourceAction; + Asset : ResourceAction; }; // A record type that can be used to represent the caller privileges for a given permission. @@ -2174,6 +2271,122 @@ type ListRequestPoliciesResult = variant { Err : Error; }; +type AddAssetOperation = record { + // The result of adding an asset. + asset : opt Asset; + // The input to the request to add an asset. + input : AddAssetOperationInput; +}; + +// The input type for adding an asset. +type AddAssetOperationInput = record { + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : text; + // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string + // with spaces replaced with underscores. + standards : vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : AssetSymbol; + // The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) + name : text; + // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). + metadata : vec AssetMetadata; + // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). + decimals : nat32; +}; + +type EditAssetOperation = record { + // The input to the request to edit an asset. + input : EditAssetOperationInput; +}; + +// The input type for editing an asset. +type EditAssetOperationInput = record { + // The asset id to edit. + asset_id : UUID; + // The name of the asset. + name : opt text; + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : opt text; + // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string + // with spaces replaced with underscores. + standards : opt vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : opt AssetSymbol; + // The metadata to change. + change_metadata : opt ChangeMetadata; +}; + +// Type for instructions to update the address book entry's metadata. +type ChangeMetadata = variant { + // Replace all existing metadata by the specified metadata. + ReplaceAllBy : vec AssetMetadata; + // Override values of existing metadata with the specified keys + // and add new metadata if no metadata can be found with the specified keys. + OverrideSpecifiedBy : vec AssetMetadata; + // Remove metadata with the specified keys. + RemoveKeys : vec text; +}; + +type RemoveAssetOperation = record { + // The input to the request to remove an asset. + input : RemoveAssetOperationInput; +}; + +// The input type for removing an asset. +type RemoveAssetOperationInput = record { + // The asset id to remove. + asset_id : UUID; +}; + +// The input type for listing assets. +type ListAssetsInput = record { + // The pagination parameters. + paginate : opt PaginationInput; +}; + +// The result type for listing assets. +type ListAssetsResult = variant { + // The result data for a successful execution. + Ok : record { + // The list of assets. + assets : vec Asset; + // The offset to use for the next page. + next_offset : opt nat64; + // The total number of assets. + total : nat64; + // The caller privileges for the assets. + privileges : vec AssetCallerPrivileges; + }; + // The error that occurred (e.g. the user does not have the necessary permissions). + Err : Error; +}; + +// The input type for getting an asset. +type GetAssetInput = record { + // The asset id to retrieve. + asset_id : UUID; +}; + +// The result type for getting an asset. +type GetAssetResult = variant { + // The result data for a successful execution. + Ok : record { + // The asset that was retrieved. + asset : Asset; + // The caller privileges for the asset. + privileges : AssetCallerPrivileges; + }; + // The error that occurred (e.g. the user does not have the necessary permissions). + Err : Error; +}; + +type AssetCallerPrivileges = record { + id : UUID; + can_edit : bool; + can_delete : bool; +}; + // The top level privileges that the user has when making calls to the canister. type UserPrivilege = variant { Capabilities; @@ -2195,6 +2408,8 @@ type UserPrivilege = variant { CreateExternalCanister; ListExternalCanisters; CallAnyExternalCanister; + ListAssets; + AddAsset; }; type MeResult = variant { @@ -2230,13 +2445,31 @@ type InitAccountInput = record { // A friendly name for the account (e.g. "My Account"). name : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; + seed : AccountSeed; // The asset standard for this account (e.g. `native`, `erc20`, etc.). - standard : text; + assets : vec UUID; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; }; +// The initial assets to create when initializing the canister for the first time, e.g., after disaster recovery. +type InitAssetInput = record { + // The UUID of the asset, if not provided a new UUID will be generated. + id : UUID; + // The name of the asset. + name : text; + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : text; + // The standards this asset supports. + standards : vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : text; + // The number of decimals used to format the asset balance. + decimals : nat32; + // Metadata associated with the asset. + metadata : vec AssetMetadata; +}; + // The init configuration for the canister. // // Only used when installing the canister for the first time. @@ -2253,6 +2486,8 @@ type SystemInit = record { fallback_controller : opt principal; // Optional initial accounts to create. accounts : opt vec InitAccountInput; + // Optional initial assets to create. + assets : opt vec InitAssetInput; }; // The upgrade configuration for the canister. @@ -2766,4 +3001,8 @@ service : (opt SystemInstall) -> { http_request : (HttpRequest) -> (HttpResponse) query; // Internal endpoint used by the upgrader canister to notify the station about a failed station upgrade request. notify_failed_station_upgrade : (NotifyFailedStationUpgradeInput) -> (NotifyFailedStationUpgradeResult); + // Get an asset by id. + get_asset : (input : GetAssetInput) -> (GetAssetResult) query; + // List all assets that the caller has access to. + list_assets : (input : ListAssetsInput) -> (ListAssetsResult) query; }; diff --git a/apps/wallet/src/generated/station/station.did.d.ts b/apps/wallet/src/generated/station/station.did.d.ts index 4655876e1..6d5d1b6f9 100644 --- a/apps/wallet/src/generated/station/station.did.d.ts +++ b/apps/wallet/src/generated/station/station.did.d.ts @@ -5,22 +5,25 @@ import type { IDL } from '@dfinity/candid'; export interface Account { 'id' : UUID, 'configs_request_policy' : [] | [RequestPolicyRule], - 'decimals' : number, - 'balance' : [] | [AccountBalanceInfo], 'metadata' : Array, 'name' : string, - 'blockchain' : string, - 'address' : string, + 'assets' : Array, + 'addresses' : Array, 'transfer_request_policy' : [] | [RequestPolicyRule], 'last_modification_timestamp' : TimestampRFC3339, - 'standard' : string, - 'symbol' : AssetSymbol, +} +export interface AccountAddress { 'address' : string, 'format' : string } +export interface AccountAsset { + 'balance' : [] | [AccountBalance], + 'asset_id' : UUID, } export interface AccountBalance { 'account_id' : UUID, 'decimals' : number, 'balance' : bigint, 'last_update_timestamp' : TimestampRFC3339, + 'query_state' : string, + 'asset_id' : UUID, } export interface AccountBalanceInfo { 'decimals' : number, @@ -38,6 +41,7 @@ export type AccountResourceAction = { 'List' : null } | { 'Create' : null } | { 'Transfer' : ResourceId } | { 'Update' : ResourceId }; +export type AccountSeed = Uint8Array | number[]; export interface AddAccountOperation { 'account' : [] | [Account], 'input' : AddAccountOperationInput, @@ -48,10 +52,9 @@ export interface AddAccountOperationInput { 'configs_permission' : Allow, 'metadata' : Array, 'name' : string, - 'blockchain' : string, + 'assets' : Array, 'transfer_request_policy' : [] | [RequestPolicyRule], 'transfer_permission' : Allow, - 'standard' : string, } export interface AddAddressBookEntryOperation { 'address_book_entry' : [] | [AddressBookEntry], @@ -62,8 +65,21 @@ export interface AddAddressBookEntryOperationInput { 'labels' : Array, 'blockchain' : string, 'address' : string, + 'address_format' : string, 'address_owner' : string, } +export interface AddAssetOperation { + 'asset' : [] | [Asset], + 'input' : AddAssetOperationInput, +} +export interface AddAssetOperationInput { + 'decimals' : number, + 'standards' : Array, + 'metadata' : Array, + 'name' : string, + 'blockchain' : string, + 'symbol' : AssetSymbol, +} export interface AddRequestPolicyOperation { 'input' : AddRequestPolicyOperationInput, 'policy_id' : [] | [UUID], @@ -94,6 +110,7 @@ export interface AddressBookEntry { 'blockchain' : string, 'address' : string, 'last_modification_timestamp' : string, + 'address_format' : string, 'address_owner' : string, } export interface AddressBookEntryCallerPrivileges { @@ -109,12 +126,19 @@ export interface Allow { 'users' : Array, } export interface Asset { + 'id' : UUID, + 'decimals' : number, + 'standards' : Array, 'metadata' : Array, 'name' : string, 'blockchain' : string, - 'standard' : string, 'symbol' : AssetSymbol, } +export interface AssetCallerPrivileges { + 'id' : UUID, + 'can_delete' : boolean, + 'can_edit' : boolean, +} export interface AssetMetadata { 'key' : string, 'value' : string } export type AssetSymbol = string; export type AuthScope = { 'Authenticated' : null } | @@ -185,6 +209,7 @@ export interface Capabilities { 'name' : string, 'version' : string, 'supported_assets' : Array, + 'supported_blockchains' : Array, } export type CapabilitiesResult = { 'Ok' : { 'capabilities' : Capabilities } } | { 'Err' : Error }; @@ -193,6 +218,8 @@ export type ChangeAddressBookMetadata = { } | { 'RemoveKeys' : Array } | { 'ReplaceAllBy' : Array }; +export type ChangeAssets = { 'ReplaceWith' : { 'assets' : Array } } | + { 'Change' : { 'add_assets' : Array, 'remove_assets' : Array } }; export type ChangeExternalCanisterMetadata = { 'OverrideSpecifiedBy' : Array } | @@ -211,6 +238,9 @@ export interface ChangeExternalCanisterOperationInput { 'canister_id' : Principal, 'module' : Uint8Array | number[], } +export type ChangeMetadata = { 'OverrideSpecifiedBy' : Array } | + { 'RemoveKeys' : Array } | + { 'ReplaceAllBy' : Array }; export type ConfigureExternalCanisterOperation = ConfigureExternalCanisterOperationInput; export interface ConfigureExternalCanisterOperationInput { 'kind' : ConfigureExternalCanisterOperationKind, @@ -311,6 +341,7 @@ export interface EditAccountOperationInput { 'read_permission' : [] | [Allow], 'configs_permission' : [] | [Allow], 'name' : [] | [string], + 'change_assets' : [] | [ChangeAssets], 'transfer_request_policy' : [] | [RequestPolicyRuleInput], 'transfer_permission' : [] | [Allow], } @@ -323,6 +354,15 @@ export interface EditAddressBookEntryOperationInput { 'address_book_entry_id' : UUID, 'address_owner' : [] | [string], } +export interface EditAssetOperation { 'input' : EditAssetOperationInput } +export interface EditAssetOperationInput { + 'standards' : [] | [Array], + 'name' : [] | [string], + 'blockchain' : [] | [string], + 'change_metadata' : [] | [ChangeMetadata], + 'asset_id' : UUID, + 'symbol' : [] | [AssetSymbol], +} export interface EditPermissionOperation { 'input' : EditPermissionOperationInput, } @@ -525,7 +565,7 @@ export type ExternalCanisterState = { 'Active' : null } | { 'Archived' : null }; export interface FetchAccountBalancesInput { 'account_ids' : Array } export type FetchAccountBalancesResult = { - 'Ok' : { 'balances' : Array } + 'Ok' : { 'balances' : Array<[] | [AccountBalance]> } } | { 'Err' : Error }; export type FundExternalCanisterOperation = FundExternalCanisterOperationInput; @@ -550,6 +590,11 @@ export type GetAddressBookEntryResult = { } } | { 'Err' : Error }; +export interface GetAssetInput { 'asset_id' : UUID } +export type GetAssetResult = { + 'Ok' : { 'privileges' : AssetCallerPrivileges, 'asset' : Asset } + } | + { 'Err' : Error }; export interface GetExternalCanisterFiltersInput { 'with_labels' : [] | [boolean], 'with_name' : [] | [{ 'prefix' : [] | [string] }], @@ -638,8 +683,17 @@ export interface InitAccountInput { 'id' : [] | [UUID], 'metadata' : Array, 'name' : string, + 'assets' : Array, + 'seed' : AccountSeed, +} +export interface InitAssetInput { + 'id' : UUID, + 'decimals' : number, + 'standards' : Array, + 'metadata' : Array, + 'name' : string, 'blockchain' : string, - 'standard' : string, + 'symbol' : string, } export interface ListAccountTransfersInput { 'account_id' : UUID, @@ -666,6 +720,7 @@ export type ListAccountsResult = { { 'Err' : Error }; export interface ListAddressBookEntriesInput { 'ids' : [] | [Array], + 'address_formats' : [] | [Array], 'labels' : [] | [Array], 'blockchain' : [] | [string], 'addresses' : [] | [Array], @@ -680,6 +735,16 @@ export type ListAddressBookEntriesResult = { } } | { 'Err' : Error }; +export interface ListAssetsInput { 'paginate' : [] | [PaginationInput] } +export type ListAssetsResult = { + 'Ok' : { + 'total' : bigint, + 'privileges' : Array, + 'assets' : Array, + 'next_offset' : [] | [bigint], + } + } | + { 'Err' : Error }; export interface ListExternalCanistersInput { 'sort_by' : [] | [ListExternalCanistersSortInput], 'states' : [] | [Array], @@ -746,15 +811,18 @@ export interface ListRequestsInput { 'only_approvable' : boolean, 'created_from_dt' : [] | [TimestampRFC3339], } -export type ListRequestsOperationType = { 'AddUserGroup' : null } | +export type ListRequestsOperationType = { 'RemoveAsset' : null } | + { 'AddUserGroup' : null } | { 'EditPermission' : null } | { 'ConfigureExternalCanister' : [] | [Principal] } | { 'ChangeExternalCanister' : [] | [Principal] } | { 'AddUser' : null } | + { 'EditAsset' : null } | { 'EditUserGroup' : null } | { 'SetDisasterRecovery' : null } | { 'EditRequestPolicy' : null } | { 'RemoveRequestPolicy' : null } | + { 'AddAsset' : null } | { 'SystemUpgrade' : null } | { 'RemoveAddressBookEntry' : null } | { 'CreateExternalCanister' : null } | @@ -894,6 +962,8 @@ export interface RemoveAddressBookEntryOperation { export interface RemoveAddressBookEntryOperationInput { 'address_book_entry_id' : UUID, } +export interface RemoveAssetOperation { 'input' : RemoveAssetOperationInput } +export interface RemoveAssetOperationInput { 'asset_id' : UUID } export interface RemoveRequestPolicyOperation { 'input' : RemoveRequestPolicyOperationInput, } @@ -940,15 +1010,18 @@ export interface RequestEvaluationResult { } export type RequestExecutionSchedule = { 'Immediate' : null } | { 'Scheduled' : { 'execution_time' : TimestampRFC3339 } }; -export type RequestOperation = { 'AddUserGroup' : AddUserGroupOperation } | +export type RequestOperation = { 'RemoveAsset' : RemoveAssetOperation } | + { 'AddUserGroup' : AddUserGroupOperation } | { 'EditPermission' : EditPermissionOperation } | { 'ConfigureExternalCanister' : ConfigureExternalCanisterOperation } | { 'ChangeExternalCanister' : ChangeExternalCanisterOperation } | { 'AddUser' : AddUserOperation } | + { 'EditAsset' : EditAssetOperation } | { 'EditUserGroup' : EditUserGroupOperation } | { 'SetDisasterRecovery' : SetDisasterRecoveryOperation } | { 'EditRequestPolicy' : EditRequestPolicyOperation } | { 'RemoveRequestPolicy' : RemoveRequestPolicyOperation } | + { 'AddAsset' : AddAssetOperation } | { 'SystemUpgrade' : SystemUpgradeOperation } | { 'RemoveAddressBookEntry' : RemoveAddressBookEntryOperation } | { 'CreateExternalCanister' : CreateExternalCanisterOperation } | @@ -964,16 +1037,19 @@ export type RequestOperation = { 'AddUserGroup' : AddUserGroupOperation } | { 'CallExternalCanister' : CallExternalCanisterOperation } | { 'AddAccount' : AddAccountOperation }; export type RequestOperationInput = { - 'AddUserGroup' : AddUserGroupOperationInput + 'RemoveAsset' : RemoveAssetOperationInput } | + { 'AddUserGroup' : AddUserGroupOperationInput } | { 'EditPermission' : EditPermissionOperationInput } | { 'ConfigureExternalCanister' : ConfigureExternalCanisterOperationInput } | { 'ChangeExternalCanister' : ChangeExternalCanisterOperationInput } | { 'AddUser' : AddUserOperationInput } | + { 'EditAsset' : EditAssetOperationInput } | { 'EditUserGroup' : EditUserGroupOperationInput } | { 'SetDisasterRecovery' : SetDisasterRecoveryOperationInput } | { 'EditRequestPolicy' : EditRequestPolicyOperationInput } | { 'RemoveRequestPolicy' : RemoveRequestPolicyOperationInput } | + { 'AddAsset' : AddAssetOperationInput } | { 'SystemUpgrade' : SystemUpgradeOperationInput } | { 'RemoveAddressBookEntry' : RemoveAddressBookEntryOperationInput } | { 'CreateExternalCanister' : CreateExternalCanisterOperationInput } | @@ -988,15 +1064,18 @@ export type RequestOperationInput = { { 'RemoveUserGroup' : RemoveUserGroupOperationInput } | { 'CallExternalCanister' : CallExternalCanisterOperationInput } | { 'AddAccount' : AddAccountOperationInput }; -export type RequestOperationType = { 'AddUserGroup' : null } | +export type RequestOperationType = { 'RemoveAsset' : null } | + { 'AddUserGroup' : null } | { 'EditPermission' : null } | { 'ConfigureExternalCanister' : null } | { 'ChangeExternalCanister' : null } | { 'AddUser' : null } | + { 'EditAsset' : null } | { 'EditUserGroup' : null } | { 'SetDisasterRecovery' : null } | { 'EditRequestPolicy' : null } | { 'RemoveRequestPolicy' : null } | + { 'AddAsset' : null } | { 'SystemUpgrade' : null } | { 'RemoveAddressBookEntry' : null } | { 'CreateExternalCanister' : null } | @@ -1037,14 +1116,17 @@ export interface RequestPolicyRuleResult { } export type RequestResourceAction = { 'List' : null } | { 'Read' : ResourceId }; -export type RequestSpecifier = { 'AddUserGroup' : null } | +export type RequestSpecifier = { 'RemoveAsset' : ResourceIds } | + { 'AddUserGroup' : null } | { 'EditPermission' : ResourceSpecifier } | { 'ChangeExternalCanister' : ExternalCanisterId } | { 'AddUser' : null } | + { 'EditAsset' : ResourceIds } | { 'EditUserGroup' : ResourceIds } | { 'SetDisasterRecovery' : null } | { 'EditRequestPolicy' : ResourceIds } | { 'RemoveRequestPolicy' : ResourceIds } | + { 'AddAsset' : null } | { 'SystemUpgrade' : null } | { 'RemoveAddressBookEntry' : ResourceIds } | { 'CreateExternalCanister' : null } | @@ -1082,6 +1164,7 @@ export type Resource = { 'Request' : RequestResourceAction } | { 'ExternalCanister' : ExternalCanisterResourceAction } | { 'Account' : AccountResourceAction } | { 'AddressBook' : ResourceAction } | + { 'Asset' : ResourceAction } | { 'UserGroup' : ResourceAction } | { 'Permission' : PermissionResourceAction } | { 'RequestPolicy' : ResourceAction }; @@ -1105,6 +1188,12 @@ export interface SetDisasterRecoveryOperationInput { export type Sha256Hash = string; export type SortByDirection = { 'Asc' : null } | { 'Desc' : null }; +export interface StandardData { + 'supported_operations' : Array, + 'supported_address_formats' : Array, + 'required_metadata_fields' : Array, + 'standard' : string, +} export interface SubmitRequestApprovalInput { 'request_id' : UUID, 'decision' : RequestApprovalStatus, @@ -1121,6 +1210,10 @@ export type SubmitRequestApprovalResult = { export interface SubnetFilter { 'subnet_type' : [] | [string] } export type SubnetSelection = { 'Filter' : SubnetFilter } | { 'Subnet' : { 'subnet' : Principal } }; +export interface SupportedBlockchain { + 'blockchain' : string, + 'supported_standards' : Array, +} export interface SystemInfo { 'disaster_recovery' : [] | [DisasterRecovery], 'name' : string, @@ -1135,6 +1228,7 @@ export type SystemInfoResult = { 'Ok' : { 'system' : SystemInfo } } | { 'Err' : Error }; export interface SystemInit { 'name' : string, + 'assets' : [] | [Array], 'fallback_controller' : [] | [Principal], 'upgrader' : SystemUpgraderInput, 'accounts' : [] | [Array], @@ -1186,6 +1280,7 @@ export interface TransferListItem { export interface TransferMetadata { 'key' : string, 'value' : string } export interface TransferOperation { 'fee' : [] | [bigint], + 'from_asset' : Asset, 'network' : Network, 'transfer_id' : [] | [UUID], 'from_account' : [] | [Account], @@ -1194,10 +1289,12 @@ export interface TransferOperation { export interface TransferOperationInput { 'to' : string, 'fee' : [] | [bigint], + 'with_standard' : string, 'from_account_id' : UUID, 'metadata' : Array, 'network' : [] | [Network], 'amount' : bigint, + 'from_asset_id' : UUID, } export type TransferStatus = { 'Failed' : { 'reason' : string } } | { 'Processing' : { 'started_at' : TimestampRFC3339 } } | @@ -1235,8 +1332,10 @@ export type UserPrivilege = { 'AddUserGroup' : null } | { 'ListUserGroups' : null } | { 'AddUser' : null } | { 'ListUsers' : null } | + { 'AddAsset' : null } | { 'SystemUpgrade' : null } | { 'CreateExternalCanister' : null } | + { 'ListAssets' : null } | { 'ManageSystemInfo' : null } | { 'AddAddressBookEntry' : null } | { 'ListAccounts' : null } | @@ -1278,6 +1377,7 @@ export interface _SERVICE { [GetAddressBookEntryInput], GetAddressBookEntryResult >, + 'get_asset' : ActorMethod<[GetAssetInput], GetAssetResult>, 'get_external_canister' : ActorMethod< [GetExternalCanisterInput], GetExternalCanisterResult @@ -1310,6 +1410,7 @@ export interface _SERVICE { [ListAddressBookEntriesInput], ListAddressBookEntriesResult >, + 'list_assets' : ActorMethod<[ListAssetsInput], ListAssetsResult>, 'list_external_canisters' : ActorMethod< [ListExternalCanistersInput], ListExternalCanistersResult diff --git a/apps/wallet/src/generated/station/station.did.js b/apps/wallet/src/generated/station/station.did.js index 11a797576..be19c7b1f 100644 --- a/apps/wallet/src/generated/station/station.did.js +++ b/apps/wallet/src/generated/station/station.did.js @@ -2,18 +2,29 @@ export const idlFactory = ({ IDL }) => { const RequestPolicyRule = IDL.Rec(); const RequestPolicyRuleResult = IDL.Rec(); const SystemUpgrade = IDL.Record({ 'name' : IDL.Opt(IDL.Text) }); + const UUID = IDL.Text; + const AssetMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); + const InitAssetInput = IDL.Record({ + 'id' : UUID, + 'decimals' : IDL.Nat32, + 'standards' : IDL.Vec(IDL.Text), + 'metadata' : IDL.Vec(AssetMetadata), + 'name' : IDL.Text, + 'blockchain' : IDL.Text, + 'symbol' : IDL.Text, + }); const SystemUpgraderInput = IDL.Variant({ 'Id' : IDL.Principal, 'WasmModule' : IDL.Vec(IDL.Nat8), }); - const UUID = IDL.Text; const AccountMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); + const AccountSeed = IDL.Vec(IDL.Nat8); const InitAccountInput = IDL.Record({ 'id' : IDL.Opt(UUID), 'metadata' : IDL.Vec(AccountMetadata), 'name' : IDL.Text, - 'blockchain' : IDL.Text, - 'standard' : IDL.Text, + 'assets' : IDL.Vec(UUID), + 'seed' : AccountSeed, }); const AdminInitInput = IDL.Record({ 'name' : IDL.Text, @@ -21,6 +32,7 @@ export const idlFactory = ({ IDL }) => { }); const SystemInit = IDL.Record({ 'name' : IDL.Text, + 'assets' : IDL.Opt(IDL.Vec(InitAssetInput)), 'fallback_controller' : IDL.Opt(IDL.Principal), 'upgrader' : SystemUpgraderInput, 'accounts' : IDL.Opt(IDL.Vec(InitAccountInput)), @@ -50,6 +62,10 @@ export const idlFactory = ({ IDL }) => { 'Immediate' : IDL.Null, 'Scheduled' : IDL.Record({ 'execution_time' : TimestampRFC3339 }), }); + const RemoveAssetOperationInput = IDL.Record({ 'asset_id' : UUID }); + const RemoveAssetOperation = IDL.Record({ + 'input' : RemoveAssetOperationInput, + }); const UserGroup = IDL.Record({ 'id' : UUID, 'name' : IDL.Text }); const AddUserGroupOperationInput = IDL.Record({ 'name' : IDL.Text }); const AddUserGroupOperation = IDL.Record({ @@ -131,6 +147,7 @@ export const idlFactory = ({ IDL }) => { 'ExternalCanister' : ExternalCanisterResourceAction, 'Account' : AccountResourceAction, 'AddressBook' : ResourceAction, + 'Asset' : ResourceAction, 'UserGroup' : ResourceAction, 'Permission' : PermissionResourceAction, 'RequestPolicy' : ResourceAction, @@ -333,6 +350,21 @@ export const idlFactory = ({ IDL }) => { 'user' : IDL.Opt(User), 'input' : AddUserOperationInput, }); + const ChangeMetadata = IDL.Variant({ + 'OverrideSpecifiedBy' : IDL.Vec(AssetMetadata), + 'RemoveKeys' : IDL.Vec(IDL.Text), + 'ReplaceAllBy' : IDL.Vec(AssetMetadata), + }); + const AssetSymbol = IDL.Text; + const EditAssetOperationInput = IDL.Record({ + 'standards' : IDL.Opt(IDL.Vec(IDL.Text)), + 'name' : IDL.Opt(IDL.Text), + 'blockchain' : IDL.Opt(IDL.Text), + 'change_metadata' : IDL.Opt(ChangeMetadata), + 'asset_id' : UUID, + 'symbol' : IDL.Opt(AssetSymbol), + }); + const EditAssetOperation = IDL.Record({ 'input' : EditAssetOperationInput }); const EditUserGroupOperationInput = IDL.Record({ 'name' : IDL.Text, 'user_group_id' : UUID, @@ -347,20 +379,23 @@ export const idlFactory = ({ IDL }) => { const SetDisasterRecoveryOperation = IDL.Record({ 'committee' : IDL.Opt(DisasterRecoveryCommittee), }); + const ResourceIds = IDL.Variant({ 'Any' : IDL.Null, 'Ids' : IDL.Vec(UUID) }); const ResourceSpecifier = IDL.Variant({ 'Any' : IDL.Null, 'Resource' : Resource, }); - const ResourceIds = IDL.Variant({ 'Any' : IDL.Null, 'Ids' : IDL.Vec(UUID) }); const RequestSpecifier = IDL.Variant({ + 'RemoveAsset' : ResourceIds, 'AddUserGroup' : IDL.Null, 'EditPermission' : ResourceSpecifier, 'ChangeExternalCanister' : ExternalCanisterId, 'AddUser' : IDL.Null, + 'EditAsset' : ResourceIds, 'EditUserGroup' : ResourceIds, 'SetDisasterRecovery' : IDL.Null, 'EditRequestPolicy' : ResourceIds, 'RemoveRequestPolicy' : ResourceIds, + 'AddAsset' : IDL.Null, 'SystemUpgrade' : IDL.Null, 'RemoveAddressBookEntry' : ResourceIds, 'CreateExternalCanister' : IDL.Null, @@ -388,6 +423,27 @@ export const idlFactory = ({ IDL }) => { const RemoveRequestPolicyOperation = IDL.Record({ 'input' : RemoveRequestPolicyOperationInput, }); + const Asset = IDL.Record({ + 'id' : UUID, + 'decimals' : IDL.Nat32, + 'standards' : IDL.Vec(IDL.Text), + 'metadata' : IDL.Vec(AssetMetadata), + 'name' : IDL.Text, + 'blockchain' : IDL.Text, + 'symbol' : AssetSymbol, + }); + const AddAssetOperationInput = IDL.Record({ + 'decimals' : IDL.Nat32, + 'standards' : IDL.Vec(IDL.Text), + 'metadata' : IDL.Vec(AssetMetadata), + 'name' : IDL.Text, + 'blockchain' : IDL.Text, + 'symbol' : AssetSymbol, + }); + const AddAssetOperation = IDL.Record({ + 'asset' : IDL.Opt(Asset), + 'input' : AddAssetOperationInput, + }); const SystemUpgradeTarget = IDL.Variant({ 'UpgradeUpgrader' : IDL.Null, 'UpgradeStation' : IDL.Null, @@ -489,37 +545,46 @@ export const idlFactory = ({ IDL }) => { }); const NetworkId = IDL.Text; const Network = IDL.Record({ 'id' : NetworkId, 'name' : IDL.Text }); - const AccountBalanceInfo = IDL.Record({ + const AccountBalance = IDL.Record({ + 'account_id' : UUID, 'decimals' : IDL.Nat32, 'balance' : IDL.Nat, 'last_update_timestamp' : TimestampRFC3339, + 'query_state' : IDL.Text, + 'asset_id' : UUID, + }); + const AccountAsset = IDL.Record({ + 'balance' : IDL.Opt(AccountBalance), + 'asset_id' : UUID, + }); + const AccountAddress = IDL.Record({ + 'address' : IDL.Text, + 'format' : IDL.Text, }); - const AssetSymbol = IDL.Text; const Account = IDL.Record({ 'id' : UUID, 'configs_request_policy' : IDL.Opt(RequestPolicyRule), - 'decimals' : IDL.Nat32, - 'balance' : IDL.Opt(AccountBalanceInfo), 'metadata' : IDL.Vec(AccountMetadata), 'name' : IDL.Text, - 'blockchain' : IDL.Text, - 'address' : IDL.Text, + 'assets' : IDL.Vec(AccountAsset), + 'addresses' : IDL.Vec(AccountAddress), 'transfer_request_policy' : IDL.Opt(RequestPolicyRule), 'last_modification_timestamp' : TimestampRFC3339, - 'standard' : IDL.Text, - 'symbol' : AssetSymbol, }); const TransferMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); const TransferOperationInput = IDL.Record({ 'to' : IDL.Text, 'fee' : IDL.Opt(IDL.Nat), + 'with_standard' : IDL.Text, 'from_account_id' : UUID, 'metadata' : IDL.Vec(TransferMetadata), 'network' : IDL.Opt(Network), 'amount' : IDL.Nat, + 'from_asset_id' : UUID, }); const TransferOperation = IDL.Record({ 'fee' : IDL.Opt(IDL.Nat), + 'from_asset' : Asset, 'network' : Network, 'transfer_id' : IDL.Opt(UUID), 'from_account' : IDL.Opt(Account), @@ -529,12 +594,20 @@ export const idlFactory = ({ IDL }) => { 'Set' : RequestPolicyRule, 'Remove' : IDL.Null, }); + const ChangeAssets = IDL.Variant({ + 'ReplaceWith' : IDL.Record({ 'assets' : IDL.Vec(UUID) }), + 'Change' : IDL.Record({ + 'add_assets' : IDL.Vec(UUID), + 'remove_assets' : IDL.Vec(UUID), + }), + }); const EditAccountOperationInput = IDL.Record({ 'account_id' : UUID, 'configs_request_policy' : IDL.Opt(RequestPolicyRuleInput), 'read_permission' : IDL.Opt(Allow), 'configs_permission' : IDL.Opt(Allow), 'name' : IDL.Opt(IDL.Text), + 'change_assets' : IDL.Opt(ChangeAssets), 'transfer_request_policy' : IDL.Opt(RequestPolicyRuleInput), 'transfer_permission' : IDL.Opt(Allow), }); @@ -548,6 +621,7 @@ export const idlFactory = ({ IDL }) => { 'blockchain' : IDL.Text, 'address' : IDL.Text, 'last_modification_timestamp' : IDL.Text, + 'address_format' : IDL.Text, 'address_owner' : IDL.Text, }); const AddAddressBookEntryOperationInput = IDL.Record({ @@ -555,6 +629,7 @@ export const idlFactory = ({ IDL }) => { 'labels' : IDL.Vec(IDL.Text), 'blockchain' : IDL.Text, 'address' : IDL.Text, + 'address_format' : IDL.Text, 'address_owner' : IDL.Text, }); const AddAddressBookEntryOperation = IDL.Record({ @@ -588,25 +663,27 @@ export const idlFactory = ({ IDL }) => { 'configs_permission' : Allow, 'metadata' : IDL.Vec(AccountMetadata), 'name' : IDL.Text, - 'blockchain' : IDL.Text, + 'assets' : IDL.Vec(UUID), 'transfer_request_policy' : IDL.Opt(RequestPolicyRule), 'transfer_permission' : Allow, - 'standard' : IDL.Text, }); const AddAccountOperation = IDL.Record({ 'account' : IDL.Opt(Account), 'input' : AddAccountOperationInput, }); const RequestOperation = IDL.Variant({ + 'RemoveAsset' : RemoveAssetOperation, 'AddUserGroup' : AddUserGroupOperation, 'EditPermission' : EditPermissionOperation, 'ConfigureExternalCanister' : ConfigureExternalCanisterOperation, 'ChangeExternalCanister' : ChangeExternalCanisterOperation, 'AddUser' : AddUserOperation, + 'EditAsset' : EditAssetOperation, 'EditUserGroup' : EditUserGroupOperation, 'SetDisasterRecovery' : SetDisasterRecoveryOperation, 'EditRequestPolicy' : EditRequestPolicyOperation, 'RemoveRequestPolicy' : RemoveRequestPolicyOperation, + 'AddAsset' : AddAssetOperation, 'SystemUpgrade' : SystemUpgradeOperation, 'RemoveAddressBookEntry' : RemoveAddressBookEntryOperation, 'CreateExternalCanister' : CreateExternalCanisterOperation, @@ -686,18 +763,21 @@ export const idlFactory = ({ IDL }) => { 'Ok' : CanisterStatusResponse, 'Err' : Error, }); - const AssetMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); - const Asset = IDL.Record({ - 'metadata' : IDL.Vec(AssetMetadata), - 'name' : IDL.Text, - 'blockchain' : IDL.Text, + const StandardData = IDL.Record({ + 'supported_operations' : IDL.Vec(IDL.Text), + 'supported_address_formats' : IDL.Vec(IDL.Text), + 'required_metadata_fields' : IDL.Vec(IDL.Text), 'standard' : IDL.Text, - 'symbol' : AssetSymbol, + }); + const SupportedBlockchain = IDL.Record({ + 'blockchain' : IDL.Text, + 'supported_standards' : IDL.Vec(StandardData), }); const Capabilities = IDL.Record({ 'name' : IDL.Text, 'version' : IDL.Text, 'supported_assets' : IDL.Vec(Asset), + 'supported_blockchains' : IDL.Vec(SupportedBlockchain), }); const CapabilitiesResult = IDL.Variant({ 'Ok' : IDL.Record({ 'capabilities' : Capabilities }), @@ -731,15 +811,18 @@ export const idlFactory = ({ IDL }) => { 'execution_method_cycles' : IDL.Opt(IDL.Nat64), }); const RequestOperationInput = IDL.Variant({ + 'RemoveAsset' : RemoveAssetOperationInput, 'AddUserGroup' : AddUserGroupOperationInput, 'EditPermission' : EditPermissionOperationInput, 'ConfigureExternalCanister' : ConfigureExternalCanisterOperationInput, 'ChangeExternalCanister' : ChangeExternalCanisterOperationInput, 'AddUser' : AddUserOperationInput, + 'EditAsset' : EditAssetOperationInput, 'EditUserGroup' : EditUserGroupOperationInput, 'SetDisasterRecovery' : SetDisasterRecoveryOperationInput, 'EditRequestPolicy' : EditRequestPolicyOperationInput, 'RemoveRequestPolicy' : RemoveRequestPolicyOperationInput, + 'AddAsset' : AddAssetOperationInput, 'SystemUpgrade' : SystemUpgradeOperationInput, 'RemoveAddressBookEntry' : RemoveAddressBookEntryOperationInput, 'CreateExternalCanister' : CreateExternalCanisterOperationInput, @@ -825,14 +908,8 @@ export const idlFactory = ({ IDL }) => { const FetchAccountBalancesInput = IDL.Record({ 'account_ids' : IDL.Vec(UUID), }); - const AccountBalance = IDL.Record({ - 'account_id' : UUID, - 'decimals' : IDL.Nat32, - 'balance' : IDL.Nat, - 'last_update_timestamp' : TimestampRFC3339, - }); const FetchAccountBalancesResult = IDL.Variant({ - 'Ok' : IDL.Record({ 'balances' : IDL.Vec(AccountBalance) }), + 'Ok' : IDL.Record({ 'balances' : IDL.Vec(IDL.Opt(AccountBalance)) }), 'Err' : Error, }); const GetAccountInput = IDL.Record({ 'account_id' : UUID }); @@ -863,6 +940,19 @@ export const idlFactory = ({ IDL }) => { }), 'Err' : Error, }); + const GetAssetInput = IDL.Record({ 'asset_id' : UUID }); + const AssetCallerPrivileges = IDL.Record({ + 'id' : UUID, + 'can_delete' : IDL.Bool, + 'can_edit' : IDL.Bool, + }); + const GetAssetResult = IDL.Variant({ + 'Ok' : IDL.Record({ + 'privileges' : AssetCallerPrivileges, + 'asset' : Asset, + }), + 'Err' : Error, + }); const GetExternalCanisterInput = IDL.Record({ 'canister_id' : IDL.Principal, }); @@ -927,15 +1017,18 @@ export const idlFactory = ({ IDL }) => { 'Err' : Error, }); const ListRequestsOperationType = IDL.Variant({ + 'RemoveAsset' : IDL.Null, 'AddUserGroup' : IDL.Null, 'EditPermission' : IDL.Null, 'ConfigureExternalCanister' : IDL.Opt(IDL.Principal), 'ChangeExternalCanister' : IDL.Opt(IDL.Principal), 'AddUser' : IDL.Null, + 'EditAsset' : IDL.Null, 'EditUserGroup' : IDL.Null, 'SetDisasterRecovery' : IDL.Null, 'EditRequestPolicy' : IDL.Null, 'RemoveRequestPolicy' : IDL.Null, + 'AddAsset' : IDL.Null, 'SystemUpgrade' : IDL.Null, 'RemoveAddressBookEntry' : IDL.Null, 'CreateExternalCanister' : IDL.Null, @@ -1110,6 +1203,7 @@ export const idlFactory = ({ IDL }) => { }); const ListAddressBookEntriesInput = IDL.Record({ 'ids' : IDL.Opt(IDL.Vec(UUID)), + 'address_formats' : IDL.Opt(IDL.Vec(IDL.Text)), 'labels' : IDL.Opt(IDL.Vec(IDL.Text)), 'blockchain' : IDL.Opt(IDL.Text), 'addresses' : IDL.Opt(IDL.Vec(IDL.Text)), @@ -1124,6 +1218,16 @@ export const idlFactory = ({ IDL }) => { }), 'Err' : Error, }); + const ListAssetsInput = IDL.Record({ 'paginate' : IDL.Opt(PaginationInput) }); + const ListAssetsResult = IDL.Variant({ + 'Ok' : IDL.Record({ + 'total' : IDL.Nat64, + 'privileges' : IDL.Vec(AssetCallerPrivileges), + 'assets' : IDL.Vec(Asset), + 'next_offset' : IDL.Opt(IDL.Nat64), + }), + 'Err' : Error, + }); const SortByDirection = IDL.Variant({ 'Asc' : IDL.Null, 'Desc' : IDL.Null }); const ListExternalCanistersSortInput = IDL.Variant({ 'Name' : SortByDirection, @@ -1159,15 +1263,18 @@ export const idlFactory = ({ IDL }) => { 'notification_type' : IDL.Opt(NotificationTypeInput), }); const RequestOperationType = IDL.Variant({ + 'RemoveAsset' : IDL.Null, 'AddUserGroup' : IDL.Null, 'EditPermission' : IDL.Null, 'ConfigureExternalCanister' : IDL.Null, 'ChangeExternalCanister' : IDL.Null, 'AddUser' : IDL.Null, + 'EditAsset' : IDL.Null, 'EditUserGroup' : IDL.Null, 'SetDisasterRecovery' : IDL.Null, 'EditRequestPolicy' : IDL.Null, 'RemoveRequestPolicy' : IDL.Null, + 'AddAsset' : IDL.Null, 'SystemUpgrade' : IDL.Null, 'RemoveAddressBookEntry' : IDL.Null, 'CreateExternalCanister' : IDL.Null, @@ -1327,8 +1434,10 @@ export const idlFactory = ({ IDL }) => { 'ListUserGroups' : IDL.Null, 'AddUser' : IDL.Null, 'ListUsers' : IDL.Null, + 'AddAsset' : IDL.Null, 'SystemUpgrade' : IDL.Null, 'CreateExternalCanister' : IDL.Null, + 'ListAssets' : IDL.Null, 'ManageSystemInfo' : IDL.Null, 'AddAddressBookEntry' : IDL.Null, 'ListAccounts' : IDL.Null, @@ -1416,6 +1525,7 @@ export const idlFactory = ({ IDL }) => { [GetAddressBookEntryResult], ['query'], ), + 'get_asset' : IDL.Func([GetAssetInput], [GetAssetResult], ['query']), 'get_external_canister' : IDL.Func( [GetExternalCanisterInput], [GetExternalCanisterResult], @@ -1470,6 +1580,7 @@ export const idlFactory = ({ IDL }) => { [ListAddressBookEntriesResult], ['query'], ), + 'list_assets' : IDL.Func([ListAssetsInput], [ListAssetsResult], ['query']), 'list_external_canisters' : IDL.Func( [ListExternalCanistersInput], [ListExternalCanistersResult], @@ -1522,18 +1633,29 @@ export const idlFactory = ({ IDL }) => { }; export const init = ({ IDL }) => { const SystemUpgrade = IDL.Record({ 'name' : IDL.Opt(IDL.Text) }); + const UUID = IDL.Text; + const AssetMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); + const InitAssetInput = IDL.Record({ + 'id' : UUID, + 'decimals' : IDL.Nat32, + 'standards' : IDL.Vec(IDL.Text), + 'metadata' : IDL.Vec(AssetMetadata), + 'name' : IDL.Text, + 'blockchain' : IDL.Text, + 'symbol' : IDL.Text, + }); const SystemUpgraderInput = IDL.Variant({ 'Id' : IDL.Principal, 'WasmModule' : IDL.Vec(IDL.Nat8), }); - const UUID = IDL.Text; const AccountMetadata = IDL.Record({ 'key' : IDL.Text, 'value' : IDL.Text }); + const AccountSeed = IDL.Vec(IDL.Nat8); const InitAccountInput = IDL.Record({ 'id' : IDL.Opt(UUID), 'metadata' : IDL.Vec(AccountMetadata), 'name' : IDL.Text, - 'blockchain' : IDL.Text, - 'standard' : IDL.Text, + 'assets' : IDL.Vec(UUID), + 'seed' : AccountSeed, }); const AdminInitInput = IDL.Record({ 'name' : IDL.Text, @@ -1541,6 +1663,7 @@ export const init = ({ IDL }) => { }); const SystemInit = IDL.Record({ 'name' : IDL.Text, + 'assets' : IDL.Opt(IDL.Vec(InitAssetInput)), 'fallback_controller' : IDL.Opt(IDL.Principal), 'upgrader' : SystemUpgraderInput, 'accounts' : IDL.Opt(IDL.Vec(InitAccountInput)), diff --git a/apps/wallet/src/locales/en.locale.ts b/apps/wallet/src/locales/en.locale.ts index 694db6e60..297cd51c1 100644 --- a/apps/wallet/src/locales/en.locale.ts +++ b/apps/wallet/src/locales/en.locale.ts @@ -95,6 +95,7 @@ export default { verify_instructions: 'To verify the update, open the terminal and follow the instructions bellow:', }, + asset: 'Asset', no_data: 'No data available.', no_matching_results: 'No matching results found for `{search}`.', add_new_label: 'Add new label: {label}', @@ -110,7 +111,12 @@ export default { icp: { name: 'Internet Computer', standards: { - native: 'Native', + icp_native: 'ICP (Native)', + icrc1: 'ICRC-1', + }, + formats: { + icp_account_identifier: 'ICP Native', + icrc1_account: 'ICRC-1', }, }, eth: { @@ -169,6 +175,7 @@ export default { system: 'System', transfers: 'Transfers', users: 'Users', + assets: 'Assets', external_canisters: 'Canisters', }, headers: { @@ -265,6 +272,9 @@ export default { editaccount: { title: 'Edit account', request_title: 'Edit account request', + added_assets: 'Added', + removed_assets: 'Removed', + replaced_assets: 'Replaced', }, editaddressbookentry: { title: 'Edit address book entry', @@ -282,6 +292,18 @@ export default { title: 'Manage system info', request_title: 'Manage system info request', }, + addasset: { + title: 'Add asset', + request_title: 'Add asset request', + }, + editasset: { + title: 'Edit asset', + request_title: 'Edit asset request', + }, + removeasset: { + title: 'Remove asset', + request_title: 'Remove asset request', + }, createexternalcanister: { title: 'Create canister', request_title: 'Create canister request', @@ -696,6 +718,7 @@ export default { principal: 'Principal', status: 'Status', transfer: 'Transfer', + transfer_asset: 'Transfer {asset}', invalid: 'Invalid', control_panel: 'Control panel', confirmed: 'Confirmed', @@ -710,6 +733,9 @@ export default { version: 'Version', continue: 'Continue', cycle_obtain_strategy: 'Wallet top-up method', + symbol: 'Symbol', + standards: 'Standards', + assets: 'Assets', }, forms: { create: 'Create', @@ -732,11 +758,15 @@ export default { numberRange: 'This field must be between {min} and {max}.', invalidDecimalPlaces: 'This field must have a maximum of {decimals} decimal places.', isHex: 'This field must be a valid hexadecimal value.', + validAddress: 'This field must be a valid address.', + validSymbol: 'Symbol must be 1-32 alphanumeric characters.', }, }, navigation: { home: 'Home', + dashboard: 'Dashboard', accounts: 'Accounts', + account: 'Account', address_book: 'Address Book', users: 'Users', settings: 'Settings', @@ -750,9 +780,14 @@ export default { transfer_requests: 'Transfer Requests', permissions: 'Permissions', request_policies: 'Request Policies', + assets: 'Assets', external_canisters: 'Canisters', }, pages: { + dashboard: { + title: 'Dashboard', + available_assets: 'Available Assets', + }, accounts: { title: 'Accounts', btn_new_transfer: 'New transfer', @@ -773,6 +808,14 @@ export default { csv_ignored_transfers_hint: 'Transfers with errors will be ignored.', csv_transfer_failed: 'Failed to process transfers, please try again.', csv_download_invalid: 'Download invalid', + add_asset: 'Add asset', + remove_asset: 'Remove asset', + no_assets_to_add: 'No assets available to add.', + remove_asset_confirm: + 'Are you sure you want to remove this asset? Removing the asset does not affect the account balance. Re-adding the asset will restore access to the balance.', + transfers_not_supported: 'Transfers are not supported for this asset.', + add_index_canister_to_see_transactions: + 'Consider adding the index canister to the asset to see transactions.', }, address_book: { title: 'Address Book', @@ -871,6 +914,17 @@ export default { create_label: 'Add Policy', dialog_title: 'Policy', }, + assets: { + title: 'Assets', + btn_new_entry: 'New asset', + no_results_found: 'No assets found.', + error_fetching_assets: 'Error fetching assets, please try again.', + forms: { + ledger_canister_id: 'Ledger Canister ID', + index_canister_id: 'Index Canister ID', + decimals: 'Decimals', + }, + }, not_found: { title: 'Whoops, 404', subtitle: 'The page you were looking for does not exist.', @@ -910,6 +964,7 @@ export default { select_resource: 'Resource Type', resources: { account: 'Account', + asset: 'Asset', user: 'User', usergroup: 'User Group', permission: 'Access Policy', @@ -988,6 +1043,9 @@ export default { setdisasterrecovery: 'Configure disaster recovery', callexternalcanister: 'Call canister', createexternalcanister: 'Create canister', + addasset: 'Add asset', + editasset: 'Edit asset', + removeasset: 'Remove asset', }, }, cycle_obtain_strategies: { diff --git a/apps/wallet/src/locales/fr.locale.ts b/apps/wallet/src/locales/fr.locale.ts index 4dc027894..7a66c2709 100644 --- a/apps/wallet/src/locales/fr.locale.ts +++ b/apps/wallet/src/locales/fr.locale.ts @@ -97,6 +97,7 @@ export default { verify_instructions: 'Pour vérifier la mise à jour, ouvrez le terminal et suivez les instructions ci-dessous:', }, + asset: 'Actif', no_data: 'Pas de données disponibles.', no_matching_results: 'Pas de résultats correspondants trouvés pour `{search}`.', add_new_label: 'Ajouter une nouvelle étiquette: {label}', @@ -120,7 +121,12 @@ export default { icp: { name: 'Internet Computer', standards: { - native: 'Native', + icp_native: 'ICP (Native)', + icrc1: 'ICRC-1', + }, + formats: { + icp_account_identifier: 'ICP Native', + icrc1_account: 'ICRC-1', }, }, eth: { @@ -179,6 +185,7 @@ export default { system: 'Système', transfers: 'Transferts', users: 'Usagers', + assets: 'Actifs', external_canisters: 'Canisters', }, headers: { @@ -275,6 +282,9 @@ export default { editaccount: { title: 'Modifier de modifier un compte', request_title: 'Demande de modifier un compte', + added_assets: 'Ajouté', + removed_assets: 'Supprimé', + replaced_assets: 'Remplacé', }, editaddressbookentry: { title: "Modifier une entrée de carnet d'adresses", @@ -292,6 +302,18 @@ export default { title: 'Gérer les informations système', request_title: 'Demande de gérer les informations système', }, + addasset: { + title: 'Ajouter un actif', + request_title: 'Demande d ajouter un actif', + }, + editasset: { + title: 'Modifier un actif', + request_title: 'Demande de modifier un actif', + }, + removeasset: { + title: 'Supprimer un actif', + request_title: 'Demande de supprimer un actif', + }, createexternalcanister: { title: 'Créer un canister', request_title: 'Demande de création de canister', @@ -704,6 +726,7 @@ export default { principal: 'Principal', status: 'Statut', transfer: 'Transfert', + transfer_asset: 'Transfert {asset}', invalid: 'Invalide', control_panel: 'Paneau de Contrôle', confirmed: 'Confirmé', @@ -718,6 +741,9 @@ export default { version: 'Version', continue: 'Continuer', cycle_obtain_strategy: 'Méthode de recharge du portefeuille', + symbol: 'Symbole', + standards: 'Standards', + assets: 'Actifs', }, forms: { create: 'Créer', @@ -740,11 +766,15 @@ export default { numberRange: 'Le champ doit contenir une valeur valide entre {min} et {max}.', invalidDecimalPlaces: 'Ce champ doit contenir un maximum de {decimals} décimales.', isHex: 'Ce champ doit contenir une valeur hexadécimale valide.', + validAddress: 'Ce champ doit contenir une adresse valide.', + validSymbol: 'Le symbole doit contenir entre 1 et 32 charactères alphanumériques.', }, }, navigation: { home: 'Acceuil', + dashboard: 'Tableau de Bord', accounts: 'Comptes', + account: 'Compte', address_book: "Carnet d'Adresses", users: 'Usagers', settings: 'Settings', @@ -758,9 +788,14 @@ export default { transfer_requests: 'Demandes de Transfert', permissions: "Polices d'Accés", request_policies: "Polices d'Aprobation", + assets: 'Actifs', external_canisters: 'Canisters', }, pages: { + dashboard: { + title: 'Tableau de Bord', + available_assets: 'Actifs Disponibles', + }, accounts: { title: 'Comptes', btn_new_transfer: 'Nouveau Transfert', @@ -783,6 +818,14 @@ export default { csv_ignored_transfers_hint: 'Transfers with errors will be ignored.', csv_transfer_failed: 'Échec de process transfers, veuillez essayer de nouveau.', csv_download_invalid: 'Téléchargement invalide', + add_asset: 'Ajouter un actif', + remove_asset: 'Supprimer un actif', + no_assets_to_add: 'Pas d actifs disponibles à ajouter.', + remove_asset_confirm: + 'Êtes-vous sûr de vouloir supprimer cet actif? Supprimer l actif n affecte pas le solde du compte. Réajouter l actif restaurera l accès au solde.', + transfers_not_supported: 'Les transferts ne sont pas supportés pour cet actif.', + add_index_canister_to_see_transactions: + 'Considérez d ajouter le canister d index à l actif pour voir les transactions.', }, address_book: { title: "Carnet d'Adresses", @@ -884,6 +927,17 @@ export default { create_label: 'Ajouter un police', dialog_title: 'Police', }, + assets: { + title: 'Actifs', + btn_new_asset: 'Nouvel Actif', + no_results_found: 'Pas d actif trouvé.', + error_fetching_assets: 'Erreur lors du chargement des actifs, veuillez essayer de nouveau.', + forms: { + ledger_canister_id: 'ID du Canister Ledger', + index_canister_id: 'ID du Canister Index', + decimals: 'Décimales', + }, + }, not_found: { title: 'Oulala, 404', subtitle: "La page que vous cherchez n'existe pas.", @@ -923,6 +977,7 @@ export default { select_resource: 'Type de Resource', resources: { account: 'Compte', + asset: 'Actif', user: 'Usager', usergroup: "Groupe d'Usagers", permission: "Police d'Accés", @@ -1001,6 +1056,9 @@ export default { setdisasterrecovery: 'Définir la récupération après sinistre', callexternalcanister: 'Appeler un canister', createexternalcanister: 'Créer un canister', + addasset: 'Ajouter un actif', + editasset: 'Modifier un actif', + removeasset: 'Éffacer un actif', }, }, cycle_obtain_strategies: { diff --git a/apps/wallet/src/locales/pt.locale.ts b/apps/wallet/src/locales/pt.locale.ts index 65fd5ce69..5275309ef 100644 --- a/apps/wallet/src/locales/pt.locale.ts +++ b/apps/wallet/src/locales/pt.locale.ts @@ -96,6 +96,7 @@ export default { verify_instructions: 'Para verificar a atualização, abra o terminal e siga as instruções abaixo:', }, + assets: 'Ativos', no_data: 'Nenhum dado disponível.', no_matching_results: 'Nenhum resultado encontrado para `{search}`.', add_new_label: 'Adicionar novo rótulo: {label}', @@ -125,7 +126,12 @@ export default { icp: { name: 'Internet Computer', standards: { - native: 'Nativo', + icp_native: 'ICP (Nativo)', + icrc1: 'ICRC-1', + }, + formats: { + icp_account_identifier: 'ICP Nativo', + icrc1_account: 'ICRC-1', }, }, eth: { @@ -178,6 +184,7 @@ export default { system: 'Sistema', transfers: 'Transferências', users: 'Usuários', + assets: 'Ativos', external_canisters: 'Canisters', }, download: { @@ -274,6 +281,9 @@ export default { editaccount: { title: 'Editar conta', request_title: 'Pedido de alteração de conta', + added_assets: 'Adicionado', + removed_assets: 'Removido', + replaced_assets: 'Substituído', }, editaddressbookentry: { title: 'Editar endereço', @@ -291,6 +301,18 @@ export default { title: 'Gerir informações do sistema', request_title: 'Pedido de alteração de informações do sistema', }, + addasset: { + title: 'Adicionar ativo', + request_title: 'Pedido de adição de ativo', + }, + editasset: { + title: 'Editar ativo', + request_title: 'Pedido de alteração de ativo', + }, + removeasset: { + title: 'Remover ativo', + request_title: 'Pedido de remoção de ativo', + }, createexternalcanister: { title: 'Criar canister', request_title: 'Pedido de criação de canister', @@ -686,6 +708,7 @@ export default { settings: 'Configuraçōes', close: 'Fechar', transfer: 'Transferência', + transfer_asset: 'Transferir {asset}', general: 'Geral', update: 'Atualizar', time: 'Horário', @@ -713,6 +736,9 @@ export default { version: 'Versão', continue: 'Continuar', cycle_obtain_strategy: 'Método de recarga da carteira', + symbol: 'Símbolo', + standards: 'Padrões', + assets: 'Ativos', }, forms: { create: 'Criar', @@ -735,11 +761,15 @@ export default { numberRange: 'Este campo deve estar entre {min} e {max}.', invalidDecimalPlaces: 'Este campo deve ter no máximo {decimals} casas decimais.', isHex: 'Este campo deve conter um valor hexadecimal válido.', + validAddress: 'Este campo deve conter um endereço válido.', + validSymbol: 'O símbolo deve ter de 1 a 32 caracteres alfanuméricos.', }, }, navigation: { home: 'Início', + dashboard: 'Dashboard', accounts: 'Contas', + account: 'Conta', address_book: 'Endereços', users: 'Usuários', settings: 'Configuraçōes', @@ -753,9 +783,14 @@ export default { transfer_requests: 'Pedidos de transferência', permissions: 'Permissões', request_policies: 'Regras de aprovação', + assets: 'Ativos', external_canisters: 'Canisters', }, pages: { + dashboard: { + title: 'Dashboard', + available_assets: 'Ativos disponíveis', + }, accounts: { title: 'Contas', btn_new_transfer: 'Nova transferência', @@ -777,6 +812,14 @@ export default { csv_ignored_transfers_hint: 'Transferências com erros serão ignoradas.', csv_transfer_failed: 'Error ao processar transferências, por favor, tente novamente.', csv_download_invalid: 'Baixar erros', + add_asset: 'Adicionar ativo', + remove_asset: 'Remover ativo', + no_assets_to_add: 'Nenhum ativo disponível para adicionar.', + remove_asset_confirm: + 'Tem a certeza que deseja remover este ativo? Remover o ativo não afeta o saldo da conta. Re-adicionar o ativo restaurará o acesso ao saldo.', + transfers_not_supported: 'As transferências não são suportadas para este ativo.', + add_index_canister_to_see_transactions: + 'Considere adicionar o canister de índice ao ativo para ver as transações.', }, address_book: { title: 'Livro de endereços', @@ -879,6 +922,17 @@ export default { create_label: 'Criar Regra', dialog_title: 'Regra', }, + assets: { + title: 'Ativos', + btn_new_entry: 'Novo ativo', + no_results_found: 'Nenhum ativo encontrado.', + error_fetching_assets: 'Erro ao carregar os ativos, por favor, tente novamente.', + forms: { + ledger_canister_id: 'ID do canister de contabilidade', + index_canister_id: 'ID do canister de índice', + decimals: 'Decimais', + }, + }, not_found: { title: 'Ups, 404', subtitle: 'A página que está a tentar aceder não existe.', @@ -918,6 +972,7 @@ export default { select_resource: 'Selecione o tipo de recurso', resources: { account: 'Conta', + asset: 'Ativo', user: 'Usuário', usergroup: 'Grupo de usuários', permission: 'Regra de acesso', @@ -995,6 +1050,9 @@ export default { fundexternalcanister: 'Financiar canister', setdisasterrecovery: 'Recuperação de sistema', callexternalcanister: 'Interagir com canister', + addasset: 'Adicionar ativo', + editasset: 'Editar ativo', + removeasset: 'Remover ativo', }, }, cycle_obtain_strategies: { diff --git a/apps/wallet/src/mappers/permissions.mapper.ts b/apps/wallet/src/mappers/permissions.mapper.ts index 179b53104..bde3bbb88 100644 --- a/apps/wallet/src/mappers/permissions.mapper.ts +++ b/apps/wallet/src/mappers/permissions.mapper.ts @@ -43,6 +43,10 @@ export const fromResourceToResourceEnum = (resource: Resource): ResourceTypeEnum return ResourceTypeEnum.Notification; } + if (variantIs(resource, 'Asset')) { + return ResourceTypeEnum.Asset; + } + return unreachable(resource); }; diff --git a/apps/wallet/src/mappers/request-specifiers.mapper.ts b/apps/wallet/src/mappers/request-specifiers.mapper.ts index 2cb33965f..189b629bf 100644 --- a/apps/wallet/src/mappers/request-specifiers.mapper.ts +++ b/apps/wallet/src/mappers/request-specifiers.mapper.ts @@ -91,6 +91,18 @@ export const mapRequestSpecifierToEnum = (specifier: RequestSpecifier): RequestS return RequestSpecifierEnum.SetDisasterRecovery; } + if (variantIs(specifier, 'AddAsset')) { + return RequestSpecifierEnum.AddAsset; + } + + if (variantIs(specifier, 'EditAsset')) { + return RequestSpecifierEnum.EditAsset; + } + + if (variantIs(specifier, 'RemoveAsset')) { + return RequestSpecifierEnum.RemoveAsset; + } + return unreachable(specifier); }; diff --git a/apps/wallet/src/mappers/requests.mapper.ts b/apps/wallet/src/mappers/requests.mapper.ts index cd7c4f9d0..1bba7ffcd 100644 --- a/apps/wallet/src/mappers/requests.mapper.ts +++ b/apps/wallet/src/mappers/requests.mapper.ts @@ -13,6 +13,7 @@ import { RequestWithDetails, } from '~/types/requests.types'; import { RequestOperationEnum, RequestStatusEnum } from '~/types/station.types'; +import { detectAddressFormat } from '~/utils/asset.utils'; import { formatBalance, stringify, unreachable, variantIs } from '~/utils/helper.utils'; export const mapRequestsOperationTypeToGroup = ( @@ -79,6 +80,14 @@ export const mapRequestsOperationTypeToGroup = ( return ListRequestsOperationTypeGroup.ExternalCanister; } + if ( + variantIs(operationType, 'AddAsset') || + variantIs(operationType, 'EditAsset') || + variantIs(operationType, 'RemoveAsset') + ) { + return ListRequestsOperationTypeGroup.Asset; + } + return unreachable(operationType); }; @@ -241,6 +250,15 @@ export const mapRequestOperationToTypeEnum = ( if (variantIs(operation, 'SetDisasterRecovery')) { return RequestOperationEnum.SetDisasterRecovery; } + if (variantIs(operation, 'AddAsset')) { + return RequestOperationEnum.AddAsset; + } + if (variantIs(operation, 'EditAsset')) { + return RequestOperationEnum.EditAsset; + } + if (variantIs(operation, 'RemoveAsset')) { + return RequestOperationEnum.RemoveAsset; + } return unreachable(operation); }; @@ -310,6 +328,12 @@ export const mapRequestOperationToListRequestsOperationType = ( return { FundExternalCanister: [] }; } else if (variantIs(requestOperation, 'SetDisasterRecovery')) { return { SetDisasterRecovery: null }; + } else if (variantIs(requestOperation, 'AddAsset')) { + return { AddAsset: null }; + } else if (variantIs(requestOperation, 'EditAsset')) { + return { EditAsset: null }; + } else if (variantIs(requestOperation, 'RemoveAsset')) { + return { RemoveAsset: null }; } else { return unreachable(requestOperation); } @@ -421,10 +445,9 @@ const mapRequestToAccountCsvRow = (request: Request): CsvRow => { return { account_id: request.operation.AddAccount.account?.[0]?.id ?? '', account_name: request.operation.AddAccount.input.name, - blockchain: request.operation.AddAccount.input.blockchain, details: stringify({ metadata: request.operation.AddAccount.input.metadata, - standard: request.operation.AddAccount.input.standard, + assets: request.operation.AddAccount.input.assets, configs_request_policy: request.operation.AddAccount.input.configs_request_policy, transfer_request_policy: request.operation.AddAccount.input.transfer_request_policy, }), @@ -480,18 +503,31 @@ const mapRequestToTransferCsvRow = (request: Request): CsvRow => { if (variantIs(request.operation, 'Transfer') && request.operation.Transfer.from_account?.[0]) { const account = request.operation.Transfer.from_account[0]; + const asset = request.operation.Transfer.from_asset; + + // to determine the `from address` we find a matching address to the format of the `to address` + const maybeToAddressFormat = detectAddressFormat( + asset.blockchain, + request.operation.Transfer.input.to, + ); + + const fallbackAddress = account.addresses[0]?.address ?? '-'; + + const fromAddress = maybeToAddressFormat + ? (account.addresses.find(accountAddress => accountAddress.format === maybeToAddressFormat) + ?.address ?? fallbackAddress) + : fallbackAddress; + return { from_account: account.name, - from_account_address: account.address, + from_account_address: fromAddress, + from_asset: `${asset.name} (${asset.blockchain} / ${asset.name})`, to: request.operation.Transfer.input.to, amount: - formatBalance(request.operation.Transfer.input.amount, account.decimals) + - ' ' + - account.symbol, + formatBalance(request.operation.Transfer.input.amount, asset.decimals) + ' ' + asset.symbol, fee: request.operation.Transfer.fee[0] - ? formatBalance(request.operation.Transfer.fee[0], account.decimals) + ' ' + account.symbol + ? formatBalance(request.operation.Transfer.fee[0], asset.decimals) + ' ' + asset.symbol : '', - // comment: request.summary[0] ?? '', comment: request.summary[0] ?? '', }; } diff --git a/apps/wallet/src/pages/AccountAssetPage.vue b/apps/wallet/src/pages/AccountAssetPage.vue new file mode 100644 index 000000000..b03cc78c2 --- /dev/null +++ b/apps/wallet/src/pages/AccountAssetPage.vue @@ -0,0 +1,515 @@ + + + diff --git a/apps/wallet/src/pages/AccountPage.vue b/apps/wallet/src/pages/AccountPage.vue index f5a3a2a7f..07530ac85 100644 --- a/apps/wallet/src/pages/AccountPage.vue +++ b/apps/wallet/src/pages/AccountPage.vue @@ -43,25 +43,11 @@ {{ $t('terms.settings') }} - - @@ -72,7 +58,7 @@ class="mb-4" :see-all-link="{ name: Routes.Requests, - query: { group_by: RequestDomains.Transfers }, + query: { group_by: RequestDomains.Accounts }, }" :types="[{ Transfer: [account.id] }]" hide-not-found @@ -84,71 +70,68 @@ class="d-flex flex-column-reverse flex-md-row ga-4 px-0 align-md-start pt-0" >
- - - - - - {{ $t('terms.time') }} - - {{ $t('app.destination_source') }} - - - {{ $t('app.amount_token', { token: account.symbol }) }} - - - - - - {{ $t('app.no_transfers') }} - - - - {{ - `${transfer.created_at?.toLocaleDateString()} ${transfer.created_at?.toLocaleTimeString()}` - }} - - -
- - -
- - - {{ formatBalance(transfer.amount, account.decimals) }} - - - - - - -
-
+ + + + + + + + + +
diff --git a/apps/wallet/src/pages/DashboardPage.vue b/apps/wallet/src/pages/DashboardPage.vue new file mode 100644 index 000000000..015aa4fb4 --- /dev/null +++ b/apps/wallet/src/pages/DashboardPage.vue @@ -0,0 +1,219 @@ + + + diff --git a/apps/wallet/src/plugins/navigation.plugin.ts b/apps/wallet/src/plugins/navigation.plugin.ts index 2781f9e04..77149231a 100644 --- a/apps/wallet/src/plugins/navigation.plugin.ts +++ b/apps/wallet/src/plugins/navigation.plugin.ts @@ -4,6 +4,7 @@ import { mdiDatabase, mdiFormatListText, mdiPlusBox, + mdiViewDashboard, mdiWalletBifold, } from '@mdi/js'; import { App, Ref, computed, ref, watch } from 'vue'; @@ -38,6 +39,19 @@ const sections = (): NavigationSections => ({ }, icon: mdiPlusBox, }, + { + name: 'dashboard', + localeKey: 'navigation.dashboard', + action: { + type: NavigationActionType.To, + handle: route => (route.params.locale ? `/${route.params.locale}/dashboard` : '/dashboard'), + }, + auth: { + type: NavigastionAuthType.Route, + route: Routes.Dashboard, + }, + icon: mdiViewDashboard, + }, { name: 'accounts', localeKey: 'navigation.accounts', @@ -177,6 +191,19 @@ const sections = (): NavigationSections => ({ route: Routes.Requests, }, }, + { + name: 'assets', + localeKey: 'navigation.assets', + action: { + type: NavigationActionType.To, + handle: route => + route.params.locale ? `/${route.params.locale}/settings/assets` : '/settings/assets', + }, + auth: { + type: NavigastionAuthType.Route, + route: Routes.Assets, + }, + }, ], }, ], diff --git a/apps/wallet/src/plugins/router.plugin.ts b/apps/wallet/src/plugins/router.plugin.ts index 03b65b087..02679d596 100644 --- a/apps/wallet/src/plugins/router.plugin.ts +++ b/apps/wallet/src/plugins/router.plugin.ts @@ -18,6 +18,7 @@ import { hasRequiredPrivilege, hasRequiredSession } from '~/utils/auth.utils'; import { i18n, i18nRouteGuard } from './i18n.plugin'; import { initStateGuard } from './pinia.plugin'; import { services } from './services.plugin'; +import DashboardPage from '~/pages/DashboardPage.vue'; export const redirectToKey = 'redirectTo'; @@ -53,6 +54,18 @@ const router = createRouter({ }, }, }, + { + path: 'dashboard', + name: Routes.Dashboard, + component: DashboardPage, + meta: { + auth: { + check: { + session: RequiredSessionState.ConnectedToStation, + }, + }, + }, + }, { path: 'accounts', component: RouterView, @@ -87,16 +100,7 @@ const router = createRouter({ }, { path: ':id', - name: Routes.Account, - component: () => import('~/pages/AccountPage.vue'), - props: () => { - return { - breadcrumbs: [ - { title: i18n.global.t('navigation.home'), to: { name: defaultHomeRoute } }, - { title: i18n.global.t('navigation.accounts'), to: { name: Routes.Accounts } }, - ], - }; - }, + component: RouterView, meta: { auth: { check: { @@ -105,6 +109,44 @@ const router = createRouter({ }, }, }, + children: [ + { + path: '', + name: Routes.Account, + component: () => import('~/pages/AccountPage.vue'), + props: () => { + return { + breadcrumbs: [ + { title: i18n.global.t('navigation.home'), to: { name: defaultHomeRoute } }, + { + title: i18n.global.t('navigation.accounts'), + to: { name: Routes.Accounts }, + }, + ], + }; + }, + }, + { + path: ':assetId', + name: Routes.AccountAsset, + component: () => import('~/pages/AccountAssetPage.vue'), + props: params => { + return { + breadcrumbs: [ + { title: i18n.global.t('navigation.home'), to: { name: defaultHomeRoute } }, + { + title: i18n.global.t('navigation.accounts'), + to: { name: Routes.Accounts }, + }, + { + title: i18n.global.t('navigation.account'), + to: { name: Routes.Account, params: { id: params.params.id } }, + }, + ], + }; + }, + }, + ], }, ], }, @@ -395,6 +437,29 @@ const router = createRouter({ }, }, }, + { + path: 'assets', + name: Routes.Assets, + component: () => import('~/pages/AssetsPage.vue'), + props: () => { + return { + title: i18n.global.t('pages.assets.title'), + breadcrumbs: [ + { title: i18n.global.t('navigation.home'), to: { name: defaultHomeRoute } }, + { title: i18n.global.t('navigation.settings') }, + { title: i18n.global.t('navigation.assets') }, + ], + }; + }, + meta: { + auth: { + check: { + session: RequiredSessionState.ConnectedToStation, + privileges: [Privilege.ListAssets], + }, + }, + }, + }, ], }, { diff --git a/apps/wallet/src/services/chains/ic-native-api.service.ts b/apps/wallet/src/services/chains/ic-native-api.service.ts index e79d3daa0..c08924b95 100644 --- a/apps/wallet/src/services/chains/ic-native-api.service.ts +++ b/apps/wallet/src/services/chains/ic-native-api.service.ts @@ -1,43 +1,68 @@ import { Actor, ActorSubclass, HttpAgent } from '@dfinity/agent'; -import { appInitConfig } from '~/configs/init.config'; import { icAgent } from '~/core/ic-agent.core'; -import { idlFactory } from '~/generated/icp_index'; -import { _SERVICE } from '~/generated/icp_index/icp_index.did'; -import { Account } from '~/generated/station/station.did'; -import { AccountIncomingTransfer, ChainApi, FetchTransfersInput } from '~/types/chain.types'; +import { idlFactory as IcpIndexIdlFactory } from '~/generated/icp_index'; +import { idlFactory as IcpLedgerIdlFactory } from '~/generated/icp_ledger'; +import { _SERVICE as IcpIndexService } from '~/generated/icp_index/icp_index.did'; +import { _SERVICE as IcpLedgerService } from '~/generated/icp_ledger/icp_ledger.did'; +import { + AccountIncomingTransfer, + ChainApi, + ChainApiCapability, + FetchTransfersInput, +} from '~/types/chain.types'; import { nanoToJsDate } from '~/utils/date.utils'; -import { isValidSha256 } from '~/utils/helper.utils'; +import { hexStringToUint8Array, isValidSha256 } from '~/utils/helper.utils'; export class ICNativeApi implements ChainApi { - private actor: ActorSubclass<_SERVICE>; + private indexActor: ActorSubclass | null = null; + private ledgerActor: ActorSubclass; static PAGE_SIZE = BigInt(100); constructor( - private readonly account: Account, + private readonly address: string, + private readonly ledgerCanisterId: string, + private readonly indexCanisterId: string | undefined, agent: HttpAgent = icAgent.get(), ) { - this.actor = Actor.createActor<_SERVICE>(idlFactory, { + if (this.indexCanisterId) { + this.indexActor = Actor.createActor(IcpIndexIdlFactory, { + agent, + canisterId: this.indexCanisterId, + }); + } + + this.ledgerActor = Actor.createActor(IcpLedgerIdlFactory, { agent, - canisterId: appInitConfig.canisters.icpIndex, + canisterId: this.ledgerCanisterId, }); } - isValidAddress(address: string): boolean { + static isValidAddress(address: string): boolean { return isValidSha256(address); } + isValidAddress(address: string): boolean { + return ICNativeApi.isValidAddress(address); + } + async fetchBalance(): Promise { - const balance = await this.actor.get_account_identifier_balance(this.account.address); + const balance = await this.ledgerActor.account_balance({ + account: hexStringToUint8Array(this.address), + }); - return balance; + return balance.e8s; } async fetchTransfers( input: FetchTransfersInput, startBlockId?: bigint, ): Promise { - const result = await this.actor.get_account_identifier_transactions({ - account_identifier: this.account.address, + if (!this.indexActor) { + throw new Error('Cannot fetch balance without index canister id.'); + } + + const result = await this.indexActor.get_account_identifier_transactions({ + account_identifier: this.address, start: startBlockId ? [startBlockId] : [], max_results: ICNativeApi.PAGE_SIZE, }); @@ -95,4 +120,11 @@ export class ICNativeApi implements ChainApi { return transfers; } + + getCapabilities(): ChainApiCapability[] { + return [ + ChainApiCapability.Balance, // balance always available due to ledger canister id mandatory + ...(this.indexActor ? [ChainApiCapability.Transfers] : []), + ]; + } } diff --git a/apps/wallet/src/services/chains/icrc1-api.service.ts b/apps/wallet/src/services/chains/icrc1-api.service.ts new file mode 100644 index 000000000..59cca23e6 --- /dev/null +++ b/apps/wallet/src/services/chains/icrc1-api.service.ts @@ -0,0 +1,144 @@ +import { Actor, ActorSubclass, HttpAgent } from '@dfinity/agent'; +import { icAgent } from '~/core/ic-agent.core'; +import { + AccountIncomingTransfer, + ChainApi, + ChainApiCapability, + FetchTransfersInput, +} from '~/types/chain.types'; +import { nanoToJsDate } from '~/utils/date.utils'; +import { decodeIcrcAccount, encodeIcrcAccount } from '@dfinity/ledger-icrc'; +import { Account } from '~/generated/icp_index/icp_index.did'; +import { idlFactory as Icrc1IndexIdlFactory } from '~/generated/icrc1_index'; +import { idlFactory as Icrc1LedgerIdlFactory } from '~/generated/icrc1_ledger'; +import { _SERVICE as Icrc1IndexService } from '~/generated/icrc1_index/icrc1_index_canister.did'; +import { _SERVICE as Icrc1LedgerService } from '~/generated/icrc1_ledger/icrc1_ledger_canister.did'; + +export class ICRC1Api implements ChainApi { + private indexActor: ActorSubclass | null = null; + private ledgerActor: ActorSubclass; + static PAGE_SIZE = BigInt(100); + + private account: Account; + + constructor( + address: string, + private readonly ledgerCanisterId: string, + private readonly indexCanisterId: string | undefined, + agent: HttpAgent = icAgent.get(), + ) { + const icrc1Account = decodeIcrcAccount(address); + + this.account = { + owner: icrc1Account.owner, + subaccount: icrc1Account.subaccount ? [icrc1Account.subaccount] : [], + }; + + if (this.indexCanisterId) { + this.indexActor = Actor.createActor(Icrc1IndexIdlFactory, { + agent, + canisterId: this.indexCanisterId, + }); + } + + this.ledgerActor = Actor.createActor(Icrc1LedgerIdlFactory, { + agent, + canisterId: this.ledgerCanisterId, + }); + } + + static isValidAddress(address: string): boolean { + try { + decodeIcrcAccount(address); + return true; + } catch { + return false; + } + } + isValidAddress(address: string): boolean { + return ICRC1Api.isValidAddress(address); + } + + async fetchBalance(): Promise { + return await this.ledgerActor.icrc1_balance_of(this.account); + } + + async fetchTransfers( + input: FetchTransfersInput, + startBlockId?: bigint, + ): Promise { + if (!this.indexActor) { + throw new Error('Cannot fetch balance without index canister id.'); + } + + const result = await this.indexActor.get_account_transactions({ + account: this.account, + max_results: ICRC1Api.PAGE_SIZE, + start: startBlockId ? [startBlockId] : [], + }); + + if ('Err' in result) { + throw result.Err; + } + + const response = result.Ok; + let transfers: AccountIncomingTransfer[] = []; + let nextTxId: null | bigint = null; + if (response.transactions.length) { + const lastTx = response.transactions[response.transactions.length - 1]; + nextTxId = lastTx.id; + } + response.transactions.forEach(tx => { + if (tx.transaction.transfer[0]) { + const transferInfo = tx.transaction.transfer[0]; + + transfers.push({ + from: encodeIcrcAccount({ + owner: transferInfo.from.owner, + subaccount: transferInfo.from.subaccount[0], + }), + to: encodeIcrcAccount({ + owner: transferInfo.to.owner, + subaccount: transferInfo.to.subaccount[0], + }), + amount: transferInfo.amount, + fee: transferInfo.fee[0] ?? 0n, + created_at: nanoToJsDate(tx.transaction.timestamp), + }); + } + }); + + if ( + transfers.length && + transfers[transfers.length - 1]?.created_at && + nextTxId !== null && + nextTxId !== response.oldest_tx_id?.[0] + ) { + const lastTransfer = transfers[transfers.length - 1]; + const lastTransferTime = lastTransfer.created_at!.getTime(); + const shouldFetchMore = + (input.fromDt && lastTransferTime > input.fromDt!.getTime()) || (!input.fromDt && nextTxId); + + if (shouldFetchMore) { + const moreTransfers = await this.fetchTransfers(input, nextTxId); + transfers.push(...moreTransfers); + } + } + + transfers = transfers.filter(t => { + const isInFromDt = !input.fromDt ? true : t.created_at && t.created_at >= input.fromDt; + const isInToDt = !input.toDt ? true : t.created_at && t.created_at <= input.toDt; + + return isInFromDt && isInToDt; + }); + + return transfers; + } + + getCapabilities(): ChainApiCapability[] { + return [ + ChainApiCapability.Balance, // balance always available due to ledger canister id mandatory + ...(this.indexActor ? [ChainApiCapability.Transfers] : []), + ]; + } +} diff --git a/apps/wallet/src/services/chains/index.ts b/apps/wallet/src/services/chains/index.ts index 4a022f024..f524f8c54 100644 --- a/apps/wallet/src/services/chains/index.ts +++ b/apps/wallet/src/services/chains/index.ts @@ -1,16 +1,48 @@ -import { Account } from '~/generated/station/station.did'; -import { BlockchainStandard, BlockchainType, ChainApi } from '~/types/chain.types'; +import { AccountAddress, Asset } from '~/generated/station/station.did'; +import { AddressFormat, BlockchainStandard, BlockchainType, ChainApi } from '~/types/chain.types'; +import { getAssetMetadata } from '~/utils/asset.utils'; import { ICNativeApi } from './ic-native-api.service'; +import { ICRC1Api } from './icrc1-api.service'; export class ChainApiFactory { - static create(account: Account): ChainApi { - const chainAndStandard = `${account.blockchain}-${account.standard}`; + static create(asset: Asset, addresses: AccountAddress[]): ChainApi { + switch (asset.blockchain) { + case BlockchainType.InternetComputer: { + const maybeIcpNativeAddress = addresses.find(a => a.format === AddressFormat.ICPNative); + const maybeIcrc1Address = addresses.find(a => a.format === AddressFormat.ICRC1); + const maybeLedgerCanisterId = getAssetMetadata(asset, 'ledger_canister_id'); + const maybeIndexCanisterId = getAssetMetadata(asset, 'index_canister_id'); - switch (chainAndStandard) { - case `${BlockchainType.InternetComputer}-${BlockchainStandard.Native}`: - return new ICNativeApi(account); + if ( + asset.standards.includes(BlockchainStandard.Native) && + maybeIcpNativeAddress && + maybeLedgerCanisterId + ) { + return new ICNativeApi( + maybeIcpNativeAddress.address, + maybeLedgerCanisterId, + maybeIndexCanisterId, + ); + } + + if ( + asset.standards.includes(BlockchainStandard.ICRC1) && + maybeIcrc1Address && + maybeLedgerCanisterId + ) { + return new ICRC1Api( + maybeIcrc1Address.address, + maybeLedgerCanisterId, + maybeIndexCanisterId, + ); + } + + throw new Error(`Blockchain not supported: ${asset.blockchain}`); + } + case BlockchainType.Bitcoin: + case BlockchainType.Ethereum: default: - throw new Error(`Blockchain not supported ${chainAndStandard}`); + throw new Error(`Blockchain not supported: ${asset.blockchain}`); } } } diff --git a/apps/wallet/src/services/station.service.ts b/apps/wallet/src/services/station.service.ts index 3a6e66aff..d497586d7 100644 --- a/apps/wallet/src/services/station.service.ts +++ b/apps/wallet/src/services/station.service.ts @@ -2,9 +2,11 @@ import { Actor, ActorSubclass, HttpAgent } from '@dfinity/agent'; import { Principal } from '@dfinity/principal'; import { idlFactory } from '~/generated/station'; import { - AccountBalance, + Account, + AccountCallerPrivileges, AddAccountOperationInput, AddAddressBookEntryOperationInput, + AddAssetOperationInput, AddRequestPolicyOperationInput, AddUserGroupOperationInput, AddUserOperationInput, @@ -20,16 +22,20 @@ import { DisasterRecoveryCommittee, EditAccountOperationInput, EditAddressBookEntryOperationInput, + EditAssetOperationInput, EditPermissionOperationInput, EditRequestPolicyOperationInput, EditUserGroupOperationInput, EditUserOperationInput, FetchAccountBalancesInput, + FetchAccountBalancesResult, FundExternalCanisterOperationInput, GetAccountInput, GetAccountResult, GetAddressBookEntryInput, GetAddressBookEntryResult, + GetAssetInput, + GetAssetResult, GetExternalCanisterFiltersResult, GetExternalCanisterResult, GetNextApprovableRequestResult, @@ -46,6 +52,7 @@ import { ListAccountTransfersInput, ListAccountsResult, ListAddressBookEntriesResult, + ListAssetsResult, ListExternalCanistersResult, ListNotificationsInput, ListPermissionsInput, @@ -59,6 +66,7 @@ import { MarkNotificationsReadInput, Notification, PaginationInput, + RemoveAssetOperationInput, RemoveUserGroupOperationInput, Request, SubmitRequestApprovalInput, @@ -78,6 +86,7 @@ import { GetNextApprovableRequestArgs, ListAccountsArgs, ListAddressBookEntriesArgs, + ListAssetsArgs, ListExternalCanistersArgs, ListRequestsArgs, } from '~/types/station.types'; @@ -548,8 +557,50 @@ export class StationService { return result.Ok; } + async listAllAccounts(verifiedCall = false): Promise<{ + accounts: Account[]; + privileges: AccountCallerPrivileges[]; + }> { + const actor = verifiedCall ? this.verified_actor : this.actor; + + const accounts: Account[] = []; + const privileges: AccountCallerPrivileges[] = []; + let nextOffset: [bigint] | [] = []; + + do { + const result = await actor.list_accounts({ + paginate: [ + { + limit: [100], + offset: nextOffset, + }, + ], + search_term: [], + }); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + accounts.push(...result.Ok.accounts); + privileges.push(...result.Ok.privileges); + + nextOffset = result.Ok.next_offset as [bigint] | []; // have to force cast here because of typescript inference + } while (nextOffset.length > 0); + + return { accounts, privileges }; + } + async listAddressBook( - { limit, offset, blockchain, labels, ids, addresses }: ListAddressBookEntriesArgs = {}, + { + limit, + offset, + blockchain, + labels, + ids, + addresses, + address_formats, + }: ListAddressBookEntriesArgs = {}, verifiedCall = false, ): Promise> { const actor = verifiedCall ? this.verified_actor : this.actor; @@ -564,6 +615,7 @@ export class StationService { labels: labels ? [labels] : [], addresses: addresses ? [addresses] : [], ids: ids ? [ids] : [], + address_formats: address_formats ? [address_formats] : [], }); if (variantIs(result, 'Err')) { @@ -573,6 +625,17 @@ export class StationService { return result.Ok; } + async getAsset(input: GetAssetInput, verifiedCall = false): Promise> { + const actor = verifiedCall ? this.verified_actor : this.actor; + const result = await actor.get_asset(input); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + return result.Ok; + } + async fundExternalCanister(input: FundExternalCanisterOperationInput): Promise { const result = await this.actor.create_request({ execution_plan: [{ Immediate: null }], @@ -677,6 +740,27 @@ export class StationService { return result.Ok; } + async listAssets( + { limit, offset }: ListAssetsArgs = {}, + verifiedCall = false, + ): Promise> { + const actor = verifiedCall ? this.verified_actor : this.actor; + const result = await actor.list_assets({ + paginate: [ + { + limit: limit !== undefined ? [limit] : [], + offset: offset !== undefined ? [BigInt(offset)] : [], + }, + ], + }); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + return result.Ok; + } + async getExternalCanisterByCanisterId( canisterId: Principal, verifiedCall = false, @@ -718,6 +802,22 @@ export class StationService { return result.Ok; } + async addAsset(input: AddAssetOperationInput): Promise { + const result = await this.actor.create_request({ + execution_plan: [{ Immediate: null }], + title: [], + summary: [], + operation: { AddAsset: input }, + expiration_dt: [], + }); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + return result.Ok.request; + } + async fetchExternalCanisterFilters( args: { with_labels?: boolean; @@ -757,6 +857,38 @@ export class StationService { return result.Ok.request; } + async editAsset(input: EditAssetOperationInput): Promise { + const result = await this.actor.create_request({ + execution_plan: [{ Immediate: null }], + title: [], + summary: [], + operation: { EditAsset: input }, + expiration_dt: [], + }); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + return result.Ok.request; + } + + async removeAsset(input: RemoveAssetOperationInput): Promise { + const result = await this.actor.create_request({ + execution_plan: [{ Immediate: null }], + title: [], + summary: [], + operation: { RemoveAsset: input }, + expiration_dt: [], + }); + + if (variantIs(result, 'Err')) { + throw result.Err; + } + + return result.Ok.request; + } + async getAccount( input: GetAccountInput, verifiedCall = false, @@ -824,7 +956,9 @@ export class StationService { return variantIs(result, 'Healthy'); } - async fetchAccountBalances(input: FetchAccountBalancesInput): Promise { + async fetchAccountBalances( + input: FetchAccountBalancesInput, + ): Promise['balances']> { const result = await this.actor.fetch_account_balances(input); if (variantIs(result, 'Err')) { diff --git a/apps/wallet/src/stores/station.store.ts b/apps/wallet/src/stores/station.store.ts index d33785318..a3e30cb7c 100644 --- a/apps/wallet/src/stores/station.store.ts +++ b/apps/wallet/src/stores/station.store.ts @@ -21,7 +21,7 @@ import { services } from '~/plugins/services.plugin'; import { StationService } from '~/services/station.service'; import { useAppStore } from '~/stores/app.store'; import { Privilege } from '~/types/auth.types'; -import { BlockchainStandard, BlockchainType } from '~/types/chain.types'; +import { BlockchainType } from '~/types/chain.types'; import { LoadableItem } from '~/types/helper.types'; import { computedStationName, isApiError, popRedirectToLocation } from '~/utils/app.utils'; import { hasRequiredPrivilege } from '~/utils/auth.utils'; @@ -73,6 +73,10 @@ export const createUserInitialAccount = async ( userId: UUID, station = useStationStore(), ): Promise => { + const maybeIcpId = station.configuration.details.supported_assets.find( + asset => asset.blockchain == BlockchainType.InternetComputer && asset.symbol == 'ICP', + )?.id; + await station.service.createRequest({ title: [], summary: [], @@ -81,8 +85,7 @@ export const createUserInitialAccount = async ( operation: { AddAccount: { name: i18n.global.t('app.initial_account_name'), - blockchain: BlockchainType.InternetComputer, - standard: BlockchainStandard.Native, + assets: maybeIcpId ? [maybeIcpId] : [], metadata: [], read_permission: { auth_scope: { Restricted: null }, user_groups: [], users: [userId] }, transfer_permission: { @@ -124,6 +127,7 @@ const initialStoreState = (): StationStoreState => { name: '', version: '', supported_assets: [], + supported_blockchains: [], }, cycleObtainStrategy: { Disabled: null }, }, diff --git a/apps/wallet/src/types/auth.types.ts b/apps/wallet/src/types/auth.types.ts index e18c717c6..4f277d99f 100644 --- a/apps/wallet/src/types/auth.types.ts +++ b/apps/wallet/src/types/auth.types.ts @@ -15,6 +15,8 @@ export enum Privilege { ListRequests = 'ListRequests', SystemUpgrade = 'SystemUpgrade', ManageSystemInfo = 'ManageSystemInfo', + ListAssets = 'ListAssets', + AddAsset = 'AddAsset', ListExternalCanisters = 'ListExternalCanisters', CreateExternalCanister = 'CreateExternalCanister', CallAnyExternalCanister = 'CallAnyExternalCanister', diff --git a/apps/wallet/src/types/chain.types.ts b/apps/wallet/src/types/chain.types.ts index 4aa6ba37c..b071b0a71 100644 --- a/apps/wallet/src/types/chain.types.ts +++ b/apps/wallet/src/types/chain.types.ts @@ -5,7 +5,13 @@ export enum BlockchainType { } export enum BlockchainStandard { - Native = 'native', + Native = 'icp_native', + ICRC1 = 'icrc1', +} + +export enum AddressFormat { + ICPNative = 'icp_account_identifier', + ICRC1 = 'icrc1_account', } export enum TokenSymbol { @@ -30,10 +36,17 @@ export interface FetchTransfersResponse { transfers: AccountIncomingTransfer[]; } +export enum ChainApiCapability { + Balance, + Transfers, +} + export interface ChainApi { fetchBalance(): Promise; fetchTransfers(input: FetchTransfersInput): Promise; isValidAddress(address: string): boolean; + + getCapabilities(): ChainApiCapability[]; } diff --git a/apps/wallet/src/types/permissions.types.ts b/apps/wallet/src/types/permissions.types.ts index 80ba85a60..a1c58ac27 100644 --- a/apps/wallet/src/types/permissions.types.ts +++ b/apps/wallet/src/types/permissions.types.ts @@ -13,6 +13,7 @@ export enum ResourceTypeEnum { ExternalCanister = 'ExternalCanister', SetDisasterRecovery = 'SetDisasterRecovery', Notification = 'Notification', + Asset = 'Asset', } export enum ResourceActionEnum { diff --git a/apps/wallet/src/types/requests.types.ts b/apps/wallet/src/types/requests.types.ts index 3143cf482..e37f5c080 100644 --- a/apps/wallet/src/types/requests.types.ts +++ b/apps/wallet/src/types/requests.types.ts @@ -11,6 +11,7 @@ export enum ListRequestsOperationTypeGroup { SystemUpgrade = 'system_upgrade', SystemInfo = 'system_info', ExternalCanister = 'external_canister', + Asset = 'asset', } export enum RequestApprovalStatusEnum { diff --git a/apps/wallet/src/types/station.types.ts b/apps/wallet/src/types/station.types.ts index 0bd8edc06..95b45ab98 100644 --- a/apps/wallet/src/types/station.types.ts +++ b/apps/wallet/src/types/station.types.ts @@ -80,6 +80,7 @@ export enum RequestDomains { Users = 'users', ExternalCanisters = 'external_canisters', System = 'system', + Assets = 'assets', } export interface ListAccountsArgs { @@ -116,6 +117,9 @@ export enum RequestSpecifierEnum { CallExternalCanister = 'CallExternalCanister', FundExternalCanister = 'FundExternalCanister', SetDisasterRecovery = 'SetDisasterRecovery', + AddAsset = 'AddAsset', + EditAsset = 'EditAsset', + RemoveAsset = 'RemoveAsset', } export enum RequestPolicyRuleEnum { @@ -142,6 +146,12 @@ export interface ListAddressBookEntriesArgs { blockchain?: string; labels?: []; ids?: UUID[]; + address_formats?: string[]; +} + +export interface ListAssetsArgs { + limit?: number; + offset?: number; } export interface ListExternalCanistersArgs { @@ -186,4 +196,7 @@ export enum RequestOperationEnum { ConfigureExternalCanister = 'ConfigureExternalCanister', FundExternalCanister = 'FundExternalCanister', SetDisasterRecovery = 'SetDisasterRecovery', + AddAsset = 'AddAsset', + EditAsset = 'EditAsset', + RemoveAsset = 'RemoveAsset', } diff --git a/apps/wallet/src/utils/asset.utils.spec.ts b/apps/wallet/src/utils/asset.utils.spec.ts new file mode 100644 index 000000000..e4d021e37 --- /dev/null +++ b/apps/wallet/src/utils/asset.utils.spec.ts @@ -0,0 +1,27 @@ +import { shortenIcrc1Address } from './asset.utils'; +import { describe, expect, it } from 'vitest'; + +describe('shortenIcrc1Address', () => { + it('returns the principal if the subaccount is not present', () => { + expect(shortenIcrc1Address('rwlgt-iiaaa-aaaaa-aaaaa-cai')).toBe('rwlgt-iiaaa-aaaaa-aaaaa-cai'); + expect( + shortenIcrc1Address('wmzac-nabae-aqcai-baeaq-caiba-eaqca-ibaea-qcaib-aeaqc-aibae-aqc'), + ).toBe('wmzac-nabae-...-aibae-aqc'); + }); + + it('returns some of the principal and some of the subaccount if the subaccount is present', () => { + expect( + shortenIcrc1Address( + 'wmzac-nabae-aqcai-baeaq-caiba-eaqca-ibaea-qcaib-aeaqc-aibae-aqc-haltvua.102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', + ), + ).toBe('wmzac-...102030405060708090a0...1e1f'); + + expect( + shortenIcrc1Address( + 'rwlgt-iiaaa-aaaaa-aaaaa-cai-pyz4egi.102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', + ), + ).toBe('rwlgt-...102030405060708090a0...1e1f'); + + expect(shortenIcrc1Address('rwlgt-iiaaa-aaaaa-aaaaa-cai-ltrlami.10203')).toBe('rwlgt-...10203'); + }); +}); diff --git a/apps/wallet/src/utils/asset.utils.ts b/apps/wallet/src/utils/asset.utils.ts new file mode 100644 index 000000000..8f6f7f956 --- /dev/null +++ b/apps/wallet/src/utils/asset.utils.ts @@ -0,0 +1,72 @@ +import { decodeIcrcAccount } from '@dfinity/ledger-icrc'; +import { Asset, StandardData, SupportedBlockchain } from '~/generated/station/station.did'; +import { ICNativeApi } from '~/services/chains/ic-native-api.service'; +import { ICRC1Api } from '~/services/chains/icrc1-api.service'; +import { AddressFormat, BlockchainType } from '~/types/chain.types'; + +export function getAssetMetadata(asset: Asset, key: string): string | undefined { + return asset.metadata.find(m => m.key === key)?.value; +} + +export function detectAddressFormat(blockchain: string, address: string): string | undefined { + switch (blockchain) { + case BlockchainType.InternetComputer: + if (ICNativeApi.isValidAddress(address)) { + return AddressFormat.ICPNative; + } else if (ICRC1Api.isValidAddress(address)) { + return AddressFormat.ICRC1; + } else { + return; + } + case BlockchainType.Bitcoin: + case BlockchainType.Ethereum: + return; + default: + throw new Error(`Blockchain not supported ${blockchain}`); + } +} + +export function detectAddressStandard( + asset: Asset, + address: string, + supportedBlockchains: SupportedBlockchain[], +): StandardData | undefined { + const maybeFormat = detectAddressFormat(asset.blockchain, address); + if (!maybeFormat) { + return; + } + + const supportedStandards = supportedBlockchains + .find(b => b.blockchain === asset.blockchain) + ?.supported_standards.filter(supportedStandard => + asset.standards.includes(supportedStandard.standard), + ); + + return supportedStandards?.find(s => s.supported_address_formats.includes(maybeFormat)); +} + +export function shortenIcrc1Address(address: string): string { + const account = decodeIcrcAccount(address); + const principal = account.owner.toText(); + + if (!account.subaccount || account.subaccount.every(b => b === 0)) { + // show just the principal, if there is no subaccount + if (principal.length <= 32) { + // the principal is short enough to show the whole thing + return principal; + } + + // shorten the principal + return principal.slice(0, 12) + '...' + principal.slice(-10); + } else { + const subaccount = address.split('.')[1]; + + if (subaccount.length <= 27) { + // the subaccount is short enough to show the whole thing + return `${address.slice(0, 6)}...${subaccount}`; + } + + // shorted the subaccount + return `${address.slice(0, 6)}...${subaccount.slice(0, 20)}...${address.slice(-4)}`; + } +} diff --git a/apps/wallet/src/utils/form.utils.ts b/apps/wallet/src/utils/form.utils.ts index 4a254289e..f58d23d07 100644 --- a/apps/wallet/src/utils/form.utils.ts +++ b/apps/wallet/src/utils/form.utils.ts @@ -1,6 +1,7 @@ import { Principal } from '@dfinity/principal'; import isUUID from 'validator/es/lib/isUUID'; import { i18n } from '~/plugins/i18n.plugin'; +import { detectAddressFormat } from './asset.utils'; export const requiredRule = (value: unknown): string | boolean => { if (value === null || value === undefined || value === '') { @@ -109,6 +110,20 @@ export const maxLengthRule = (max: number, field: string) => { }; }; +export const validSymbolRule = (value: unknown): string | boolean => { + const hasValue = !!value; + if (!hasValue) { + // this rule only applies if there is a value + return true; + } + + if (typeof value !== 'string') { + throw new Error('validSymbolRule only applies to strings'); + } + + return /^[a-zA-Z0-9]{1,32}$/.test(value) ? true : i18n.global.t('forms.rules.validSymbol'); +}; + export const uniqueRule = ( existing: unknown[], errorMessage: string = i18n.global.t('forms.rules.duplicate'), @@ -241,3 +256,26 @@ export const validEmail = (value: unknown): string | boolean => { return true; }; + +export const validAddress = + (blockchain: string) => + (value: unknown): string | boolean => { + const hasValue = !!value; + if (!hasValue) { + // this rule only applies if there is a value + return true; + } + + if (typeof value !== 'string') { + return i18n.global.t('forms.rules.validAddress'); + } + + try { + if (detectAddressFormat(blockchain, value) !== undefined) { + return true; + } + return i18n.global.t('forms.rules.validAddress'); + } catch { + return i18n.global.t('forms.rules.validAddress'); + } + }; diff --git a/apps/wallet/src/utils/helper.utils.ts b/apps/wallet/src/utils/helper.utils.ts index 0581a60e7..d3d64b457 100644 --- a/apps/wallet/src/utils/helper.utils.ts +++ b/apps/wallet/src/utils/helper.utils.ts @@ -542,6 +542,16 @@ export const transformData = ( return normalizedInput; }; +export function hexStringToUint8Array(input: string) { + const result = new Uint8Array(input.length / 2); + + for (let i = 0; i < input.length; i += 2) { + result[i / 2] = parseInt(input.slice(i, i + 2), 16); + } + + return result; +} + /** * Deep clones the input data using structured cloning, if Proxy objects are found they are * transformed to plain objects. diff --git a/apps/wallet/src/workers/accounts.worker.ts b/apps/wallet/src/workers/accounts.worker.ts index 111216e24..4025e6321 100644 --- a/apps/wallet/src/workers/accounts.worker.ts +++ b/apps/wallet/src/workers/accounts.worker.ts @@ -1,8 +1,9 @@ import { Principal } from '@dfinity/principal'; import { icAgent } from '~/core/ic-agent.core'; import { logger } from '~/core/logger.core'; -import { AccountBalance, UUID } from '~/generated/station/station.did'; +import { AccountBalance, FetchAccountBalancesResult, UUID } from '~/generated/station/station.did'; import { StationService } from '~/services/station.service'; +import { ExtractOk } from '~/types/helper.types'; import { arrayBatchMaker, timer, unreachable } from '~/utils/helper.utils'; const DEFAULT_INTERVAL_MS = 10000; @@ -42,7 +43,7 @@ export interface AccountsWorkerErrorResponse { } export interface AccountBalancesWorkerResponse { - balances: AccountBalance[]; + balances: Array<[] | [AccountBalance]>; } export type AccountsWorkerResponseMessage = @@ -130,7 +131,7 @@ class AccountsWorkerImpl { this.stationService.fetchAccountBalances({ account_ids: accountIds }).catch(err => { logger.error('Failed to update the balance for the given account ids', { err }); - return [] as AccountBalance[]; + return [] as ExtractOk['balances']; }), ); diff --git a/core/control-panel/impl/src/controllers/station.rs b/core/control-panel/impl/src/controllers/station.rs index 1029e3003..a8918b0b2 100644 --- a/core/control-panel/impl/src/controllers/station.rs +++ b/core/control-panel/impl/src/controllers/station.rs @@ -130,7 +130,7 @@ impl StationController { async fn deploy_station(&self, input: DeployStationInput) -> ApiResult { let ctx = CallContext::get(); let _lock = STATE - .with(|state| CallerGuard::new(state.clone(), ctx.caller())) + .with(|state| CallerGuard::new(state.clone(), ctx.caller(), None)) .ok_or(UserError::ConcurrentStationDeployment)?; let deployed_station_id = self.deploy_service.deploy_station(input, &ctx).await?; diff --git a/core/control-panel/impl/src/services/canister.rs b/core/control-panel/impl/src/services/canister.rs index efb5589b2..705a927eb 100644 --- a/core/control-panel/impl/src/services/canister.rs +++ b/core/control-panel/impl/src/services/canister.rs @@ -51,6 +51,7 @@ impl CanisterService { self.assert_controller(&CallContext::get(), "upload_canister_modules".to_string())?; let mut config = canister_config().unwrap_or_default(); + if let Some(upgrader_wasm_module) = input.upgrader_wasm_module { config.upgrader_wasm_module = upgrader_wasm_module; } @@ -60,6 +61,7 @@ impl CanisterService { if let Some(station_wasm_module_extra_chunks) = input.station_wasm_module_extra_chunks { config.station_wasm_module_extra_chunks = station_wasm_module_extra_chunks; } + write_canister_config(config); Ok(()) diff --git a/core/control-panel/impl/src/services/deploy.rs b/core/control-panel/impl/src/services/deploy.rs index ff1a9b6a5..4f54f8090 100644 --- a/core/control-panel/impl/src/services/deploy.rs +++ b/core/control-panel/impl/src/services/deploy.rs @@ -103,6 +103,7 @@ impl DeployService { quorum: Some(1), fallback_controller: Some(NNS_ROOT_CANISTER_ID), accounts: None, + assets: None, })) .map_err(|err| DeployError::Failed { reason: err.to_string(), diff --git a/core/station/api/spec.did b/core/station/api/spec.did index a2fbdbd4f..ad4c9c2d4 100644 --- a/core/station/api/spec.did +++ b/core/station/api/spec.did @@ -59,6 +59,9 @@ type RequestSpecifier = variant { EditUserGroup : ResourceIds; RemoveUserGroup : ResourceIds; ManageSystemInfo; + AddAsset; + EditAsset : ResourceIds; + RemoveAsset : ResourceIds; }; // A record type that can be used to represent a percentage of users that are required to approve a rule. @@ -322,6 +325,10 @@ type RequestApproval = record { type TransferOperationInput = record { // The account id to use for the transaction. from_account_id : UUID; + // The asset id to transfer. + from_asset_id : UUID; + // The standard to use for the transfer. + with_standard : text; // The amount to transfer. amount : nat; // The destination address of the transaction (e.g. "1BvBMSE..."). @@ -342,6 +349,8 @@ type TransferOperationInput = record { type TransferOperation = record { // The account to use for the transaction. from_account : opt Account; + // The asset to use for the transaction. + from_asset : Asset; // The network to use for the transaction. network : Network; // The input to the request to transfer funds. @@ -352,12 +361,27 @@ type TransferOperation = record { fee : opt nat; }; +// Mutate the list of assets. +type ChangeAssets = variant { + // Replace all current assets with the specified list. + ReplaceWith : record { + assets : vec UUID; + }; + // Change the list of assets by adding and removing assets. + Change : record { + add_assets : vec UUID; + remove_assets : vec UUID; + }; +}; + // Input type for editing an account through a request. type EditAccountOperationInput = record { // The account id that will be edited. account_id : UUID; // A friendly name for the account (e.g. "My Account"). name : opt text; + // Mutate the list of assets. + change_assets : opt ChangeAssets; // Who can read the account information. read_permission : opt Allow; // Who can request configuration changes to the account. @@ -379,10 +403,8 @@ type EditAccountOperation = record { type AddAccountOperationInput = record { // A friendly name for the account (e.g. "My Account"). name : text; - // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; - // The asset standard for this account (e.g. `native`, `erc20`, etc.). - standard : text; + // The assets to add to the account. + assets : vec UUID; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; // Who can read the account information. @@ -417,6 +439,8 @@ type AddAddressBookEntryOperationInput = record { address_owner : text; // The actual address. address : text; + // The format of the address, eg. icp_account_identifier + address_format : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // Metadata associated with the address book entry (e.g. `{"kyc": "true"}`). @@ -922,6 +946,12 @@ type RequestOperation = variant { RemoveRequestPolicy : RemoveRequestPolicyOperation; // An operation for managing system info. ManageSystemInfo : ManageSystemInfoOperation; + // An operation for adding a new asset. + AddAsset : AddAssetOperation; + // An operation for editing an existing asset. + EditAsset : EditAssetOperation; + // An operation for removing an existing asset. + RemoveAsset : RemoveAssetOperation; }; type RequestOperationInput = variant { @@ -971,6 +1001,12 @@ type RequestOperationInput = variant { RemoveRequestPolicy : RemoveRequestPolicyOperationInput; // An operation for managing system info. ManageSystemInfo : ManageSystemInfoOperationInput; + // An operation for adding a new asset. + AddAsset : AddAssetOperationInput; + // An operation for editing an existing asset. + EditAsset : EditAssetOperationInput; + // An operation for removing an existing asset. + RemoveAsset : RemoveAssetOperationInput; }; type RequestOperationType = variant { @@ -1020,6 +1056,12 @@ type RequestOperationType = variant { RemoveRequestPolicy; // And operation for managing system info. ManageSystemInfo; + // An operation for adding a new asset. + AddAsset; + // An operation for editing an existing asset. + EditAsset; + // An operation for removing an existing asset. + RemoveAsset; }; // The schedule for executing a transaction of a given transfer. @@ -1170,6 +1212,12 @@ type ListRequestsOperationType = variant { ManageSystemInfo; // An operation for setting disaster recovery config. SetDisasterRecovery; + // An operation for adding an asset. + AddAsset; + // An operation for editing an asset. + EditAsset; + // An operation for removing an asset. + RemoveAsset; }; // The direction to use for sorting. @@ -1549,21 +1597,15 @@ type AccountCallerPrivileges = record { type Account = record { // The internal account id. id : UUID; - // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; - // The asset symbol, e.g. "ICP" or "BTC". - symbol : AssetSymbol; - // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string - // with spaces replaced with underscores. - standard : text; - // The address of the account (e.g. "0x1234"). - address : text; - // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). - decimals : nat32; + + // The list of assets supported by this account. + assets : vec AccountAsset; + + // The list of addresses associated with the account. + addresses : vec AccountAddress; + // A friendly name for the account. name : text; - // Account balance when available. - balance : opt AccountBalanceInfo; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; // The transfer approval policy for the account. @@ -1578,6 +1620,25 @@ type Account = record { last_modification_timestamp : TimestampRFC3339; }; +// The seed used to derive the addresses of the account. +type AccountSeed = blob; + +// Record type to describe an address of an account. +type AccountAddress = record { + // The address. + address : text; + // The format of the address, eg. icp_account_identifier. + format : text; +}; + +// Record type to describe an asset of an account. +type AccountAsset = record { + // The asset id. + asset_id : UUID; + // The balance of the asset. + balance : opt AccountBalance; +}; + // Input type for getting a account. type GetAccountInput = record { // The account id to retrieve. @@ -1600,12 +1661,19 @@ type GetAccountResult = variant { type AccountBalance = record { // The account id. account_id : UUID; + // The asset id. + asset_id : UUID; // The balance of the account. balance : nat; // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). decimals : nat32; // The time at which the balance was last updated. last_update_timestamp : TimestampRFC3339; + // The state of balance query: + // - `fresh`: The balance was recently updated and is considered fresh. + // - `stale`: The balance may be out of date. + // - `stale_refreshing`: The balance may be out of date but it is being refreshed in the background. + query_state : text; }; // Input type for getting a account balance. @@ -1619,7 +1687,7 @@ type FetchAccountBalancesResult = variant { // The result data for a successful execution. Ok : record { // The account balance that was retrieved. - balances : vec AccountBalance; + balances : vec opt AccountBalance; }; // The error that occurred (e.g. the user does not have the necessary permissions). Err : Error; @@ -1652,6 +1720,8 @@ type AddressBookEntry = record { address_owner : text; // The actual address. address : text; + // The address format (e.g. "icp_account_identifier"). + address_format : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // Metadata associated with the address book entry (e.g. `{"kyc": "true"}`). @@ -1691,6 +1761,8 @@ type ListAddressBookEntriesInput = record { blockchain : opt text; // The labels to search for, if provided only address book entries with the given labels will be returned. labels : opt vec text; + // The address formats to search for. + address_formats : opt vec text; // The pagination parameters. paginate : opt PaginationInput; }; @@ -1723,19 +1795,41 @@ type AssetMetadata = record { // A record type that can be used to represent an asset in the station. type Asset = record { + // The internal asset id. + id : UUID; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) blockchain : text; // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string // with spaces replaced with underscores. - standard : text; + standards : vec text; // The asset symbol, e.g. "ICP" or "BTC". symbol : AssetSymbol; // The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) name : text; - // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`), - // also, in the case of non-native assets, it can contain other required - // information (e.g. `{"address": "0x1234"}`). + // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). metadata : vec AssetMetadata; + // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). + decimals : nat32; +}; + +// Describes a standard suported by a blockchain. +type StandardData = record { + // The standard name. + standard : text; + // Required metadata fields for the standard (e.g. `["ledger_canister_id"]`). + required_metadata_fields : vec text; + // Supported operations for the standard (e.g. `["transfer", "list_transfers", "balance"]`). + supported_operations : vec text; + // Supported address formats of the standard. + supported_address_formats : vec text; +}; + +// Describes a blockchain and its standards supported by the station. +type SupportedBlockchain = record { + // The blockchain name. + blockchain : text; + // The supported standards for the blockchain. + supported_standards : vec StandardData; }; // A record type that is used to show the current capabilities of the station. @@ -1746,6 +1840,8 @@ type Capabilities = record { version : text; // The list of supported assets. supported_assets : vec Asset; + // The list of supported blockchains and standards. + supported_blockchains : vec SupportedBlockchain; }; // Result type for getting the current config. @@ -2014,6 +2110,7 @@ type Resource = variant { System : SystemResourceAction; User : UserResourceAction; UserGroup : ResourceAction; + Asset : ResourceAction; }; // A record type that can be used to represent the caller privileges for a given permission. @@ -2174,6 +2271,122 @@ type ListRequestPoliciesResult = variant { Err : Error; }; +type AddAssetOperation = record { + // The result of adding an asset. + asset : opt Asset; + // The input to the request to add an asset. + input : AddAssetOperationInput; +}; + +// The input type for adding an asset. +type AddAssetOperationInput = record { + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : text; + // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string + // with spaces replaced with underscores. + standards : vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : AssetSymbol; + // The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) + name : text; + // The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). + metadata : vec AssetMetadata; + // The number of decimals used by the asset (e.g. `8` for `BTC`, `18` for `ETH`, etc.). + decimals : nat32; +}; + +type EditAssetOperation = record { + // The input to the request to edit an asset. + input : EditAssetOperationInput; +}; + +// The input type for editing an asset. +type EditAssetOperationInput = record { + // The asset id to edit. + asset_id : UUID; + // The name of the asset. + name : opt text; + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : opt text; + // The asset standard that is supported (e.g. `erc20`, etc.), canonically represented as a lowercase string + // with spaces replaced with underscores. + standards : opt vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : opt AssetSymbol; + // The metadata to change. + change_metadata : opt ChangeMetadata; +}; + +// Type for instructions to update the address book entry's metadata. +type ChangeMetadata = variant { + // Replace all existing metadata by the specified metadata. + ReplaceAllBy : vec AssetMetadata; + // Override values of existing metadata with the specified keys + // and add new metadata if no metadata can be found with the specified keys. + OverrideSpecifiedBy : vec AssetMetadata; + // Remove metadata with the specified keys. + RemoveKeys : vec text; +}; + +type RemoveAssetOperation = record { + // The input to the request to remove an asset. + input : RemoveAssetOperationInput; +}; + +// The input type for removing an asset. +type RemoveAssetOperationInput = record { + // The asset id to remove. + asset_id : UUID; +}; + +// The input type for listing assets. +type ListAssetsInput = record { + // The pagination parameters. + paginate : opt PaginationInput; +}; + +// The result type for listing assets. +type ListAssetsResult = variant { + // The result data for a successful execution. + Ok : record { + // The list of assets. + assets : vec Asset; + // The offset to use for the next page. + next_offset : opt nat64; + // The total number of assets. + total : nat64; + // The caller privileges for the assets. + privileges : vec AssetCallerPrivileges; + }; + // The error that occurred (e.g. the user does not have the necessary permissions). + Err : Error; +}; + +// The input type for getting an asset. +type GetAssetInput = record { + // The asset id to retrieve. + asset_id : UUID; +}; + +// The result type for getting an asset. +type GetAssetResult = variant { + // The result data for a successful execution. + Ok : record { + // The asset that was retrieved. + asset : Asset; + // The caller privileges for the asset. + privileges : AssetCallerPrivileges; + }; + // The error that occurred (e.g. the user does not have the necessary permissions). + Err : Error; +}; + +type AssetCallerPrivileges = record { + id : UUID; + can_edit : bool; + can_delete : bool; +}; + // The top level privileges that the user has when making calls to the canister. type UserPrivilege = variant { Capabilities; @@ -2195,6 +2408,8 @@ type UserPrivilege = variant { CreateExternalCanister; ListExternalCanisters; CallAnyExternalCanister; + ListAssets; + AddAsset; }; type MeResult = variant { @@ -2230,13 +2445,31 @@ type InitAccountInput = record { // A friendly name for the account (e.g. "My Account"). name : text; // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - blockchain : text; + seed : AccountSeed; // The asset standard for this account (e.g. `native`, `erc20`, etc.). - standard : text; + assets : vec UUID; // Metadata associated with the account (e.g. `{"contract": "0x1234", "symbol": "ANY"}`). metadata : vec AccountMetadata; }; +// The initial assets to create when initializing the canister for the first time, e.g., after disaster recovery. +type InitAssetInput = record { + // The UUID of the asset, if not provided a new UUID will be generated. + id : UUID; + // The name of the asset. + name : text; + // The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + blockchain : text; + // The standards this asset supports. + standards : vec text; + // The asset symbol, e.g. "ICP" or "BTC". + symbol : text; + // The number of decimals used to format the asset balance. + decimals : nat32; + // Metadata associated with the asset. + metadata : vec AssetMetadata; +}; + // The init configuration for the canister. // // Only used when installing the canister for the first time. @@ -2253,6 +2486,8 @@ type SystemInit = record { fallback_controller : opt principal; // Optional initial accounts to create. accounts : opt vec InitAccountInput; + // Optional initial assets to create. + assets : opt vec InitAssetInput; }; // The upgrade configuration for the canister. @@ -2766,4 +3001,8 @@ service : (opt SystemInstall) -> { http_request : (HttpRequest) -> (HttpResponse) query; // Internal endpoint used by the upgrader canister to notify the station about a failed station upgrade request. notify_failed_station_upgrade : (NotifyFailedStationUpgradeInput) -> (NotifyFailedStationUpgradeResult); + // Get an asset by id. + get_asset : (input : GetAssetInput) -> (GetAssetResult) query; + // List all assets that the caller has access to. + list_assets : (input : ListAssetsInput) -> (ListAssetsResult) query; }; diff --git a/core/station/api/src/account.rs b/core/station/api/src/account.rs index b5a4e67d7..d55c318ce 100644 --- a/core/station/api/src/account.rs +++ b/core/station/api/src/account.rs @@ -14,22 +14,44 @@ pub struct AccountCallerPrivilegesDTO { pub struct AccountDTO { pub id: UuidDTO, pub name: String, - pub address: String, - pub blockchain: String, - pub standard: String, - pub symbol: String, - pub decimals: u32, - pub balance: Option, + pub assets: Vec, + pub addresses: Vec, pub metadata: Vec, pub transfer_request_policy: Option, pub configs_request_policy: Option, pub last_modification_timestamp: String, } +pub type AccountSeedDTO = [u8; 16]; + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct AccountAssetDTO { + pub asset_id: UuidDTO, + pub balance: Option, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct AccountAddressDTO { + pub address: String, + pub format: String, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub enum ChangeAssets { + ReplaceWith { + assets: Vec, + }, + Change { + add_assets: Vec, + remove_assets: Vec, + }, +} + #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct EditAccountOperationInput { pub account_id: UuidDTO, pub name: Option, + pub change_assets: Option, pub read_permission: Option, pub configs_permission: Option, pub transfer_permission: Option, @@ -45,8 +67,7 @@ pub struct EditAccountOperationDTO { #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct AddAccountOperationInput { pub name: String, - pub blockchain: String, - pub standard: String, + pub assets: Vec, pub metadata: Vec, pub read_permission: AllowDTO, pub configs_permission: AllowDTO, @@ -80,9 +101,11 @@ pub struct FetchAccountBalancesInput { #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct AccountBalanceDTO { pub account_id: String, + pub asset_id: String, pub balance: candid::Nat, pub decimals: u32, pub last_update_timestamp: String, + pub query_state: String, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] @@ -94,7 +117,7 @@ pub struct AccountBalanceInfoDTO { #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct FetchAccountBalancesResponse { - pub balances: Vec, + pub balances: Vec>, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/api/src/address_book.rs b/core/station/api/src/address_book.rs index 0438463f1..caa4dcbfe 100644 --- a/core/station/api/src/address_book.rs +++ b/core/station/api/src/address_book.rs @@ -6,6 +6,7 @@ pub struct AddressBookEntryDTO { pub id: UuidDTO, pub address_owner: String, pub address: String, + pub address_format: String, pub blockchain: String, pub labels: Vec, pub metadata: Vec, @@ -29,6 +30,7 @@ pub struct AddAddressBookEntryOperationDTO { pub struct AddAddressBookEntryOperationInput { pub address_owner: String, pub address: String, + pub address_format: String, pub blockchain: String, pub metadata: Vec, pub labels: Vec, @@ -75,6 +77,7 @@ pub struct ListAddressBookEntriesInputDTO { pub blockchain: Option, pub labels: Option>, pub paginate: Option, + pub address_formats: Option>, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/api/src/asset.rs b/core/station/api/src/asset.rs new file mode 100644 index 000000000..b5b649ea0 --- /dev/null +++ b/core/station/api/src/asset.rs @@ -0,0 +1,94 @@ +use candid::CandidType; +use serde::Deserialize; + +use crate::{ChangeMetadataDTO, MetadataDTO, PaginationInput, UuidDTO}; + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct AssetDTO { + /// The asset identifier, which is a UUID. + pub id: UuidDTO, + /// The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + pub blockchain: String, + /// The asset symbol (e.g. `ICP`, `BTC`, `ETH`, etc.) + pub symbol: String, + /// The number of decimal places that the asset supports (e.g. `8` for `BTC`, `18` for `ETH`, etc.) + pub decimals: u32, + // The asset standard that is supported (e.g. `erc20`, etc.), canonically + // represented as a lowercase string with spaces replaced with underscores. + pub standards: Vec, + /// The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) + pub name: String, + /// The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). + pub metadata: Vec, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct AddAssetOperationDTO { + pub asset: Option, + pub input: AddAssetOperationInput, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct AddAssetOperationInput { + pub name: String, + pub blockchain: String, + pub standards: Vec, + pub symbol: String, + pub decimals: u32, + pub metadata: Vec, +} +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct EditAssetOperationDTO { + pub input: EditAssetOperationInput, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct EditAssetOperationInput { + pub asset_id: UuidDTO, + pub name: Option, + pub blockchain: Option, + pub standards: Option>, + pub symbol: Option, + pub change_metadata: Option, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct RemoveAssetOperationDTO { + pub input: RemoveAssetOperationInput, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct RemoveAssetOperationInput { + pub asset_id: UuidDTO, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct ListAssetsInput { + pub paginate: Option, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct ListAssetsResponse { + pub assets: Vec, + pub next_offset: Option, + pub total: u64, + pub privileges: Vec, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct AssetCallerPrivilegesDTO { + pub id: UuidDTO, + pub can_edit: bool, + pub can_delete: bool, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct GetAssetInput { + pub asset_id: UuidDTO, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] +pub struct GetAssetResponse { + pub asset: AssetDTO, + pub privileges: AssetCallerPrivilegesDTO, +} diff --git a/core/station/api/src/capabilities.rs b/core/station/api/src/capabilities.rs index a3e966f78..59b6c1cce 100644 --- a/core/station/api/src/capabilities.rs +++ b/core/station/api/src/capabilities.rs @@ -1,23 +1,6 @@ -use crate::MetadataDTO; +use crate::AssetDTO; use candid::{CandidType, Deserialize}; -#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] -pub struct AssetDTO { - /// The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) - pub blockchain: String, - /// The asset symbol (e.g. `ICP`, `BTC`, `ETH`, etc.) - pub symbol: String, - // The asset standard that is supported (e.g. `erc20`, etc.), canonically - // represented as a lowercase string with spaces replaced with underscores. - pub standard: String, - /// The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) - pub name: String, - /// The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`), - /// also, in the case of non-native assets, it can contain other required - /// information (e.g. `{"address": "0x1234"}`). - pub metadata: Vec, -} - /// The capabilities of the canister. #[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] pub struct CapabilitiesDTO { @@ -27,9 +10,25 @@ pub struct CapabilitiesDTO { pub version: String, /// The list of assets that are supported by the canister (e.g. `ICP`, `BTC`, `ETH`, etc.) pub supported_assets: Vec, + /// The list of blockchains and standards that are supported by the canister (e.g. `ethereum`, `bitcoin`, `icp`, etc.) + pub supported_blockchains: Vec, } #[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] pub struct CapabilitiesResponse { pub capabilities: CapabilitiesDTO, } + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct SupportedBlockchainDTO { + pub blockchain: String, + pub supported_standards: Vec, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct StandardDataDTO { + pub standard: String, + pub required_metadata_fields: Vec, + pub supported_operations: Vec, + pub supported_address_formats: Vec, +} diff --git a/core/station/api/src/lib.rs b/core/station/api/src/lib.rs index 6b1b4e144..4f47b8ad1 100644 --- a/core/station/api/src/lib.rs +++ b/core/station/api/src/lib.rs @@ -48,3 +48,6 @@ pub use resource::*; mod disaster_recovery; pub use disaster_recovery::*; + +mod asset; +pub use asset::*; diff --git a/core/station/api/src/request.rs b/core/station/api/src/request.rs index cfe1a8e97..6a2e8ac39 100644 --- a/core/station/api/src/request.rs +++ b/core/station/api/src/request.rs @@ -3,18 +3,19 @@ use super::{ }; use crate::{ AddAccountOperationDTO, AddAccountOperationInput, AddAddressBookEntryOperationDTO, - AddAddressBookEntryOperationInput, AddUserGroupOperationDTO, AddUserGroupOperationInput, - AddUserOperationDTO, AddUserOperationInput, CallExternalCanisterOperationDTO, - CallExternalCanisterOperationInput, ChangeExternalCanisterOperationDTO, - ChangeExternalCanisterOperationInput, ConfigureExternalCanisterOperationDTO, - ConfigureExternalCanisterOperationInput, CreateExternalCanisterOperationDTO, - CreateExternalCanisterOperationInput, DisplayUserDTO, EditAccountOperationDTO, - EditAddressBookEntryOperationDTO, EditAddressBookEntryOperationInput, - EditPermissionOperationDTO, EditPermissionOperationInput, EditUserGroupOperationDTO, - EditUserGroupOperationInput, EditUserOperationDTO, EditUserOperationInput, - FundExternalCanisterOperationDTO, FundExternalCanisterOperationInput, - ManageSystemInfoOperationDTO, ManageSystemInfoOperationInput, PaginationInput, - RemoveAddressBookEntryOperationDTO, RemoveAddressBookEntryOperationInput, + AddAddressBookEntryOperationInput, AddAssetOperationDTO, AddAssetOperationInput, + AddUserGroupOperationDTO, AddUserGroupOperationInput, AddUserOperationDTO, + AddUserOperationInput, CallExternalCanisterOperationDTO, CallExternalCanisterOperationInput, + ChangeExternalCanisterOperationDTO, ChangeExternalCanisterOperationInput, + ConfigureExternalCanisterOperationDTO, ConfigureExternalCanisterOperationInput, + CreateExternalCanisterOperationDTO, CreateExternalCanisterOperationInput, DisplayUserDTO, + EditAccountOperationDTO, EditAddressBookEntryOperationDTO, EditAddressBookEntryOperationInput, + EditAssetOperationDTO, EditAssetOperationInput, EditPermissionOperationDTO, + EditPermissionOperationInput, EditUserGroupOperationDTO, EditUserGroupOperationInput, + EditUserOperationDTO, EditUserOperationInput, FundExternalCanisterOperationDTO, + FundExternalCanisterOperationInput, ManageSystemInfoOperationDTO, + ManageSystemInfoOperationInput, PaginationInput, RemoveAddressBookEntryOperationDTO, + RemoveAddressBookEntryOperationInput, RemoveAssetOperationDTO, RemoveAssetOperationInput, RemoveUserGroupOperationDTO, RemoveUserGroupOperationInput, RequestEvaluationResultDTO, RequestPolicyRuleDTO, RequestSpecifierDTO, SetDisasterRecoveryOperationDTO, SetDisasterRecoveryOperationInput, SortDirection, SystemUpgradeOperationDTO, @@ -83,6 +84,9 @@ pub enum RequestOperationDTO { EditRequestPolicy(Box), RemoveRequestPolicy(Box), ManageSystemInfo(Box), + AddAsset(Box), + EditAsset(Box), + RemoveAsset(Box), } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] @@ -110,6 +114,9 @@ pub enum RequestOperationInput { EditRequestPolicy(EditRequestPolicyOperationInput), RemoveRequestPolicy(RemoveRequestPolicyOperationInput), ManageSystemInfo(ManageSystemInfoOperationInput), + AddAsset(AddAssetOperationInput), + EditAsset(EditAssetOperationInput), + RemoveAsset(RemoveAssetOperationInput), } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] @@ -137,6 +144,9 @@ pub enum RequestOperationTypeDTO { RemoveRequestPolicy, ManageSystemInfo, ConfigureExternalCanister, + AddAsset, + EditAsset, + RemoveAsset, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] @@ -164,6 +174,9 @@ pub enum ListRequestsOperationTypeDTO { ManageSystemInfo, SetDisasterRecovery, ConfigureExternalCanister(Option), + AddAsset, + EditAsset, + RemoveAsset, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/api/src/request_policy.rs b/core/station/api/src/request_policy.rs index 98001c18f..f48a80b4e 100644 --- a/core/station/api/src/request_policy.rs +++ b/core/station/api/src/request_policy.rs @@ -28,6 +28,9 @@ pub enum RequestSpecifierDTO { EditUserGroup(ResourceIdsDTO), RemoveUserGroup(ResourceIdsDTO), ManageSystemInfo, + AddAsset, + EditAsset(ResourceIdsDTO), + RemoveAsset(ResourceIdsDTO), } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/api/src/resource.rs b/core/station/api/src/resource.rs index f13be8774..eb15823a6 100644 --- a/core/station/api/src/resource.rs +++ b/core/station/api/src/resource.rs @@ -13,6 +13,7 @@ pub enum ResourceDTO { System(SystemResourceActionDTO), User(UserResourceActionDTO), UserGroup(ResourceActionDTO), + Asset(ResourceActionDTO), } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/api/src/system.rs b/core/station/api/src/system.rs index e1d8636f3..9e50d0b16 100644 --- a/core/station/api/src/system.rs +++ b/core/station/api/src/system.rs @@ -1,5 +1,5 @@ use super::TimestampRfc3339; -use crate::{DisasterRecoveryCommitteeDTO, MetadataDTO, Sha256HashDTO, UuidDTO}; +use crate::{AccountSeedDTO, DisasterRecoveryCommitteeDTO, MetadataDTO, Sha256HashDTO, UuidDTO}; use candid::{CandidType, Deserialize, Principal}; use orbit_essentials::types::WasmModuleExtraChunks; @@ -68,9 +68,20 @@ pub enum SystemUpgraderInput { pub struct InitAccountInput { pub id: Option, pub name: String, + pub seed: AccountSeedDTO, + pub assets: Vec, + pub metadata: Vec, +} + +#[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] +pub struct InitAssetInput { + pub id: UuidDTO, + pub name: String, pub blockchain: String, - pub standard: String, + pub standards: Vec, pub metadata: Vec, + pub symbol: String, + pub decimals: u32, } #[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] @@ -87,6 +98,8 @@ pub struct SystemInit { pub fallback_controller: Option, /// Optionally set the initial accounts. pub accounts: Option>, + /// Optionally set the initial accounts. + pub assets: Option>, } #[derive(CandidType, serde::Serialize, Deserialize, Clone, Debug)] diff --git a/core/station/api/src/transfer.rs b/core/station/api/src/transfer.rs index f2f471b78..8389e6235 100644 --- a/core/station/api/src/transfer.rs +++ b/core/station/api/src/transfer.rs @@ -1,5 +1,5 @@ use super::{AccountDTO, TimestampRfc3339}; -use crate::{MetadataDTO, UuidDTO}; +use crate::{AssetDTO, MetadataDTO, UuidDTO}; use candid::{CandidType, Deserialize}; pub type NetworkIdDTO = String; @@ -13,6 +13,8 @@ pub struct NetworkDTO { #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct TransferOperationInput { pub from_account_id: UuidDTO, + pub from_asset_id: UuidDTO, + pub with_standard: String, pub to: String, pub amount: candid::Nat, pub fee: Option, @@ -23,6 +25,7 @@ pub struct TransferOperationInput { #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] pub struct TransferOperationDTO { pub from_account: Option, + pub from_asset: AssetDTO, pub network: NetworkDTO, pub input: TransferOperationInput, pub transfer_id: Option, diff --git a/core/station/api/src/user.rs b/core/station/api/src/user.rs index adff70832..8e1b30585 100644 --- a/core/station/api/src/user.rs +++ b/core/station/api/src/user.rs @@ -114,6 +114,8 @@ pub enum UserPrivilege { CreateExternalCanister, ListExternalCanisters, CallAnyExternalCanister, + ListAssets, + AddAsset, } #[derive(CandidType, serde::Serialize, Deserialize, Debug, Clone)] diff --git a/core/station/impl/Cargo.toml b/core/station/impl/Cargo.toml index e84b4555b..6beb9032f 100644 --- a/core/station/impl/Cargo.toml +++ b/core/station/impl/Cargo.toml @@ -31,6 +31,7 @@ ic-cdk = { workspace = true } ic-cdk-macros = { workspace = true } ic-ledger-types = { workspace = true } ic-stable-structures = { workspace = true } +icrc-ledger-types = { workspace = true } lazy_static = { workspace = true } num-bigint = { workspace = true } serde = { workspace = true, features = ['derive'] } diff --git a/core/station/impl/results.yml b/core/station/impl/results.yml index a6c7ee77d..108226765 100644 --- a/core/station/impl/results.yml +++ b/core/station/impl/results.yml @@ -1,7 +1,7 @@ benches: batch_insert_100_requests: total: - instructions: 224453231 + instructions: 229054294 heap_increase: 0 stable_memory_increase: 96 scopes: {} @@ -13,44 +13,44 @@ benches: scopes: {} find_500_external_canister_policies_from_50k_dataset: total: - instructions: 30909471 + instructions: 28629145 heap_increase: 0 stable_memory_increase: 0 scopes: {} heap_size_of_indexed_request_fields_cache_is_lt_300mib: total: - instructions: 131557138 - heap_increase: 87 + instructions: 195191574 + heap_increase: 85 stable_memory_increase: 0 scopes: {} list_1k_requests: total: - instructions: 98802710 - heap_increase: 7 + instructions: 142128177 + heap_increase: 14 stable_memory_increase: 0 scopes: {} list_external_canisters_with_all_statuses: total: - instructions: 211825288 + instructions: 213226507 heap_increase: 0 stable_memory_increase: 0 scopes: {} repository_find_1k_requests_from_10k_dataset_default_filters: total: - instructions: 94586868 + instructions: 92053986 heap_increase: 17 stable_memory_increase: 0 scopes: {} service_filter_5k_requests_from_100k_dataset: total: - instructions: 686346031 + instructions: 680738365 heap_increase: 106 stable_memory_increase: 16 scopes: {} service_find_all_requests_from_2k_dataset: total: - instructions: 277217390 + instructions: 275726235 heap_increase: 44 stable_memory_increase: 16 scopes: {} -version: 0.1.4 +version: 0.1.8 diff --git a/core/station/impl/src/controllers/asset.rs b/core/station/impl/src/controllers/asset.rs new file mode 100644 index 000000000..1e103cfdc --- /dev/null +++ b/core/station/impl/src/controllers/asset.rs @@ -0,0 +1,78 @@ +use crate::{ + core::middlewares::{authorize, call_context}, + mappers::HelperMapper, + models::resource::{Resource, ResourceAction}, + services::AssetService, +}; +use ic_cdk_macros::query; +use lazy_static::lazy_static; +use orbit_essentials::api::ApiResult; +use orbit_essentials::with_middleware; +use station_api::{ + AssetCallerPrivilegesDTO, GetAssetInput, GetAssetResponse, ListAssetsInput, ListAssetsResponse, +}; + +#[query(name = "get_asset")] +async fn get_asset(input: GetAssetInput) -> ApiResult { + CONTROLLER.get_asset(input).await +} + +#[query(name = "list_assets")] +async fn list_assets(input: ListAssetsInput) -> ApiResult { + CONTROLLER.list_assets(input).await +} + +lazy_static! { + static ref CONTROLLER: AssetController = AssetController::new(AssetService::default()); +} + +#[derive(Debug)] +pub struct AssetController { + asset_service: AssetService, +} + +impl AssetController { + pub fn new(asset_service: AssetService) -> Self { + Self { asset_service } + } + + #[with_middleware(guard = authorize(&call_context(), &[Resource::from(&input)]))] + async fn get_asset(&self, input: GetAssetInput) -> ApiResult { + let ctx = call_context(); + let asset = self + .asset_service + .get(HelperMapper::to_uuid(input.asset_id)?.as_bytes())?; + let privileges = self + .asset_service + .get_caller_privileges_for_asset(&asset.id, &ctx) + .await?; + + Ok(GetAssetResponse { + asset: asset.into(), + privileges: privileges.into(), + }) + } + + #[with_middleware(guard = authorize(&call_context(), &[Resource::Asset(ResourceAction::List)]))] + async fn list_assets(&self, input: ListAssetsInput) -> ApiResult { + let ctx = call_context(); + let result = self.asset_service.list(input, Some(&ctx))?; + let mut privileges = Vec::new(); + + for asset in &result.items { + let asset_privileges = self + .asset_service + .get_caller_privileges_for_asset(&asset.id, &ctx) + .await?; + + privileges.push(AssetCallerPrivilegesDTO::from(asset_privileges)); + } + + Ok(ListAssetsResponse { + assets: result.items.into_iter().map(Into::into).collect(), + next_offset: result.next_offset, + total: result.total, + privileges, + }) + } +} diff --git a/core/station/impl/src/controllers/capabilities.rs b/core/station/impl/src/controllers/capabilities.rs index a3cf75999..3189bbb29 100644 --- a/core/station/impl/src/controllers/capabilities.rs +++ b/core/station/impl/src/controllers/capabilities.rs @@ -1,16 +1,17 @@ use crate::{ core::{ middlewares::{authorize, call_context}, - read_system_info, ASSETS, + read_system_info, SUPPORTED_BLOCKCHAINS, }, models::resource::{Resource, SystemResourceAction}, + repositories::ASSET_REPOSITORY, SYSTEM_VERSION, }; use ic_cdk_macros::query; use lazy_static::lazy_static; -use orbit_essentials::api::ApiResult; use orbit_essentials::with_middleware; -use station_api::{CapabilitiesDTO, CapabilitiesResponse}; +use orbit_essentials::{api::ApiResult, repository::Repository}; +use station_api::{CapabilitiesDTO, CapabilitiesResponse, StandardDataDTO, SupportedBlockchainDTO}; #[query(name = "capabilities")] async fn capabilities() -> ApiResult { @@ -32,14 +33,42 @@ impl CapabilitiesController { #[with_middleware(guard = authorize(&call_context(), &[Resource::System(SystemResourceAction::Capabilities)]))] async fn capabilities(&self) -> ApiResult { - let assets = ASSETS.with(|asset| asset.borrow().clone()); let system = read_system_info(); Ok(CapabilitiesResponse { capabilities: CapabilitiesDTO { name: system.get_name().to_string(), version: SYSTEM_VERSION.to_string(), - supported_assets: assets.into_iter().map(|asset| asset.into()).collect(), + supported_assets: ASSET_REPOSITORY + .list() + .into_iter() + .map(|asset| asset.into()) + .collect(), + supported_blockchains: SUPPORTED_BLOCKCHAINS + .iter() + .map(|suported_blockchain| SupportedBlockchainDTO { + blockchain: suported_blockchain.blockchain.to_string(), + supported_standards: suported_blockchain + .supported_standards + .iter() + .map(|standard| StandardDataDTO { + required_metadata_fields: standard.get_required_metadata(), + standard: standard.to_string(), + supported_operations: standard + .get_supported_operations() + .iter() + .map(|operation| operation.to_string()) + .collect(), + supported_address_formats: standard + .get_info() + .address_formats + .iter() + .map(|format| format.to_string()) + .collect(), + }) + .collect(), + }) + .collect(), }, }) } diff --git a/core/station/impl/src/controllers/mod.rs b/core/station/impl/src/controllers/mod.rs index 420facaa0..cb70a4d3e 100644 --- a/core/station/impl/src/controllers/mod.rs +++ b/core/station/impl/src/controllers/mod.rs @@ -42,6 +42,9 @@ pub use user_group::*; mod http; pub use http::*; +mod asset; +pub use asset::*; + #[cfg(test)] mod tests { use orbit_essentials::api::*; diff --git a/core/station/impl/src/controllers/system.rs b/core/station/impl/src/controllers/system.rs index d66cfa7bf..54385f1aa 100644 --- a/core/station/impl/src/controllers/system.rs +++ b/core/station/impl/src/controllers/system.rs @@ -6,7 +6,7 @@ use crate::{ errors::AuthorizationError, migration, models::resource::{Resource, SystemResourceAction}, - services::{SystemService, SYSTEM_SERVICE}, + services::{SystemService, INITIALIZING, SYSTEM_SERVICE}, SYSTEM_VERSION, }; use ic_cdk_macros::{post_upgrade, query, update}; @@ -27,6 +27,10 @@ fn set_certified_data_for_skip_certification() { #[cfg(any(not(feature = "canbench"), test))] #[ic_cdk_macros::init] async fn initialize(input: Option) { + INITIALIZING.with_borrow_mut(|initializing| { + *initializing = true; + }); + set_certified_data_for_skip_certification(); match input { Some(SystemInstall::Init(input)) => CONTROLLER.initialize(input).await, @@ -57,6 +61,10 @@ pub async fn mock_init() { #[post_upgrade] async fn post_upgrade(input: Option) { + INITIALIZING.with_borrow_mut(|initializing| { + *initializing = true; + }); + // Runs the migrations for the canister to ensure the stable memory schema is up-to-date // // WARNING: This needs to be done before any other access to stable memory is done, this is because @@ -168,9 +176,11 @@ mod tests { #[tokio::test] async fn apply_migration_should_migrate_stable_memory_version() { + let base_stable_memory_version = STABLE_MEMORY_VERSION - 1; + let mut system_info = SystemInfo::new(Principal::management_canister(), Vec::new()); - system_info.set_stable_memory_version(0); + system_info.set_stable_memory_version(base_stable_memory_version); write_system_info(system_info); @@ -191,7 +201,7 @@ mod tests { REQUEST_REPOSITORY.insert(request.to_key(), request.clone()); - system_info.set_stable_memory_version(0); + system_info.set_stable_memory_version(base_stable_memory_version); system_info.set_change_canister_request(request.id); write_system_info(system_info); diff --git a/core/station/impl/src/core/assets.rs b/core/station/impl/src/core/assets.rs deleted file mode 100644 index 5d5f9ce30..000000000 --- a/core/station/impl/src/core/assets.rs +++ /dev/null @@ -1,16 +0,0 @@ -use crate::models::{Asset, Blockchain, BlockchainStandard, Metadata}; -use std::{cell::RefCell, collections::HashSet}; - -thread_local! { - /// The list of assets that are supported by the canister (e.g. `ICP`, `BTC`, `ETH`, etc.) - pub static ASSETS: RefCell> = - RefCell::new(vec![ - Asset { - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, - symbol: "ICP".to_string(), - name: "Internet Computer".to_string(), - metadata: Metadata::default(), - }, - ].into_iter().collect()); -} diff --git a/core/station/impl/src/core/init.rs b/core/station/impl/src/core/init.rs index d99127199..8fa894b29 100644 --- a/core/station/impl/src/core/init.rs +++ b/core/station/impl/src/core/init.rs @@ -164,7 +164,28 @@ lazy_static! { ( Allow::user_groups(vec![*ADMIN_GROUP_ID]), Resource::ExternalCanister(ExternalCanisterResourceAction::Fund(ExternalCanisterId::Any)), - ) + ), + // assets + ( + Allow::user_groups(vec![*ADMIN_GROUP_ID]), + Resource::Asset(ResourceAction::Create), + ), + ( + Allow::authenticated(), + Resource::Asset(ResourceAction::List), + ), + ( + Allow::authenticated(), + Resource::Asset(ResourceAction::Read(ResourceId::Any)), + ), + ( + Allow::user_groups(vec![*ADMIN_GROUP_ID]), + Resource::Asset(ResourceAction::Update(ResourceId::Any)), + ), + ( + Allow::user_groups(vec![*ADMIN_GROUP_ID]), + Resource::Asset(ResourceAction::Delete(ResourceId::Any)), + ), ]; } @@ -252,5 +273,18 @@ pub fn default_policies(admin_quorum: u16) -> Vec<(RequestSpecifier, RequestPoli RequestSpecifier::FundExternalCanister(ExternalCanisterId::Any), RequestPolicyRule::Quorum(UserSpecifier::Group(vec![*ADMIN_GROUP_ID]), admin_quorum), ), + // create, edit, and remove assets + ( + RequestSpecifier::AddAsset, + RequestPolicyRule::Quorum(UserSpecifier::Group(vec![*ADMIN_GROUP_ID]), admin_quorum), + ), + ( + RequestSpecifier::EditAsset(ResourceIds::Any), + RequestPolicyRule::Quorum(UserSpecifier::Group(vec![*ADMIN_GROUP_ID]), admin_quorum), + ), + ( + RequestSpecifier::RemoveAsset(ResourceIds::Any), + RequestPolicyRule::Quorum(UserSpecifier::Group(vec![*ADMIN_GROUP_ID]), admin_quorum), + ), ] } diff --git a/core/station/impl/src/core/memory.rs b/core/station/impl/src/core/memory.rs index 5c9bd06d8..8ff01933c 100644 --- a/core/station/impl/src/core/memory.rs +++ b/core/station/impl/src/core/memory.rs @@ -17,6 +17,7 @@ pub const TRANSFER_MEMORY_ID: MemoryId = MemoryId::new(4); pub const UNIQUE_INDEX_MEMORY_ID: MemoryId = MemoryId::new(5); // new pub const TRANSFER_ACCOUNT_INDEX_MEMORY_ID: MemoryId = MemoryId::new(6); pub const REQUEST_MEMORY_ID: MemoryId = MemoryId::new(7); +pub const ASSET_MEMORY_ID: MemoryId = MemoryId::new(8); pub const NOTIFICATION_MEMORY_ID: MemoryId = MemoryId::new(11); pub const NOTIFICATION_USER_INDEX_MEMORY_ID: MemoryId = MemoryId::new(12); pub const TRANSFER_STATUS_INDEX_MEMORY_ID: MemoryId = MemoryId::new(13); @@ -37,7 +38,7 @@ thread_local! { // The memory manager is used for simulating multiple memories. Given a `MemoryId` it can // return a memory that can be used by stable structures. - static MEMORY_MANAGER: RefCell> = + pub static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init_with_bucket_size(managed_memory(), STABLE_MEMORY_BUCKET_SIZE)); } diff --git a/core/station/impl/src/core/metrics.rs b/core/station/impl/src/core/metrics.rs index 4294d35c0..908b5285a 100644 --- a/core/station/impl/src/core/metrics.rs +++ b/core/station/impl/src/core/metrics.rs @@ -1,8 +1,9 @@ +use crate::core::ic_cdk::api::print; use crate::{ - models::{Account, AddressBookEntry, Request, RequestPolicy, Transfer, User, UserGroup}, + models::{Account, AddressBookEntry, Asset, Request, RequestPolicy, Transfer, User, UserGroup}, repositories::{ request_policy::REQUEST_POLICY_REPOSITORY, ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, - USER_GROUP_REPOSITORY, USER_REPOSITORY, + ASSET_REPOSITORY, USER_GROUP_REPOSITORY, USER_REPOSITORY, }, SERVICE_NAME, }; @@ -15,6 +16,7 @@ use orbit_essentials::{ repository::Repository, }; use std::{cell::RefCell, collections::BTreeMap, rc::Rc}; +use uuid::Uuid; use super::observer::Observer; @@ -33,6 +35,13 @@ thread_local! { Rc::new(RefCell::new(MetricTotalUserGroups)), ]; + /// A collection of asset related metrics. + /// + /// This list should be updated with new asset metrics as they are added. + pub static ASSET_METRICS: Vec>>> = vec![ + Rc::new(RefCell::new(MetricTotalAssets)), + ]; + /// A collection of account related metrics. /// /// This list should be updated with new account metrics as they are added. @@ -77,6 +86,7 @@ pub fn recompute_metrics() { let users = USER_REPOSITORY.list(); let user_groups = USER_GROUP_REPOSITORY.list(); let accounts = ACCOUNT_REPOSITORY.list(); + let assets = ASSET_REPOSITORY.list(); // To avoid deserialize all the data, we can use the repository length to get the total number of entries of // simple gauge metrics. @@ -95,6 +105,12 @@ pub fn recompute_metrics() { .for_each(|metric| metric.borrow_mut().recalculate(&user_groups)) }); + ASSET_METRICS.with(|metrics| { + metrics + .iter() + .for_each(|metric| metric.borrow_mut().recalculate(&assets)) + }); + ACCOUNT_METRICS.with(|metrics| { metrics .iter() @@ -235,6 +251,30 @@ impl ApplicationMetric for MetricTotalUserGroups { self.dec(SERVICE_NAME, &labels! { "status" => "active" }); } } +/// Metric for the total number of assets. +pub struct MetricTotalAssets; + +impl ApplicationGaugeMetric for MetricTotalAssets {} + +impl ApplicationMetric for MetricTotalAssets { + fn name(&self) -> &'static str { + "total_assets" + } + + fn help(&self) -> &'static str { + "The total number of assets." + } + + fn sum(&mut self, _: &Asset, previous: Option<&Asset>) { + if previous.is_none() { + self.inc(SERVICE_NAME); + } + } + + fn sub(&mut self, _: &Asset) { + self.dec(SERVICE_NAME); + } +} /// Metric for the number of transfers that have been created. pub struct MetricTotalTranfers; @@ -315,17 +355,33 @@ impl ApplicationMetric for MetricAssetsTotalBalance { let mut labeled_totals = BTreeMap::new(); for account in accounts { - let label_key = ( - account.blockchain.to_string().clone(), - account.symbol.clone().to_lowercase(), - ); + for account_asset in &account.assets { + let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) else { + print(format!( + "Asset `{}` not found in account `{}`", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(account.id).hyphenated() + )); + continue; + }; + + let label_key = ( + asset.blockchain.to_string().clone(), + asset.symbol.clone().to_lowercase(), + ); + + let current_total = labeled_totals.get(&label_key).unwrap_or(&0.0); - let current_total = labeled_totals.get(&label_key).unwrap_or(&0.0); - let balance = account.balance.clone().map(|b| b.to_u64()).unwrap_or(0u64); + let balance = account_asset + .balance + .clone() + .map(|b| b.to_u64()) + .unwrap_or(0u64); - let formatted_balance = amount_to_f64(balance as i128, account.decimals); + let formatted_balance = amount_to_f64(balance as i128, asset.decimals); - labeled_totals.insert(label_key, current_total + formatted_balance); + labeled_totals.insert(label_key, current_total + formatted_balance); + } } for ((blockchain, symbol), total) in labeled_totals.into_iter() { @@ -338,39 +394,66 @@ impl ApplicationMetric for MetricAssetsTotalBalance { } fn sum(&mut self, current: &Account, previous: Option<&Account>) { - let blockchain = current.blockchain.to_string(); - let symbol = current.symbol.clone().to_lowercase(); - let account_labels = - labels! { "blockchain" => blockchain.as_str(), "symbol" => symbol.as_str() }; + if let Some(previous) = previous { + self.sub(previous); + } - let balance = current.balance.clone().map(|b| b.to_u64()).unwrap_or(0u64); + for account_asset in ¤t.assets { + let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) else { + print(format!( + "Asset `{}` not found in account `{}`", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(current.id).hyphenated() + )); - let previous_balance = previous - .and_then(|p| p.balance.clone().map(|b| b.to_u64())) - .unwrap_or(0u64); + continue; + }; - let diff_balance = balance as i128 - previous_balance as i128; - let current_total = self.get(SERVICE_NAME, &account_labels); + let blockchain = asset.blockchain.to_string(); + let symbol = asset.symbol.clone().to_lowercase(); - let formatted_balance = amount_to_f64(diff_balance, current.decimals); - let new_total = current_total + formatted_balance; + let account_labels = + labels! { "blockchain" => blockchain.as_str(), "symbol" => symbol.as_str() }; - self.set(SERVICE_NAME, &account_labels, new_total.max(0.0)); - } + let balance = account_asset + .balance + .clone() + .map(|b| b.to_u64()) + .unwrap_or(0u64); - fn sub(&mut self, current: &Account) { - let blockchain = current.blockchain.to_string(); - let symbol = current.symbol.clone().to_lowercase(); - let account_labels = - labels! { "blockchain" => blockchain.as_str(), "symbol" => symbol.as_str() }; + let current_total = self.get(SERVICE_NAME, &account_labels); - let balance = current.balance.clone().map(|b| b.to_u64()).unwrap_or(0u64); + let formatted_balance = amount_to_f64(balance as i128, asset.decimals); - let formatted_balance = amount_to_f64(balance as i128, current.decimals); - let current_total = self.get(SERVICE_NAME, &account_labels); + let new_total = current_total + formatted_balance; - let new_total = current_total - formatted_balance; - self.set(SERVICE_NAME, &account_labels, new_total.max(0.0)); + self.set(SERVICE_NAME, &account_labels, new_total.max(0.0)); + } + } + + fn sub(&mut self, current: &Account) { + for account_asset in ¤t.assets { + let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) else { + continue; + }; + let blockchain = asset.blockchain.to_string(); + let symbol = asset.symbol.clone().to_lowercase(); + + let account_labels = + labels! { "blockchain" => blockchain.as_str(), "symbol" => symbol.as_str() }; + + let balance = account_asset + .balance + .clone() + .map(|b| b.to_u64()) + .unwrap_or(0u64); + + let formatted_balance = amount_to_f64(balance as i128, asset.decimals); + let current_total = self.get(SERVICE_NAME, &account_labels); + + let new_total = current_total - formatted_balance; + self.set(SERVICE_NAME, &account_labels, new_total.max(0.0)); + } } } @@ -464,14 +547,15 @@ mod tests { use crate::{ models::{ account_test_utils::mock_account, - address_book_entry_test_utils::mock_address_book_entry, + address_book_entry_test_utils::mock_address_book_entry, asset_test_utils::mock_asset, request_policy_test_utils::mock_request_policy, request_test_utils::mock_request, transfer_test_utils::mock_transfer, user_group_test_utils, user_test_utils::mock_user, - AccountBalance, Blockchain, RequestStatus, TransferStatus, UserStatus, + AccountAsset, AccountBalance, Blockchain, RequestStatus, TransferStatus, UserStatus, }, repositories::{REQUEST_REPOSITORY, TRANSFER_REPOSITORY}, }; use candid::Nat; + use orbit_essentials::model::ModelKey; #[test] fn test_total_users_metric() { @@ -513,9 +597,12 @@ mod tests { #[test] fn test_total_accounts_metric() { let mut account = mock_account(); - account.blockchain = Blockchain::InternetComputer; - account.symbol = "ICP".to_string(); - + let asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + account.assets = vec![AccountAsset { + asset_id: asset.key(), + balance: None, + }]; ACCOUNT_REPOSITORY.insert(account.to_key(), account); assert_eq!( @@ -524,9 +611,14 @@ mod tests { ); let mut account = mock_account(); + let asset = mock_asset(); + + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + account.assets = vec![AccountAsset { + asset_id: asset.key(), + balance: None, + }]; account.name = "Test2".to_string(); - account.blockchain = Blockchain::InternetComputer; - account.symbol = "ICP".to_string(); ACCOUNT_REPOSITORY.insert(account.to_key(), account); @@ -591,13 +683,15 @@ mod tests { let blockchain_name = Blockchain::InternetComputer.to_string(); let mut account = mock_account(); - account.blockchain = Blockchain::InternetComputer; - account.symbol = "icp".to_string(); - account.balance = Some(AccountBalance { - balance: Nat::from(1_000_000_000u64), - last_modification_timestamp: 0, - }); - account.decimals = 8; + let asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + account.assets = vec![AccountAsset { + asset_id: asset.key(), + balance: Some(AccountBalance { + balance: Nat::from(1_000_000_000u64), + last_modification_timestamp: 0, + }), + }]; ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); @@ -610,13 +704,15 @@ mod tests { ); let mut account = mock_account(); - account.blockchain = Blockchain::InternetComputer; - account.symbol = "icp".to_string(); - account.balance = Some(AccountBalance { - balance: Nat::from(10_000_000_000u64), - last_modification_timestamp: 0, - }); - account.decimals = 8; + let asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + account.assets = vec![AccountAsset { + asset_id: asset.key(), + balance: Some(AccountBalance { + balance: Nat::from(10_000_000_000u64), + last_modification_timestamp: 0, + }), + }]; ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); @@ -628,10 +724,13 @@ mod tests { 110.00000000 ); - account.balance = Some(AccountBalance { - balance: Nat::from(100_000_000u64), - last_modification_timestamp: 0, - }); + account.assets = vec![AccountAsset { + asset_id: asset.key(), + balance: Some(AccountBalance { + balance: Nat::from(100_000_000u64), + last_modification_timestamp: 0, + }), + }]; ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); diff --git a/core/station/impl/src/core/mod.rs b/core/station/impl/src/core/mod.rs index b8567168c..32c75a4f6 100644 --- a/core/station/impl/src/core/mod.rs +++ b/core/station/impl/src/core/mod.rs @@ -1,8 +1,5 @@ //! Core utility features for the canister. -mod assets; -pub use assets::*; - mod constants; pub use constants::*; @@ -18,7 +15,9 @@ pub use call_context::*; pub mod middlewares; pub mod observer; +pub mod standards; pub mod validation; +pub use standards::*; #[cfg(not(test))] pub use orbit_essentials::cdk as ic_cdk; diff --git a/core/station/impl/src/core/request.rs b/core/station/impl/src/core/request.rs index 98a3b287c..9464e58e2 100644 --- a/core/station/impl/src/core/request.rs +++ b/core/station/impl/src/core/request.rs @@ -404,9 +404,9 @@ mod tests { request_test_utils::mock_request, resource::ResourceIds, user_test_utils::{self, mock_user}, - Account, AccountKey, AddUserGroupOperation, AddUserGroupOperationInput, Blockchain, - BlockchainStandard, EvaluatedRequestPolicyRule, Metadata, MetadataItem, Percentage, - RequestOperation, RequestPolicy, RequestStatus, ADMIN_GROUP_ID, + Account, AccountKey, AddUserGroupOperation, AddUserGroupOperationInput, + EvaluatedRequestPolicyRule, Metadata, MetadataItem, Percentage, RequestOperation, + RequestPolicy, RequestStatus, ADMIN_GROUP_ID, }, repositories::{ request_policy::REQUEST_POLICY_REPOSITORY, ACCOUNT_REPOSITORY, @@ -627,13 +627,10 @@ mod tests { AccountKey { id: [1; 16] }, Account { id: [1; 16], - blockchain: Blockchain::InternetComputer, - address: "a".to_owned(), - standard: BlockchainStandard::Native, - symbol: "S".to_owned(), - decimals: 1, + addresses: vec![], + assets: vec![], + seed: [0; 16], name: "test".to_owned(), - balance: None, metadata: Metadata::default(), transfer_request_policy_id: None, configs_request_policy_id: None, diff --git a/core/station/impl/src/core/standards.rs b/core/station/impl/src/core/standards.rs new file mode 100644 index 000000000..fd1c6a383 --- /dev/null +++ b/core/station/impl/src/core/standards.rs @@ -0,0 +1,17 @@ +use lazy_static::lazy_static; + +use crate::models::{Blockchain, TokenStandard}; + +pub struct SupportedBlockchain { + pub blockchain: Blockchain, + pub supported_standards: Vec, +} + +lazy_static! { + pub static ref SUPPORTED_BLOCKCHAINS: Vec = { + vec![SupportedBlockchain { + blockchain: Blockchain::InternetComputer, + supported_standards: vec![TokenStandard::InternetComputerNative, TokenStandard::ICRC1], + }] + }; +} diff --git a/core/station/impl/src/core/validation.rs b/core/station/impl/src/core/validation.rs index cbb2f4df7..39c738e71 100644 --- a/core/station/impl/src/core/validation.rs +++ b/core/station/impl/src/core/validation.rs @@ -5,24 +5,20 @@ use std::cell::RefCell; use crate::{ errors::{ExternalCanisterValidationError, RecordValidationError}, - factories::blockchains::InternetComputer, models::{ resource::{Resource, ResourceId, ResourceIds}, - AccountKey, AddressBookEntryKey, NotificationKey, RequestKey, UserKey, + AccountKey, AddressBookEntryKey, NotificationKey, RequestKey, TokenStandard, UserKey, }, repositories::{ permission::PERMISSION_REPOSITORY, request_policy::REQUEST_POLICY_REPOSITORY, - ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, NOTIFICATION_REPOSITORY, REQUEST_REPOSITORY, - USER_GROUP_REPOSITORY, USER_REPOSITORY, + ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, ASSET_REPOSITORY, NOTIFICATION_REPOSITORY, + REQUEST_REPOSITORY, USER_GROUP_REPOSITORY, USER_REPOSITORY, }, services::SYSTEM_SERVICE, }; use candid::Principal; use ic_stable_structures::{Memory, Storable}; -#[cfg(not(test))] -pub use orbit_essentials::cdk as ic_cdk; -#[cfg(test)] -pub use orbit_essentials::cdk::mocks as ic_cdk; + use orbit_essentials::repository::Repository; use orbit_essentials::types::UUID; use uuid::Uuid; @@ -199,9 +195,18 @@ impl EnsureExternalCanister { pub fn is_external_canister( principal: Principal, ) -> Result<(), ExternalCanisterValidationError> { - if principal == Principal::management_canister() - || principal == ic_cdk::api::id() - || principal == InternetComputer::ledger_canister_id() + // Check if the target canister is a ledger canister of an asset. + let principal_str = principal.to_text(); + let is_ledger_canister_id = ASSET_REPOSITORY.list().iter().any(|asset| { + asset + .metadata + .get(TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID) + .map_or(false, |canister_id| canister_id == principal_str) + }); + + if is_ledger_canister_id + || principal == Principal::management_canister() + || principal == crate::core::ic_cdk::api::id() || principal == SYSTEM_SERVICE.get_upgrader_canister_id() { return Err(ExternalCanisterValidationError::InvalidExternalCanister { principal }); @@ -227,3 +232,60 @@ impl EnsureIdExists for EnsureNotification { } impl EnsureResourceIdExists for EnsureNotification {} + +pub struct EnsureAsset {} + +impl EnsureIdExists for EnsureAsset { + fn id_exists(id: &UUID) -> Result<(), RecordValidationError> { + ensure_entry_exists(ASSET_REPOSITORY.to_owned(), *id).ok_or( + RecordValidationError::NotFound { + model_name: "Asset".to_string(), + id: Uuid::from_bytes(*id).hyphenated().to_string(), + }, + ) + } +} + +impl EnsureResourceIdExists for EnsureAsset {} + +#[cfg(test)] +mod test { + use std::collections::BTreeMap; + + use candid::Principal; + use orbit_essentials::{model::ModelKey, repository::Repository}; + + use crate::{ + core::test_utils::init_canister_system, + models::{asset_test_utils::mock_asset, TokenStandard}, + repositories::ASSET_REPOSITORY, + }; + + use super::EnsureExternalCanister; + + #[test] + fn test_is_external_canister() { + init_canister_system(); + + let principal = Principal::from_slice(&[1; 29]); + + let is_external_canister = EnsureExternalCanister::is_external_canister(principal); + assert!(is_external_canister.is_ok()); + + let mut asset = mock_asset(); + + asset + .metadata + .change(crate::models::ChangeMetadata::OverrideSpecifiedBy( + BTreeMap::from([( + TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID.to_string(), + principal.to_text(), + )]), + )); + + ASSET_REPOSITORY.insert(asset.key(), asset); + + let is_external_canister = EnsureExternalCanister::is_external_canister(principal); + assert!(is_external_canister.is_err()); + } +} diff --git a/core/station/impl/src/errors/account.rs b/core/station/impl/src/errors/account.rs index 77c0ae8b7..2dc117456 100644 --- a/core/station/impl/src/errors/account.rs +++ b/core/station/impl/src/errors/account.rs @@ -8,6 +8,9 @@ pub enum AccountError { /// The requested account was not found. #[error(r#"The requested account was not found."#)] AccountNotFound { id: String }, + /// The associated asset does not exist. + #[error(r#"The associated asset `{id}` does not exist."#)] + AssetDoesNotExist { id: String }, /// The given blockchain is unknown to the system. #[error(r#"The given blockchain is unknown to the system."#)] UnknownBlockchain { blockchain: String }, @@ -22,6 +25,20 @@ pub enum AccountError { r#"The account address is out of range, it must be between {min_length} and {max_length}."# )] InvalidAddressLength { min_length: u8, max_length: u8 }, + /// The account name is out of range. + #[error( + r#"The account name is out of range, it must be between {min_length} and {max_length}."# + )] + InvalidNameLength { min_length: u8, max_length: u8 }, + /// The address format is unknown to the system. + #[error(r#"The given address format is unknown to the system."#)] + UnknownAddressFormat { address_format: String }, + /// The address is invalid. + #[error(r#"The given address {address} does not comply with {address_format}"#)] + InvalidAddress { + address: String, + address_format: String, + }, /// The account owners selection is out of range. #[error(r#"The account owners selection is out of range, it must be between {min_owners} and {max_owners}."#)] InvalidOwnersRange { min_owners: u8, max_owners: u8 }, diff --git a/core/station/impl/src/errors/asset.rs b/core/station/impl/src/errors/asset.rs new file mode 100644 index 000000000..cbf91cace --- /dev/null +++ b/core/station/impl/src/errors/asset.rs @@ -0,0 +1,102 @@ +use orbit_essentials::api::DetailableError; +use std::collections::HashMap; +use thiserror::Error; + +/// Container for asset errors. +#[derive(Error, Debug, Eq, PartialEq, Clone)] +pub enum AssetError { + /// The asset was not found. + #[error("The asset with id {id} was not found.")] + NotFound { + /// The asset id. + id: String, + }, + /// Invalid decimals value. + #[error(r#"Decimals must be between {min} and {max}."#)] + InvalidDecimals { min: u32, max: u32 }, + /// Invalid name length. + #[error(r#"Name must be between {min_length} and {max_length}."#)] + InvalidNameLength { min_length: u16, max_length: u16 }, + /// Invalid symbol length. + #[error(r#"Symbol must be between {min_length} and {max_length}."#)] + InvalidSymbolLength { min_length: u16, max_length: u16 }, + /// Invalid symbol. + #[error(r#"Symbol must contain only alphanumeric characters."#)] + InvalidSymbol, + /// The given blockchain is unknown to the system. + #[error(r#"The given blockchain is unknown to the system."#)] + UnknownBlockchain { blockchain: String }, + /// The given token standard is unknown to the system. + #[error(r#"The given token standard is unknown to the system."#)] + UnknownTokenStandard { token_standard: String }, + /// The asset has failed validation. + #[error(r#"The account has failed validation."#)] + ValidationError { info: String }, + /// The asset is in use. + #[error(r#"The asset is used by {resource} `{id}`"#)] + AssetInUse { id: String, resource: String }, + /// The asset is not unique. + #[error(r#"The asset already exists."#)] + AlreadyExists { + /// The asset symbol. + symbol: String, + /// The asset blockchain. + blockchain: String, + }, +} + +impl DetailableError for AssetError { + fn details(&self) -> Option> { + let mut details = HashMap::new(); + match self { + AssetError::UnknownBlockchain { blockchain } => { + details.insert("blockchain".to_string(), blockchain.to_string()); + Some(details) + } + AssetError::UnknownTokenStandard { token_standard } => { + details.insert("token_standard".to_string(), token_standard.to_string()); + Some(details) + } + AssetError::ValidationError { info } => { + details.insert("info".to_string(), info.to_string()); + Some(details) + } + AssetError::InvalidDecimals { min, max } => { + details.insert("min".to_string(), min.to_string()); + details.insert("max".to_string(), max.to_string()); + Some(details) + } + AssetError::InvalidNameLength { + min_length, + max_length, + } => { + details.insert("min_length".to_string(), min_length.to_string()); + details.insert("max_length".to_string(), max_length.to_string()); + Some(details) + } + AssetError::InvalidSymbol => Some(details), + AssetError::InvalidSymbolLength { + min_length, + max_length, + } => { + details.insert("min_length".to_string(), min_length.to_string()); + details.insert("max_length".to_string(), max_length.to_string()); + Some(details) + } + AssetError::NotFound { id } => { + details.insert("id".to_string(), id.to_string()); + Some(details) + } + AssetError::AlreadyExists { symbol, blockchain } => { + details.insert("symbol".to_string(), symbol.to_string()); + details.insert("blockchain".to_string(), blockchain.to_string()); + Some(details) + } + AssetError::AssetInUse { id, resource } => { + details.insert("id".to_string(), id.to_string()); + details.insert("resource".to_string(), resource.to_string()); + Some(details) + } + } + } +} diff --git a/core/station/impl/src/errors/blockchain_api.rs b/core/station/impl/src/errors/blockchain_api.rs index 884028534..938ab4efa 100644 --- a/core/station/impl/src/errors/blockchain_api.rs +++ b/core/station/impl/src/errors/blockchain_api.rs @@ -5,9 +5,18 @@ use thiserror::Error; /// Container for blockchain api errors. #[derive(Error, Debug, Eq, PartialEq, Clone)] pub enum BlockchainApiError { - /// Failed to fetch latest account balance from the asset blockchain. - #[error(r#"Failed to fetch latest account balance from the asset blockchain."#)] - FetchBalanceFailed { account_id: String }, + /// Failed to fetch latest asset balance. + #[error(r#"Failed to fetch latest asset balance."#)] + FetchBalanceFailed { asset_id: String, info: String }, + /// Missing metadata key. + #[error(r#"Metadata '{key}' not found."#)] + MissingMetadata { key: String }, + /// Invalid metadata value. + #[error(r#"Metadata data value for key '{key}'"#)] + InvalidMetadata { key: String, value: String }, + /// Invalid address format. + #[error(r#"Invalid address format. Found {found}, expected {expected}"#)] + InvalidAddressFormat { found: String, expected: String }, /// The transaction failed to be submitted. #[error(r#"The transaction failed to be submitted."#)] TransactionSubmitFailed { info: String }, @@ -17,14 +26,21 @@ pub enum BlockchainApiError { /// The to address is invalid. #[error("The to address '{address}' is invalid: {error}")] InvalidToAddress { address: String, error: String }, + /// Missing asset. + #[error(r#"Asset id '{asset_id}' not found."#)] + MissingAsset { asset_id: String }, } impl DetailableError for BlockchainApiError { fn details(&self) -> Option> { let mut details = HashMap::new(); match self { - BlockchainApiError::FetchBalanceFailed { account_id } => { + BlockchainApiError::FetchBalanceFailed { + asset_id: account_id, + info, + } => { details.insert("account_id".to_string(), account_id.to_string()); + details.insert("info".to_string(), info.to_string()); Some(details) } BlockchainApiError::TransactionSubmitFailed { info } => { @@ -40,6 +56,24 @@ impl DetailableError for BlockchainApiError { details.insert("error".to_string(), error.to_string()); Some(details) } + BlockchainApiError::InvalidAddressFormat { found, expected } => { + details.insert("found".to_string(), found.to_string()); + details.insert("expected".to_string(), expected.to_string()); + Some(details) + } + BlockchainApiError::MissingMetadata { key } => { + details.insert("key".to_string(), key.to_string()); + Some(details) + } + BlockchainApiError::InvalidMetadata { key, value } => { + details.insert("key".to_string(), key.to_string()); + details.insert("value".to_string(), value.to_string()); + Some(details) + } + BlockchainApiError::MissingAsset { asset_id } => { + details.insert("asset_id".to_string(), asset_id.to_string()); + Some(details) + } } } } diff --git a/core/station/impl/src/errors/factory.rs b/core/station/impl/src/errors/factory.rs index 675f889ca..6104fe116 100644 --- a/core/station/impl/src/errors/factory.rs +++ b/core/station/impl/src/errors/factory.rs @@ -6,22 +6,15 @@ use thiserror::Error; #[derive(Error, Debug, Eq, PartialEq, Clone)] pub enum FactoryError { /// The selected account is not yet supported by the system. - #[error(r#"The selected account is not yet supported by the system."#)] - UnsupportedBlockchainAccount { - blockchain: String, - standard: String, - }, + #[error(r#"The selected blockchain is not yet supported by the system."#)] + UnsupportedBlockchain { blockchain: String }, } impl DetailableError for FactoryError { fn details(&self) -> Option> { let mut details = HashMap::new(); - let FactoryError::UnsupportedBlockchainAccount { - blockchain, - standard, - } = self; + let FactoryError::UnsupportedBlockchain { blockchain } = self; details.insert("blockchain".to_string(), blockchain.to_string()); - details.insert("standard".to_string(), standard.to_string()); Some(details) } diff --git a/core/station/impl/src/errors/mod.rs b/core/station/impl/src/errors/mod.rs index 346359758..f12035cae 100644 --- a/core/station/impl/src/errors/mod.rs +++ b/core/station/impl/src/errors/mod.rs @@ -70,3 +70,6 @@ pub use validation::*; mod disaster_recovery; pub use disaster_recovery::*; + +mod asset; +pub use asset::*; diff --git a/core/station/impl/src/factories/blockchains/core.rs b/core/station/impl/src/factories/blockchains/core.rs index 6e55a5a10..ea8e725ca 100644 --- a/core/station/impl/src/factories/blockchains/core.rs +++ b/core/station/impl/src/factories/blockchains/core.rs @@ -1,7 +1,10 @@ use super::InternetComputer; use crate::{ errors::FactoryError, - models::{Account, Blockchain, BlockchainStandard, Metadata, Transfer}, + models::{ + Account, AccountAddress, AccountSeed, AddressFormat, Asset, Blockchain, Metadata, + TokenStandard, Transfer, + }, }; use async_trait::async_trait; use num_bigint::BigUint; @@ -49,18 +52,24 @@ pub trait BlockchainApi: Send + Sync { /// Generates a new address for the given account. /// /// This address is used for token transfers. - async fn generate_address(&self, account: &Account) -> Result; + async fn generate_address( + &self, + seed: &AccountSeed, + format: AddressFormat, + ) -> Result; /// Returns the latest balance of the given account. - async fn balance(&self, account: &Account) -> Result; - - /// Returns the decimals of the given account. - async fn decimals(&self, account: &Account) -> Result; + async fn balance( + &self, + asset: &Asset, + addresses: &[AccountAddress], + ) -> Result; /// Returns the latest average transaction fee. async fn transaction_fee( &self, - account: &Account, + asset: &Asset, + standard: TokenStandard, ) -> Result; /// Returns the default network. @@ -78,17 +87,12 @@ pub trait BlockchainApi: Send + Sync { pub struct BlockchainApiFactory {} impl BlockchainApiFactory { - pub fn build( - blockchain: &Blockchain, - standard: &BlockchainStandard, - ) -> Result, FactoryError> { - match (blockchain, standard) { - (Blockchain::InternetComputer, BlockchainStandard::Native) => { - Ok(Box::new(InternetComputer::create())) - } - (blockchain, standard) => Err(FactoryError::UnsupportedBlockchainAccount { + pub fn build(blockchain: &Blockchain) -> Result, FactoryError> { + match blockchain { + Blockchain::InternetComputer => Ok(Box::new(InternetComputer::create())), + + blockchain => Err(FactoryError::UnsupportedBlockchain { blockchain: blockchain.to_string(), - standard: standard.to_string(), }), } } diff --git a/core/station/impl/src/factories/blockchains/internet_computer.rs b/core/station/impl/src/factories/blockchains/internet_computer.rs index ff311cc80..83cdac860 100644 --- a/core/station/impl/src/factories/blockchains/internet_computer.rs +++ b/core/station/impl/src/factories/blockchains/internet_computer.rs @@ -8,22 +8,21 @@ use crate::{ errors::BlockchainApiError, mappers::HelperMapper, models::{ - Account, AccountId, Blockchain, BlockchainStandard, Metadata, Transfer, METADATA_MEMO_KEY, + Account, AccountAddress, AccountSeed, AddressFormat, Asset, Blockchain, Metadata, + TokenStandard, Transfer, METADATA_MEMO_KEY, }, + repositories::ASSET_REPOSITORY, }; use async_trait::async_trait; use byteorder::{BigEndian, ByteOrder}; -use candid::Principal; -use ic_ledger_types::{ - account_balance, query_blocks, transfer, AccountBalanceArgs, AccountIdentifier, GetBlocksArgs, - Memo, QueryBlocksResponse, Subaccount, Timestamp, Tokens, Transaction, TransferArgs, - TransferError as LedgerTransferError, DEFAULT_FEE, -}; +use candid::{CandidType, Principal}; use num_bigint::BigUint; use orbit_essentials::{ api::ApiError, cdk::{self}, + repository::Repository, }; +use serde::Deserialize; use sha2::{Digest, Sha256}; use std::{ fmt::{Display, Formatter}, @@ -65,11 +64,22 @@ pub struct SubmitTransferResponse { pub transaction_hash: Option, } +#[derive(CandidType, Deserialize)] +pub struct ICPLedgerTransferFee { + pub e8s: u64, +} +#[derive(CandidType, Deserialize)] +pub struct ICPLedgerTransferFeeResponse { + pub transfer_fee: ICPLedgerTransferFee, +} + +#[derive(CandidType)] +pub struct ICPLedgerTransferFeeInput {} + impl InternetComputer { pub const BLOCKCHAIN: Blockchain = Blockchain::InternetComputer; - pub const STANDARD: BlockchainStandard = BlockchainStandard::Native; + pub const STANDARD: TokenStandard = TokenStandard::InternetComputerNative; pub const ICP_LEDGER_CANISTER_ID: &'static str = "ryjl3-tyaaa-aaaaa-aaaba-cai"; - pub const DECIMALS: u32 = 8; pub const MAIN_NETWORK: InternetComputerNetwork = InternetComputerNetwork::Mainnet; pub fn create() -> Self { @@ -78,22 +88,20 @@ impl InternetComputer { } } - /// Generates the corresponded subaccount id for the given station_account id. + /// Generates the corresponded subaccount id for the given seed. /// /// The subaccount id is a 32 bytes array that is used to identify a station_account in the ICP ledger. - pub fn subaccount_from_station_account_id(station_account_id: &AccountId) -> [u8; 32] { - let len = station_account_id.len(); + pub fn subaccount_from_seed(seed: &[u8; 16]) -> [u8; 32] { + let len = seed.len(); let mut subaccount_id = [0u8; 32]; - subaccount_id[0..len].copy_from_slice(&station_account_id[0..len]); + subaccount_id[0..len].copy_from_slice(&seed[0..len]); subaccount_id } - pub fn ledger_canister_id() -> Principal { - Principal::from_text(Self::ICP_LEDGER_CANISTER_ID).unwrap() - } - - fn hash_transaction(transaction: &Transaction) -> Result { + fn hash_transaction( + transaction: &ic_ledger_types::Transaction, + ) -> Result { let mut hasher = Sha256::new(); hasher.update(&serde_cbor::ser::to_vec_packed(transaction)?); Ok(hex::encode(hasher.finalize())) @@ -105,51 +113,107 @@ impl InternetComputer { /// The station_account account id is used to identify a station_account in the ICP ledger. pub fn station_account_to_ledger_account( &self, - station_account_id: &AccountId, - ) -> AccountIdentifier { - let subaccount = InternetComputer::subaccount_from_station_account_id(station_account_id); + seed: &AccountSeed, + ) -> ic_ledger_types::AccountIdentifier { + let subaccount = InternetComputer::subaccount_from_seed(seed); - AccountIdentifier::new(&self.station_canister_id, &Subaccount(subaccount)) + ic_ledger_types::AccountIdentifier::new( + &self.station_canister_id, + &ic_ledger_types::Subaccount(subaccount), + ) } - /// Generates the corresponded ledger address for the given station_account id. + /// Generates the corresponded icp ledger address for the given station account seed. /// /// This address is used for token transfers. - pub fn station_account_address(&self, station_account_id: &AccountId) -> String { - let account = self.station_account_to_ledger_account(station_account_id); + pub fn generate_account_identifier(&self, seed: &AccountSeed) -> String { + let account = self.station_account_to_ledger_account(seed); account.to_hex() } - /// Returns the latest balance of the given station_account. - pub async fn balance(&self, station_account: &Account) -> BlockchainApiResult { - let balance = account_balance( - Self::ledger_canister_id(), - AccountBalanceArgs { - account: self.station_account_to_ledger_account(&station_account.id), + /// Generates the corresponded icrc-1 ledger address for the given station account seed. + /// + /// This address is used for token transfers. + pub fn generate_icrc1_address(&self, seed: &AccountSeed) -> String { + let subaccount = Self::subaccount_from_seed(seed); + + let address = icrc_ledger_types::icrc1::account::Account { + owner: self.station_canister_id, + subaccount: Some(subaccount), + }; + + address.to_string() + } + + /// Returns the latest balance of the given icp accountidentifier of a station account. + pub async fn balance_of_account_identifier( + &self, + asset: &Asset, + account_identifier: &ic_ledger_types::AccountIdentifier, + ) -> BlockchainApiResult { + let ledger_canister_id = Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let balance = ic_ledger_types::account_balance( + ledger_canister_id, + ic_ledger_types::AccountBalanceArgs { + account: *account_identifier, }, ) .await - .map_err(|_| BlockchainApiError::FetchBalanceFailed { - account_id: Uuid::from_bytes(station_account.id) - .hyphenated() - .to_string(), + .map_err(|e| BlockchainApiError::FetchBalanceFailed { + asset_id: Uuid::from_bytes(asset.id).hyphenated().to_string(), + info: format!("Could not get balance of asset {}({}) with address {} from canister {}. Reason: {}", asset.name, Uuid::from_bytes(asset.id).hyphenated(), account_identifier.to_hex(), ledger_canister_id, e.1), })?; Ok(balance.e8s()) } - pub fn transaction_fee(&self) -> u64 { - DEFAULT_FEE.e8s() + /// Returns the latest balance of the given icrc1 account of a station account. + pub async fn balance_of_icrc1_account( + &self, + asset: &Asset, + account: &icrc_ledger_types::icrc1::account::Account, + ) -> BlockchainApiResult { + let ledger_canister_id = Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let balance = + ic_cdk::call::<(icrc_ledger_types::icrc1::account::Account,), (candid::Nat,)>( + ledger_canister_id, + "icrc1_balance_of", + // 4. Provide the arguments for the call in a tuple, here `transfer_args` is encapsulated as a single-element tuple. + (*account,), + ) + .await + .map_err(|err| BlockchainApiError::BlockchainNetworkError { + info: format!("rejection_code: {:?}, err: {}", err.0, err.1), + })? + .0; + + Ok(balance.0) } - pub fn decimals(&self) -> u32 { - Self::DECIMALS + fn get_ledger_canister_id_from_metadata(metadata: &Metadata) -> BlockchainApiResult { + let ledger_canister_id_str = metadata + .get(TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID) + .ok_or(BlockchainApiError::MissingMetadata { + key: TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID.to_string(), + })?; + + Ok( + Principal::from_text(ledger_canister_id_str.clone()).map_err(|_| { + BlockchainApiError::InvalidMetadata { + key: TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID.to_string(), + value: ledger_canister_id_str, + } + })?, + ) } - pub async fn submit_transfer( + pub async fn submit_icp_transfer( &self, station_account: Account, + asset: Asset, station_transfer: Transfer, ) -> Result { let current_time = cdk::next_time(); @@ -159,26 +223,26 @@ impl InternetComputer { Some(memo) => HelperMapper::to_u64(memo)?, None => BigEndian::read_u64(&station_transfer.id[0..8]), }; - let to_address = - AccountIdentifier::from_hex(&station_transfer.to_address).map_err(|error| { - BlockchainApiError::InvalidToAddress { - address: station_transfer.to_address.clone(), - error, - } + let to_address = ic_ledger_types::AccountIdentifier::from_hex(&station_transfer.to_address) + .map_err(|error| BlockchainApiError::InvalidToAddress { + address: station_transfer.to_address.clone(), + error, })?; - let block_height = transfer( - Self::ledger_canister_id(), - TransferArgs { - amount: Tokens::from_e8s(amount), - fee: Tokens::from_e8s(transaction_fee), - created_at_time: Some(Timestamp { + let ledger_canister_id = Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let block_height = ic_ledger_types::transfer( + ledger_canister_id, + ic_ledger_types::TransferArgs { + amount: ic_ledger_types::Tokens::from_e8s(amount), + fee: ic_ledger_types::Tokens::from_e8s(transaction_fee), + created_at_time: Some(ic_ledger_types::Timestamp { timestamp_nanos: current_time, }), - from_subaccount: Some(Subaccount( - InternetComputer::subaccount_from_station_account_id(&station_account.id), + from_subaccount: Some(ic_ledger_types::Subaccount( + InternetComputer::subaccount_from_seed(&station_account.seed), )), - memo: Memo(memo), + memo: ic_ledger_types::Memo(memo), to: to_address, }, ) @@ -188,34 +252,36 @@ impl InternetComputer { })? .map_err(|err| BlockchainApiError::TransactionSubmitFailed { info: match err { - LedgerTransferError::BadFee { expected_fee } => { + ic_ledger_types::TransferError::BadFee { expected_fee } => { format!("Bad fee, expected: {}", expected_fee) } - LedgerTransferError::InsufficientFunds { balance } => { + ic_ledger_types::TransferError::InsufficientFunds { balance } => { format!("Insufficient balance, balance: {}", balance) } - LedgerTransferError::TxTooOld { + ic_ledger_types::TransferError::TxTooOld { allowed_window_nanos, } => { format!("Tx too old, allowed_window_nanos: {}", allowed_window_nanos) } - LedgerTransferError::TxCreatedInFuture => "Tx created in future".to_string(), - LedgerTransferError::TxDuplicate { duplicate_of } => { + ic_ledger_types::TransferError::TxCreatedInFuture => { + "Tx created in future".to_string() + } + ic_ledger_types::TransferError::TxDuplicate { duplicate_of } => { format!("Tx duplicate, duplicate_of: {}", duplicate_of) } }, })?; - let transaction_hash = match query_blocks( - Self::ledger_canister_id(), - GetBlocksArgs { + let transaction_hash = match ic_ledger_types::query_blocks( + ledger_canister_id, + ic_ledger_types::GetBlocksArgs { length: 1, start: block_height, }, ) .await { - Ok(QueryBlocksResponse { blocks, .. }) => match blocks.first() { + Ok(ic_ledger_types::QueryBlocksResponse { blocks, .. }) => match blocks.first() { Some(block) => match Self::hash_transaction(&block.transaction) { Ok(transaction_hash) => Some(transaction_hash), Err(_) => { @@ -246,34 +312,258 @@ impl InternetComputer { transaction_hash, }) } + + pub async fn submit_icrc1_transfer( + &self, + station_account: Account, + asset: Asset, + station_transfer: Transfer, + ) -> Result { + let memo = match station_transfer.metadata_map().get(METADATA_MEMO_KEY) { + Some(memo) => HelperMapper::to_u64(memo)?, + None => BigEndian::read_u64(&station_transfer.id[0..8]), + }; + + let to_address = + icrc_ledger_types::icrc1::account::Account::from_str(&station_transfer.to_address) + .map_err(|error| BlockchainApiError::InvalidToAddress { + address: station_transfer.to_address.clone(), + error: error.to_string(), + })?; + + let current_time = cdk::next_time(); + + let transfer_args = icrc_ledger_types::icrc1::transfer::TransferArg { + amount: station_transfer.amount, + fee: Some(station_transfer.fee), + created_at_time: Some(current_time), + from_subaccount: Some(InternetComputer::subaccount_from_seed( + &station_account.seed, + )), + memo: Some(memo.into()), + to: to_address, + }; + + let ledger_canister_id = Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let block_height = ic_cdk::call::< + (icrc_ledger_types::icrc1::transfer::TransferArg,), + ( + Result< + icrc_ledger_types::icrc1::transfer::BlockIndex, + icrc_ledger_types::icrc1::transfer::TransferError, + >, + ), + >( + ledger_canister_id, + "icrc1_transfer", + // 4. Provide the arguments for the call in a tuple, here `transfer_args` is encapsulated as a single-element tuple. + (transfer_args,), + ) + .await + .map_err(|err| BlockchainApiError::BlockchainNetworkError { + info: format!("rejection_code: {:?}, err: {}", err.0, err.1), + })? + .0 + .map_err(|err| BlockchainApiError::TransactionSubmitFailed { + info: match err { + icrc_ledger_types::icrc1::transfer::TransferError::BadFee { expected_fee } => { + format!("Bad fee, expected: {}", expected_fee) + } + icrc_ledger_types::icrc1::transfer::TransferError::InsufficientFunds { + balance, + } => { + format!("Insufficient balance, balance: {}", balance) + } + icrc_ledger_types::icrc1::transfer::TransferError::TooOld => { + "Tx too old".to_string() + } + icrc_ledger_types::icrc1::transfer::TransferError::CreatedInFuture { .. } => { + "Tx created in future".to_string() + } + icrc_ledger_types::icrc1::transfer::TransferError::Duplicate { duplicate_of } => { + format!("Tx duplicate, duplicate_of: {}", duplicate_of) + } + icrc_ledger_types::icrc1::transfer::TransferError::BadBurn { min_burn_amount } => { + format!("Bad burn, min_burn_amount: {}", min_burn_amount) + } + icrc_ledger_types::icrc1::transfer::TransferError::TemporarilyUnavailable => { + "Ledger temporarily unavailable".to_string() + } + icrc_ledger_types::icrc1::transfer::TransferError::GenericError { + error_code, + message, + } => { + format!("Error occurred. Code: {}, message: {}", error_code, message) + } + }, + })?; + + Ok(SubmitTransferResponse { + block_height: block_height.0.iter_u64_digits().next().unwrap_or(0), + transaction_hash: None, + }) + } } #[async_trait] impl BlockchainApi for InternetComputer { - async fn generate_address(&self, station_account: &Account) -> BlockchainApiResult { - Ok(self.station_account_address(&station_account.id)) + async fn generate_address( + &self, + seed: &AccountSeed, + format: AddressFormat, + ) -> BlockchainApiResult { + match format { + AddressFormat::ICPAccountIdentifier => Ok(AccountAddress { + address: self.generate_account_identifier(seed), + format: AddressFormat::ICPAccountIdentifier, + }), + AddressFormat::ICRC1Account => Ok(AccountAddress { + address: self.generate_icrc1_address(seed), + format: AddressFormat::ICRC1Account, + }), + AddressFormat::EthereumAddress + | AddressFormat::BitcoinAddressP2WPKH + | AddressFormat::BitcoinAddressP2TR => Err(BlockchainApiError::InvalidAddressFormat { + found: format.to_string(), + expected: [ + AddressFormat::ICPAccountIdentifier.to_string(), + AddressFormat::ICRC1Account.to_string(), + ] + .join(","), + })?, + } } - async fn balance(&self, station_account: &Account) -> BlockchainApiResult { - let balance = self.balance(station_account).await?; + async fn balance( + &self, + asset: &Asset, + account_addresses: &[AccountAddress], + ) -> BlockchainApiResult { + // all matching addresses should resolve to the same balance, so pick the first one + + let supported_formats = asset + .standards + .iter() + .flat_map(|s| s.get_info().address_formats.clone()) + .collect::>(); + + for account_address in account_addresses { + if !supported_formats.contains(&account_address.format) { + // filter out irrelevant addresses + continue; + } - Ok(BigUint::from(balance)) - } + match account_address.format { + AddressFormat::ICPAccountIdentifier => { + let balance = self + .balance_of_account_identifier( + asset, + &ic_ledger_types::AccountIdentifier::from_hex(&account_address.address) + .map_err(|error| BlockchainApiError::InvalidToAddress { + address: account_address.address.clone(), + error, + })?, + ) + .await?; + + return Ok(BigUint::from(balance)); + } + AddressFormat::ICRC1Account => { + let balance = self + .balance_of_icrc1_account( + asset, + &icrc_ledger_types::icrc1::account::Account::from_str( + &account_address.address, + ) + .map_err(|error| { + BlockchainApiError::InvalidToAddress { + address: account_address.address.clone(), + error: error.to_string(), + } + })?, + ) + .await?; + + return Ok(balance); + } + AddressFormat::EthereumAddress + | AddressFormat::BitcoinAddressP2WPKH + | AddressFormat::BitcoinAddressP2TR => { + // these address formats are not supported for ICP + continue; + } + } + } + + print(format!( + "Warning: no suitable address found for balance lookup in asset {} `{}`", + asset.name, + Uuid::from_bytes(asset.id).hyphenated() + )); - async fn decimals(&self, _station_account: &Account) -> BlockchainApiResult { - Ok(self.decimals()) + Ok(BigUint::from(0u64)) } + #[cfg(not(target_arch = "wasm32"))] async fn transaction_fee( &self, - _station_account: &Account, + _asset: &Asset, + _standard: TokenStandard, ) -> BlockchainApiResult { Ok(BlockchainTransactionFee { - fee: BigUint::from(self.transaction_fee()), + fee: 10_000u64.into(), metadata: Metadata::default(), }) } + #[cfg(target_arch = "wasm32")] + async fn transaction_fee( + &self, + asset: &Asset, + standard: TokenStandard, + ) -> BlockchainApiResult { + match standard { + TokenStandard::InternetComputerNative => { + let ledger_canister_id = + Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let fee = + ic_cdk::call::<(ICPLedgerTransferFeeInput,), (ICPLedgerTransferFeeResponse,)>( + ledger_canister_id, + "transfer_fee", + (ICPLedgerTransferFeeInput {},), + ) + .await + .map_err(|err| BlockchainApiError::BlockchainNetworkError { + info: format!("rejection_code: {:?}, err: {}", err.0, err.1), + })? + .0; + + Ok(BlockchainTransactionFee { + fee: fee.transfer_fee.e8s.into(), + metadata: Metadata::default(), + }) + } + TokenStandard::ICRC1 => { + let ledger_canister_id = + Self::get_ledger_canister_id_from_metadata(&asset.metadata)?; + + let fee = ic_cdk::call::<(), (candid::Nat,)>(ledger_canister_id, "icrc1_fee", ()) + .await + .map_err(|err| BlockchainApiError::BlockchainNetworkError { + info: format!("rejection_code: {:?}, err: {}", err.0, err.1), + })? + .0; + + Ok(BlockchainTransactionFee { + fee: fee.0, + metadata: Metadata::default(), + }) + } + } + } + fn default_network(&self) -> String { Self::MAIN_NETWORK.to_string() } @@ -283,9 +573,24 @@ impl BlockchainApi for InternetComputer { station_account: &Account, transfer: &Transfer, ) -> BlockchainApiResult { - let transfer_response = self - .submit_transfer(station_account.clone(), transfer.clone()) - .await?; + let asset = ASSET_REPOSITORY.get(&transfer.from_asset).ok_or({ + BlockchainApiError::MissingAsset { + asset_id: Uuid::from_bytes(transfer.from_asset) + .hyphenated() + .to_string(), + } + })?; + + let transfer_response = match transfer.with_standard { + TokenStandard::InternetComputerNative => { + self.submit_icp_transfer(station_account.clone(), asset, transfer.clone()) + .await? + } + TokenStandard::ICRC1 => { + self.submit_icrc1_transfer(station_account.clone(), asset, transfer.clone()) + .await? + } + }; Ok(BlockchainTransactionSubmitted { details: vec![ diff --git a/core/station/impl/src/factories/requests/add_asset.rs b/core/station/impl/src/factories/requests/add_asset.rs new file mode 100644 index 000000000..fb52d2cc7 --- /dev/null +++ b/core/station/impl/src/factories/requests/add_asset.rs @@ -0,0 +1,75 @@ +use super::{Create, Execute, RequestExecuteStage}; +use crate::{ + errors::{RequestError, RequestExecuteError}, + models::{AddAssetOperation, Request, RequestExecutionPlan, RequestOperation}, + services::AssetService, +}; +use async_trait::async_trait; +use orbit_essentials::types::UUID; + +pub struct AddAssetRequestCreate {} + +#[async_trait] +impl Create for AddAssetRequestCreate { + async fn create( + &self, + request_id: UUID, + requested_by_user: UUID, + input: station_api::CreateRequestInput, + operation_input: station_api::AddAssetOperationInput, + ) -> Result { + let request = Request::new( + request_id, + requested_by_user, + Request::default_expiration_dt_ns(), + RequestOperation::AddAsset(AddAssetOperation { + asset_id: None, + input: operation_input.into(), + }), + input + .execution_plan + .map(Into::into) + .unwrap_or(RequestExecutionPlan::Immediate), + input.title.unwrap_or_else(|| "Asset creation".to_string()), + input.summary, + ); + + Ok(request) + } +} + +pub struct AddAssetRequestExecute<'p, 'o> { + request: &'p Request, + operation: &'o AddAssetOperation, + asset_service: AssetService, +} + +impl<'p, 'o> AddAssetRequestExecute<'p, 'o> { + pub fn new(request: &'p Request, operation: &'o AddAssetOperation) -> Self { + Self { + request, + operation, + asset_service: AssetService::default(), + } + } +} + +#[async_trait] +impl Execute for AddAssetRequestExecute<'_, '_> { + async fn execute(&self) -> Result { + let asset = self + .asset_service + .create(self.operation.input.clone(), None) + .map_err(|e| RequestExecuteError::Failed { + reason: format!("Failed to create asset: {}", e), + })?; + + let mut operation = self.request.operation.clone(); + + if let RequestOperation::AddAsset(ref mut operation) = operation { + operation.asset_id = Some(asset.id); + } + + Ok(RequestExecuteStage::Completed(operation)) + } +} diff --git a/core/station/impl/src/factories/requests/edit_asset.rs b/core/station/impl/src/factories/requests/edit_asset.rs new file mode 100644 index 000000000..5e7951d12 --- /dev/null +++ b/core/station/impl/src/factories/requests/edit_asset.rs @@ -0,0 +1,69 @@ +use super::{Create, Execute, RequestExecuteStage}; +use crate::{ + errors::{RequestError, RequestExecuteError}, + models::{EditAssetOperation, Request, RequestExecutionPlan, RequestOperation}, + services::AssetService, +}; +use async_trait::async_trait; +use orbit_essentials::types::UUID; + +pub struct EditAssetRequestCreate {} + +#[async_trait] +impl Create for EditAssetRequestCreate { + async fn create( + &self, + request_id: UUID, + requested_by_user: UUID, + input: station_api::CreateRequestInput, + operation_input: station_api::EditAssetOperationInput, + ) -> Result { + let request = Request::new( + request_id, + requested_by_user, + Request::default_expiration_dt_ns(), + RequestOperation::EditAsset(EditAssetOperation { + input: operation_input.into(), + }), + input + .execution_plan + .map(Into::into) + .unwrap_or(RequestExecutionPlan::Immediate), + input.title.unwrap_or_else(|| "Edit asset".to_string()), + input.summary, + ); + + Ok(request) + } +} + +pub struct EditAssetRequestExecute<'p, 'o> { + request: &'p Request, + operation: &'o EditAssetOperation, + asset_service: AssetService, +} + +impl<'p, 'o> EditAssetRequestExecute<'p, 'o> { + pub fn new(request: &'p Request, operation: &'o EditAssetOperation) -> Self { + Self { + request, + operation, + asset_service: AssetService::default(), + } + } +} + +#[async_trait] +impl Execute for EditAssetRequestExecute<'_, '_> { + async fn execute(&self) -> Result { + self.asset_service + .edit(self.operation.input.clone()) + .map_err(|e| RequestExecuteError::Failed { + reason: format!("Failed to edit asset: {}", e), + })?; + + Ok(RequestExecuteStage::Completed( + self.request.operation.clone(), + )) + } +} diff --git a/core/station/impl/src/factories/requests/mod.rs b/core/station/impl/src/factories/requests/mod.rs index 29cdf332d..a3e7fa317 100644 --- a/core/station/impl/src/factories/requests/mod.rs +++ b/core/station/impl/src/factories/requests/mod.rs @@ -18,6 +18,7 @@ use std::sync::Arc; mod add_account; mod add_address_book_entry; +mod add_asset; mod add_request_policy; mod add_user; mod add_user_group; @@ -27,6 +28,7 @@ mod configure_external_canister; mod create_canister; mod edit_account; mod edit_address_book_entry; +mod edit_asset; mod edit_permission; mod edit_request_policy; mod edit_user; @@ -34,6 +36,7 @@ mod edit_user_group; mod fund_external_canister; mod manage_system_info; mod remove_address_book_entry; +mod remove_asset; mod remove_request_policy; mod remove_user_group; mod set_disaster_recovery; @@ -247,6 +250,24 @@ impl RequestFactory { .create(id, requested_by_user, input.clone(), operation.clone()) .await } + RequestOperationInput::AddAsset(operation) => { + let creator = Box::new(add_asset::AddAssetRequestCreate {}); + creator + .create(id, requested_by_user, input.clone(), operation.clone()) + .await + } + RequestOperationInput::EditAsset(operation) => { + let creator = Box::new(edit_asset::EditAssetRequestCreate {}); + creator + .create(id, requested_by_user, input.clone(), operation.clone()) + .await + } + RequestOperationInput::RemoveAsset(operation) => { + let creator = Box::new(remove_asset::RemoveAssetRequestCreate {}); + creator + .create(id, requested_by_user, input.clone(), operation.clone()) + .await + } } } @@ -362,6 +383,15 @@ impl RequestFactory { RequestOperation::ManageSystemInfo(operation) => Box::new( manage_system_info::ManageSystemInfoRequestExecute::new(request, operation), ), + RequestOperation::AddAsset(operation) => { + Box::new(add_asset::AddAssetRequestExecute::new(request, operation)) + } + RequestOperation::EditAsset(operation) => { + Box::new(edit_asset::EditAssetRequestExecute::new(request, operation)) + } + RequestOperation::RemoveAsset(operation) => Box::new( + remove_asset::RemoveAssetRequestExecute::new(request, operation), + ), } } } diff --git a/core/station/impl/src/factories/requests/remove_asset.rs b/core/station/impl/src/factories/requests/remove_asset.rs new file mode 100644 index 000000000..452cdcf70 --- /dev/null +++ b/core/station/impl/src/factories/requests/remove_asset.rs @@ -0,0 +1,69 @@ +use super::{Create, Execute, RequestExecuteStage}; +use crate::{ + errors::{RequestError, RequestExecuteError}, + models::{RemoveAssetOperation, Request, RequestExecutionPlan, RequestOperation}, + services::AssetService, +}; +use async_trait::async_trait; +use orbit_essentials::types::UUID; + +pub struct RemoveAssetRequestCreate {} + +#[async_trait] +impl Create for RemoveAssetRequestCreate { + async fn create( + &self, + request_id: UUID, + requested_by_user: UUID, + input: station_api::CreateRequestInput, + operation_input: station_api::RemoveAssetOperationInput, + ) -> Result { + let request = Request::new( + request_id, + requested_by_user, + Request::default_expiration_dt_ns(), + RequestOperation::RemoveAsset(RemoveAssetOperation { + input: operation_input.into(), + }), + input + .execution_plan + .map(Into::into) + .unwrap_or(RequestExecutionPlan::Immediate), + input.title.unwrap_or_else(|| "Remove asset".to_string()), + input.summary, + ); + + Ok(request) + } +} + +pub struct RemoveAssetRequestExecute<'p, 'o> { + request: &'p Request, + operation: &'o RemoveAssetOperation, + asset_service: AssetService, +} + +impl<'p, 'o> RemoveAssetRequestExecute<'p, 'o> { + pub fn new(request: &'p Request, operation: &'o RemoveAssetOperation) -> Self { + Self { + request, + operation, + asset_service: AssetService::default(), + } + } +} + +#[async_trait] +impl Execute for RemoveAssetRequestExecute<'_, '_> { + async fn execute(&self) -> Result { + self.asset_service + .remove(self.operation.input.clone()) + .map_err(|e| RequestExecuteError::Failed { + reason: format!("Failed to remove asset: {}", e), + })?; + + Ok(RequestExecuteStage::Completed( + self.request.operation.clone(), + )) + } +} diff --git a/core/station/impl/src/factories/requests/transfer.rs b/core/station/impl/src/factories/requests/transfer.rs index c38f51305..98d2f4e19 100644 --- a/core/station/impl/src/factories/requests/transfer.rs +++ b/core/station/impl/src/factories/requests/transfer.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use super::{Create, Execute, RequestExecuteStage}; use crate::{ core::generate_uuid_v4, @@ -5,10 +7,10 @@ use crate::{ factories::blockchains::BlockchainApiFactory, mappers::HelperMapper, models::{ - Account, Metadata, Request, RequestOperation, Transfer, TransferOperation, + Metadata, Request, RequestOperation, TokenStandard, Transfer, TransferOperation, TransferOperationInput, }, - repositories::ACCOUNT_REPOSITORY, + repositories::ASSET_REPOSITORY, services::TransferService, }; use async_trait::async_trait; @@ -17,10 +19,6 @@ use orbit_essentials::repository::Repository; use orbit_essentials::types::UUID; use uuid::Uuid; -fn get_account(from_account_id: &UUID) -> Option { - ACCOUNT_REPOSITORY.get(&Account::key(*from_account_id)) -} - pub struct TransferRequestCreate {} #[async_trait] @@ -39,6 +37,19 @@ impl Create for TransferRequestCreate { } })?; + let from_asset_id = HelperMapper::to_uuid(operation_input.from_asset_id.clone()) + .map_err(|e| RequestError::ValidationError { + info: format!("Invalid from_asset_id: {}", e), + })? + .as_bytes() + .to_owned(); + + let asset = ASSET_REPOSITORY + .get(&from_asset_id) + .ok_or(RequestError::ValidationError { + info: format!("Asset {} does not exist.", operation_input.from_asset_id), + })?; + let request = Request::from_request_creation_input( request_id, requested_by_user, @@ -46,8 +57,14 @@ impl Create for TransferRequestCreate { RequestOperation::Transfer(TransferOperation { transfer_id: None, fee: None, + asset, input: TransferOperationInput { from_account_id: *from_account_id.as_bytes(), + from_asset_id, + with_standard: TokenStandard::from_str(&operation_input.with_standard) + .map_err(|_| RequestError::ValidationError { + info: "Invalid with_standard.".to_owned(), + })?, to: operation_input.to, amount: operation_input.amount, fee: operation_input.fee, @@ -88,29 +105,29 @@ impl<'p, 'o> TransferRequestExecute<'p, 'o> { #[async_trait] impl Execute for TransferRequestExecute<'_, '_> { async fn execute(&self) -> Result { - let account = get_account(&self.operation.input.from_account_id).ok_or( - RequestExecuteError::Failed { + let asset = ASSET_REPOSITORY + .get(&self.operation.input.from_asset_id) + .ok_or(RequestExecuteError::Failed { reason: format!( - "Account {} does not exist.", - Uuid::from_bytes(self.operation.input.from_account_id).hyphenated() + "Asset {} does not exist.", + Uuid::from_bytes(self.operation.input.from_asset_id).hyphenated() ), - }, - )?; + })?; - let blockchain_api = BlockchainApiFactory::build(&account.blockchain, &account.standard) - .map_err(|e| RequestExecuteError::Failed { + let blockchain_api = BlockchainApiFactory::build(&asset.blockchain).map_err(|e| { + RequestExecuteError::Failed { reason: format!("Failed to build blockchain api: {}", e), - })?; + } + })?; let fee = match &self.operation.input.fee { Some(fee) => fee.clone(), None => { - let transaction_fee = - blockchain_api - .transaction_fee(&account) - .await - .map_err(|e| RequestExecuteError::Failed { - reason: format!("Failed to fetch transaction fee: {}", e), - })?; + let transaction_fee = blockchain_api + .transaction_fee(&asset, self.operation.input.with_standard.clone()) + .await + .map_err(|e| RequestExecuteError::Failed { + reason: format!("Failed to fetch transaction fee: {}", e), + })?; candid::Nat(transaction_fee.fee) } @@ -122,6 +139,8 @@ impl Execute for TransferRequestExecute<'_, '_> { *generate_uuid_v4().await.as_bytes(), self.request.requested_by, self.operation.input.from_account_id, + self.operation.input.from_asset_id, + self.operation.input.with_standard.clone(), self.operation.input.to.clone(), self.operation.input.metadata.clone(), self.operation.input.amount.clone(), diff --git a/core/station/impl/src/jobs/execute_created_transfers.rs b/core/station/impl/src/jobs/execute_created_transfers.rs index e8187df1e..9c36b27cc 100644 --- a/core/station/impl/src/jobs/execute_created_transfers.rs +++ b/core/station/impl/src/jobs/execute_created_transfers.rs @@ -7,9 +7,10 @@ use crate::{ TRANSACTION_SUBMITTED_DETAILS_TRANSACTION_HASH_KEY, }, models::{ - Account, Request, RequestOperation, RequestStatus, Transfer, TransferId, TransferStatus, + Account, Asset, Request, RequestOperation, RequestStatus, Transfer, TransferId, + TransferStatus, }, - repositories::{AccountRepository, RequestRepository, TransferRepository}, + repositories::{AccountRepository, AssetRepository, RequestRepository, TransferRepository}, services::RequestService, }; use async_trait::async_trait; @@ -24,6 +25,7 @@ use uuid::Uuid; pub struct Job { transfer_repository: TransferRepository, account_repository: AccountRepository, + asset_repository: AssetRepository, request_repository: RequestRepository, request_service: RequestService, } @@ -110,7 +112,7 @@ impl Job { for (pos, result) in results.iter().enumerate() { match result { Ok((transfer, details)) => { - let mut transfer = transfer.clone(); + let (mut transfer, _account, asset) = transfer.clone(); let transfer_completed_time = next_time(); let maybe_transaction_hash = details .details @@ -133,6 +135,7 @@ impl Job { if let RequestOperation::Transfer(transfer_operation) = &mut request.operation { + transfer_operation.asset = asset; transfer_operation.transfer_id = Some(transfer.id); transfer_operation.fee = Some(transfer.fee); } @@ -184,7 +187,7 @@ impl Job { async fn execute_transfer( &self, transfer: Transfer, - ) -> Result<(Transfer, BlockchainTransactionSubmitted), TransferError> { + ) -> Result<((Transfer, Account, Asset), BlockchainTransactionSubmitted), TransferError> { let account = self .account_repository .get(&Account::key(transfer.from_account)) @@ -195,13 +198,23 @@ impl Job { ), })?; - let blockchain_api = BlockchainApiFactory::build(&account.blockchain, &account.standard) - .map_err(|e| TransferError::ExecutionError { + let asset = self.asset_repository.get(&transfer.from_asset).ok_or( + TransferError::ValidationError { + info: format!( + "Transfer asset not found for id {}", + Uuid::from_bytes(transfer.from_asset).hyphenated() + ), + }, + )?; + + let blockchain_api = BlockchainApiFactory::build(&asset.blockchain).map_err(|e| { + TransferError::ExecutionError { reason: format!("Failed to build blockchain api: {}", e), - })?; + } + })?; match blockchain_api.submit_transaction(&account, &transfer).await { - Ok(details) => Ok((transfer, details)), + Ok(details) => Ok(((transfer, account, asset), details)), Err(error) => Err(TransferError::ExecutionError { reason: error.to_json_string(), diff --git a/core/station/impl/src/jobs/mod.rs b/core/station/impl/src/jobs/mod.rs index f2db8913e..ed6669d39 100644 --- a/core/station/impl/src/jobs/mod.rs +++ b/core/station/impl/src/jobs/mod.rs @@ -294,16 +294,19 @@ mod test { use crate::jobs::scheduler::Scheduler; use crate::jobs::{execute_created_transfers, execute_scheduled_requests}; use crate::models::account_test_utils::mock_account; + use crate::models::asset_test_utils::mock_asset; use crate::models::transfer_test_utils::mock_transfer; - use crate::models::{Account, RequestStatus}; + use crate::models::{Account, AccountAsset, RequestStatus}; use crate::repositories::{ - RequestRepository, TransferRepository, ACCOUNT_REPOSITORY, TRANSFER_REPOSITORY, + RequestRepository, TransferRepository, ACCOUNT_REPOSITORY, ASSET_REPOSITORY, + TRANSFER_REPOSITORY, }; use crate::{ jobs::{cancel_expired_requests, to_coarse_time, JobStateDatabase, ScheduledJob}, models::{request_test_utils::mock_request, Request}, repositories::REQUEST_REPOSITORY, }; + use orbit_essentials::model::ModelKey; use orbit_essentials::repository::Repository; #[tokio::test] @@ -481,9 +484,16 @@ mod test { let expiration_coarse = to_coarse_time(expiration, cancel_expired_requests::Job::JOB_TOLERANCE_NS); + let asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + // create one account so transfer requests dont fail let account = Account { id: [1; 16], + assets: vec![AccountAsset { + asset_id: asset.id, + balance: None, + }], ..mock_account() }; ACCOUNT_REPOSITORY.insert(account.to_key(), account); diff --git a/core/station/impl/src/lib.rs b/core/station/impl/src/lib.rs index 03004b3bb..7fe791dc3 100644 --- a/core/station/impl/src/lib.rs +++ b/core/station/impl/src/lib.rs @@ -4,7 +4,7 @@ pub const SERVICE_NAME: &str = "station"; pub const SYSTEM_VERSION: &str = env!("CARGO_PKG_VERSION"); -pub const STABLE_MEMORY_VERSION: u32 = 1; +pub const STABLE_MEMORY_VERSION: u32 = 2; pub mod controllers; pub mod core; @@ -14,6 +14,7 @@ pub mod jobs; mod macros; pub mod mappers; pub mod migration; +pub mod migration_tests; pub mod models; pub mod repositories; pub mod services; diff --git a/core/station/impl/src/mappers/account.rs b/core/station/impl/src/mappers/account.rs index 144af61dc..ca87b2e61 100644 --- a/core/station/impl/src/mappers/account.rs +++ b/core/station/impl/src/mappers/account.rs @@ -1,15 +1,18 @@ +use std::str::FromStr; + use crate::{ core::ic_cdk::next_time, errors::MapperError, models::{ - Account, AccountBalance, AccountCallerPrivileges, AccountId, AddAccountOperationInput, - BlockchainStandard, ACCOUNT_METADATA_SYMBOL_KEY, + Account, AccountAddress, AccountAsset, AccountBalance, AccountCallerPrivileges, AccountId, + AccountSeed, AddAccountOperationInput, AddressFormat, AssetId, BalanceQueryState, + ChangeAssets, }, - repositories::request_policy::REQUEST_POLICY_REPOSITORY, + repositories::{request_policy::REQUEST_POLICY_REPOSITORY, ASSET_REPOSITORY}, }; use ic_cdk::print; use orbit_essentials::{repository::Repository, utils::timestamp_to_rfc3339}; -use station_api::{AccountBalanceDTO, AccountBalanceInfoDTO, AccountDTO}; +use station_api::{AccountAssetDTO, AccountBalanceDTO, AccountDTO}; use uuid::Uuid; #[derive(Default, Clone, Debug)] @@ -20,21 +23,29 @@ impl AccountMapper { AccountDTO { id: Uuid::from_bytes(account.id).hyphenated().to_string(), name: account.name, - decimals: account.decimals, - balance: match account.balance { - Some(balance) => Some(AccountBalanceInfoDTO { - balance: balance.balance, - decimals: account.decimals, - last_update_timestamp: timestamp_to_rfc3339( - &balance.last_modification_timestamp, - ), - }), - None => None, - }, - symbol: account.symbol, - address: account.address, - standard: account.standard.to_string(), - blockchain: account.blockchain.to_string(), + + addresses: account.addresses.into_iter().map(|a| a.into()).collect(), + assets: account + .assets + .into_iter() + .filter_map(|account_asset| { + if let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) { + Some(AccountMapper::to_account_asset_dto( + account_asset, + asset.decimals, + account.id, + )) + } else { + print(format!( + "Asset {} not found for Account {}", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(account.id).hyphenated() + )); + None + } + }) + .collect(), + metadata: account.metadata.into_vec_dto(), transfer_request_policy: account.transfer_request_policy_id.and_then(|policy_id| { REQUEST_POLICY_REPOSITORY @@ -67,49 +78,23 @@ impl AccountMapper { pub fn from_create_input( input: AddAccountOperationInput, account_id: AccountId, - address: Option, + seed: Option, ) -> Result { - if !input - .blockchain - .supported_standards() - .contains(&input.standard) - { - return Err(MapperError::UnsupportedBlockchainStandard { - blockchain: input.blockchain.to_string(), - supported_standards: input - .blockchain - .supported_standards() - .iter() - .map(|s| s.to_string()) - .collect(), - }); - } - - let symbol = match input.standard { - BlockchainStandard::Native => { - if input.metadata.get(ACCOUNT_METADATA_SYMBOL_KEY).is_some() { - return Err(MapperError::NativeAccountSymbolMetadataNotAllowed); - } - - input.blockchain.native_symbol().to_string() - } - _ => input - .metadata - .get(ACCOUNT_METADATA_SYMBOL_KEY) - .ok_or(MapperError::NonNativeAccountSymbolRequired)?, - }; - let new_account = Account { id: account_id, - blockchain: input.blockchain, - standard: input.standard, name: input.name, - address: address.unwrap_or("".to_string()), - decimals: 0, - symbol, + seed: seed.unwrap_or(account_id), + addresses: vec![], + assets: input + .assets + .iter() + .map(|asset_id| AccountAsset { + asset_id: *asset_id, + balance: None, + }) + .collect(), transfer_request_policy_id: None, configs_request_policy_id: None, - balance: None, metadata: input.metadata, last_modification_timestamp: next_time(), }; @@ -121,12 +106,38 @@ impl AccountMapper { balance: AccountBalance, decimals: u32, account_id: AccountId, + asset_id: AssetId, + query_state: BalanceQueryState, ) -> AccountBalanceDTO { AccountBalanceDTO { account_id: Uuid::from_bytes(account_id).hyphenated().to_string(), + asset_id: Uuid::from_bytes(asset_id).hyphenated().to_string(), balance: balance.balance, decimals, last_update_timestamp: timestamp_to_rfc3339(&balance.last_modification_timestamp), + query_state: query_state.to_string(), + } + } + + pub fn to_account_asset_dto( + account_asset: AccountAsset, + decimals: u32, + account_id: AccountId, + ) -> AccountAssetDTO { + AccountAssetDTO { + asset_id: Uuid::from_bytes(account_asset.asset_id) + .hyphenated() + .to_string(), + balance: account_asset.balance.map(|balance| { + let query_state = BalanceQueryState::from(&balance); + Self::to_balance_dto( + balance, + decimals, + account_id, + account_asset.asset_id, + query_state, + ) + }), } } } @@ -146,3 +157,94 @@ impl From for station_api::AccountCallerPrivilegesDTO { } } } + +impl From for station_api::AccountAddressDTO { + fn from(account_address: AccountAddress) -> Self { + Self { + address: account_address.address, + format: account_address.format.to_string(), + } + } +} + +impl From for AccountAddress { + fn from(address: station_api::AccountAddressDTO) -> Self { + Self { + address: address.address, + format: AddressFormat::from_str(address.format.as_str()) + .expect("Failed to convert string to AddressFormat"), + } + } +} + +impl From for station_api::ChangeAssets { + fn from(change_assets: ChangeAssets) -> Self { + match change_assets { + ChangeAssets::ReplaceWith { assets } => station_api::ChangeAssets::ReplaceWith { + assets: assets + .iter() + .map(|id| Uuid::from_bytes(*id).hyphenated().to_string()) + .collect(), + }, + ChangeAssets::Change { + add_assets, + remove_assets, + } => station_api::ChangeAssets::Change { + add_assets: add_assets + .iter() + .map(|id| Uuid::from_bytes(*id).hyphenated().to_string()) + .collect(), + remove_assets: remove_assets + .iter() + .map(|id| Uuid::from_bytes(*id).hyphenated().to_string()) + .collect(), + }, + } + } +} + +impl From for ChangeAssets { + fn from(change_assets: station_api::ChangeAssets) -> Self { + match change_assets { + station_api::ChangeAssets::ReplaceWith { assets } => ChangeAssets::ReplaceWith { + assets: assets + .iter() + .map(|id| *Uuid::from_str(id).expect("Invalid asset ID").as_bytes()) + .collect(), + }, + station_api::ChangeAssets::Change { + add_assets, + remove_assets, + } => ChangeAssets::Change { + add_assets: add_assets + .iter() + .map(|id| *Uuid::from_str(id).expect("Invalid asset ID").as_bytes()) + .collect(), + remove_assets: remove_assets + .iter() + .map(|id| *Uuid::from_str(id).expect("Invalid asset ID").as_bytes()) + .collect(), + }, + } + } +} + +impl From for upgrader_api::MultiAssetAccount { + fn from(account: Account) -> Self { + Self { + id: Uuid::from_bytes(account.id).hyphenated().to_string(), + seed: account.seed, + assets: account + .assets + .iter() + .map(|account_asset| { + Uuid::from_bytes(account_asset.asset_id) + .hyphenated() + .to_string() + }) + .collect(), + name: account.name.clone(), + metadata: account.metadata.clone().into(), + } + } +} diff --git a/core/station/impl/src/mappers/address_book.rs b/core/station/impl/src/mappers/address_book.rs index e3263bb12..853bb6b91 100644 --- a/core/station/impl/src/mappers/address_book.rs +++ b/core/station/impl/src/mappers/address_book.rs @@ -1,10 +1,12 @@ +use std::str::FromStr; + use super::HelperMapper; use crate::core::ic_cdk::next_time; use crate::errors::MapperError; use crate::mappers::blockchain::BlockchainMapper; use crate::models::{ AddAddressBookEntryOperationInput, AddressBookEntry, AddressBookEntryCallerPrivileges, - ListAddressBookEntriesInput, + AddressFormat, ListAddressBookEntriesInput, }; use orbit_essentials::types::UUID; use orbit_essentials::utils::timestamp_to_rfc3339; @@ -24,6 +26,7 @@ impl AddressBookMapper { .to_string(), address_owner: address_book_entry.address_owner, address: address_book_entry.address, + address_format: address_book_entry.address_format.to_string(), blockchain: address_book_entry.blockchain.to_string(), metadata: address_book_entry.metadata.into_vec_dto(), labels: address_book_entry.labels, @@ -41,6 +44,7 @@ impl AddressBookMapper { id: entry_id, address_owner: input.address_owner, address: input.address, + address_format: input.address_format, blockchain: input.blockchain, labels: input.labels, metadata: input.metadata.into(), @@ -65,6 +69,14 @@ impl From for ListAddressBookEntriesInput { }), labels: input.labels, addresses: input.addresses, + address_formats: input.address_formats.map(|address_formats| { + address_formats + .into_iter() + .map(|address_format| { + AddressFormat::from_str(&address_format).expect("Invalid address format") + }) + .collect() + }), ids: input.ids.map(|ids| { ids.into_iter() .map(|id| { diff --git a/core/station/impl/src/mappers/asset.rs b/core/station/impl/src/mappers/asset.rs index 0577c679a..f34f3dff0 100644 --- a/core/station/impl/src/mappers/asset.rs +++ b/core/station/impl/src/mappers/asset.rs @@ -1,13 +1,42 @@ -use crate::models::Asset; +use station_api::AssetCallerPrivilegesDTO; +use uuid::Uuid; + +use crate::models::{Asset, AssetCallerPrivileges}; impl From for station_api::AssetDTO { fn from(asset: Asset) -> Self { station_api::AssetDTO { + id: Uuid::from_bytes(asset.id).hyphenated().to_string(), blockchain: asset.blockchain.to_string(), symbol: asset.symbol.to_string(), - standard: asset.standard.to_string(), + standards: asset.standards.into_iter().map(|s| s.to_string()).collect(), name: asset.name, metadata: asset.metadata.into_vec_dto(), + decimals: asset.decimals, + } + } +} + +impl From for AssetCallerPrivilegesDTO { + fn from(input: AssetCallerPrivileges) -> AssetCallerPrivilegesDTO { + AssetCallerPrivilegesDTO { + id: Uuid::from_bytes(input.id).hyphenated().to_string(), + can_edit: input.can_edit, + can_delete: input.can_delete, + } + } +} + +impl From for upgrader_api::Asset { + fn from(asset: Asset) -> Self { + upgrader_api::Asset { + id: Uuid::from_bytes(asset.id).hyphenated().to_string(), + blockchain: asset.blockchain.to_string(), + symbol: asset.symbol.clone(), + name: asset.name.clone(), + decimals: asset.decimals, + standards: asset.standards.iter().map(|s| s.to_string()).collect(), + metadata: asset.metadata.clone().into(), } } } diff --git a/core/station/impl/src/mappers/authorization.rs b/core/station/impl/src/mappers/authorization.rs index fdd8c2fa8..97aba3faa 100644 --- a/core/station/impl/src/mappers/authorization.rs +++ b/core/station/impl/src/mappers/authorization.rs @@ -17,7 +17,7 @@ use orbit_essentials::repository::Repository; use orbit_essentials::types::UUID; use station_api::{RequestOperationInput, UserPrivilege}; -pub const USER_PRIVILEGES: [UserPrivilege; 19] = [ +pub const USER_PRIVILEGES: [UserPrivilege; 21] = [ UserPrivilege::Capabilities, UserPrivilege::SystemInfo, UserPrivilege::ManageSystemInfo, @@ -37,6 +37,8 @@ pub const USER_PRIVILEGES: [UserPrivilege; 19] = [ UserPrivilege::CreateExternalCanister, UserPrivilege::ListExternalCanisters, UserPrivilege::CallAnyExternalCanister, + UserPrivilege::AddAsset, + UserPrivilege::ListAssets, ]; impl From for Resource { @@ -72,6 +74,8 @@ impl From for Resource { validation_method: ValidationMethodResourceTarget::No, }), ), + UserPrivilege::AddAsset => Resource::Asset(ResourceAction::Create), + UserPrivilege::ListAssets => Resource::Asset(ResourceAction::List), } } } @@ -144,6 +148,16 @@ impl From<&station_api::GetUserGroupInput> for Resource { } } +impl From<&station_api::GetAssetInput> for Resource { + fn from(input: &station_api::GetAssetInput) -> Self { + Resource::Asset(ResourceAction::Read(ResourceId::Id( + *HelperMapper::to_uuid(input.asset_id.to_owned()) + .expect("Invalid asset id") + .as_bytes(), + ))) + } +} + impl From<&station_api::SubmitRequestApprovalInput> for Resource { fn from(input: &station_api::SubmitRequestApprovalInput) -> Self { Resource::Request(RequestResourceAction::Read(ResourceId::Id( @@ -297,6 +311,21 @@ impl From<&station_api::CreateRequestInput> for Resource { RequestOperationInput::ManageSystemInfo(_) => { Resource::System(SystemResourceAction::ManageSystemInfo) } + RequestOperationInput::AddAsset(_) => Resource::Asset(ResourceAction::Create), + RequestOperationInput::EditAsset(input) => { + Resource::Asset(ResourceAction::Update(ResourceId::Id( + *HelperMapper::to_uuid(input.asset_id.to_owned()) + .expect("Invalid asset id") + .as_bytes(), + ))) + } + RequestOperationInput::RemoveAsset(input) => { + Resource::Asset(ResourceAction::Delete(ResourceId::Id( + *HelperMapper::to_uuid(input.asset_id.to_owned()) + .expect("Invalid asset id") + .as_bytes(), + ))) + } } } } diff --git a/core/station/impl/src/mappers/blockchain.rs b/core/station/impl/src/mappers/blockchain.rs index 1f91aae77..43855e664 100644 --- a/core/station/impl/src/mappers/blockchain.rs +++ b/core/station/impl/src/mappers/blockchain.rs @@ -1,6 +1,6 @@ use crate::{ errors::MapperError, - models::{Blockchain, BlockchainStandard}, + models::{Blockchain, TokenStandard}, }; use std::str::FromStr; @@ -15,8 +15,8 @@ impl BlockchainMapper { Ok(blockchain) } - pub fn to_blockchain_standard(standard: String) -> Result { - let standard = BlockchainStandard::from_str(standard.as_str()).map_err(|_| { + pub fn to_blockchain_standard(standard: String) -> Result { + let standard = TokenStandard::from_str(standard.as_str()).map_err(|_| { MapperError::UnknownBlockchainStandard { blockchain_standard: standard, } diff --git a/core/station/impl/src/mappers/helper.rs b/core/station/impl/src/mappers/helper.rs index f12628b21..e0765b753 100644 --- a/core/station/impl/src/mappers/helper.rs +++ b/core/station/impl/src/mappers/helper.rs @@ -30,6 +30,14 @@ impl HelperMapper { nat: amount.to_string(), }) } + + pub fn nat_to_u128(amount: Nat) -> Result { + (&amount.0) + .try_into() + .map_err(|_| MapperError::NatConversionError { + nat: amount.to_string(), + }) + } } #[cfg(test)] diff --git a/core/station/impl/src/mappers/metadata.rs b/core/station/impl/src/mappers/metadata.rs index f804008d6..c0140e07b 100644 --- a/core/station/impl/src/mappers/metadata.rs +++ b/core/station/impl/src/mappers/metadata.rs @@ -1,5 +1,5 @@ use crate::{ - errors::{AccountError, AddressBookError, MetadataError, TransferError}, + errors::{AccountError, AddressBookError, AssetError, MetadataError, TransferError}, models::{ChangeMetadata, Metadata, MetadataItem}, }; @@ -114,6 +114,14 @@ impl From for AddressBookError { } } +impl From for AssetError { + fn from(metadata_error: MetadataError) -> Self { + match metadata_error { + MetadataError::ValidationError { info: e } => Self::ValidationError { info: e }, + } + } +} + impl From for TransferError { fn from(metadata_error: MetadataError) -> Self { match metadata_error { diff --git a/core/station/impl/src/mappers/notification_type.rs b/core/station/impl/src/mappers/notification_type.rs index 604189412..d49b92412 100644 --- a/core/station/impl/src/mappers/notification_type.rs +++ b/core/station/impl/src/mappers/notification_type.rs @@ -93,7 +93,10 @@ impl TryFrom for NotificationTypeDTO { | RequestOperation::ConfigureExternalCanister(_) | RequestOperation::CreateExternalCanister(_) | RequestOperation::FundExternalCanister(_) - | RequestOperation::CallExternalCanister(_) => None, + | RequestOperation::CallExternalCanister(_) + | RequestOperation::AddAsset(_) + | RequestOperation::EditAsset(_) + | RequestOperation::RemoveAsset(_) => None, }; let user_id: Option<[u8; 16]> = match &request.operation { @@ -119,7 +122,10 @@ impl TryFrom for NotificationTypeDTO { | RequestOperation::ConfigureExternalCanister(_) | RequestOperation::CreateExternalCanister(_) | RequestOperation::FundExternalCanister(_) - | RequestOperation::CallExternalCanister(_) => None, + | RequestOperation::CallExternalCanister(_) + | RequestOperation::AddAsset(_) + | RequestOperation::EditAsset(_) + | RequestOperation::RemoveAsset(_) => None, }; NotificationTypeDTO::RequestCreated(RequestCreatedNotificationDTO { diff --git a/core/station/impl/src/mappers/request_operation.rs b/core/station/impl/src/mappers/request_operation.rs index c559969b4..16bd0c777 100644 --- a/core/station/impl/src/mappers/request_operation.rs +++ b/core/station/impl/src/mappers/request_operation.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use super::{blockchain::BlockchainMapper, HelperMapper}; use crate::{ models::{ @@ -8,8 +10,9 @@ use crate::{ UserResourceAction, }, Account, AccountKey, AddAccountOperation, AddAccountOperationInput, - AddAddressBookEntryOperation, AddAddressBookEntryOperationInput, AddRequestPolicyOperation, - AddRequestPolicyOperationInput, AddUserOperation, AddUserOperationInput, AddressBookEntry, + AddAddressBookEntryOperation, AddAddressBookEntryOperationInput, AddAssetOperation, + AddAssetOperationInput, AddRequestPolicyOperation, AddRequestPolicyOperationInput, + AddUserOperation, AddUserOperationInput, AddressBookEntry, AddressFormat, Asset, CallExternalCanisterOperation, CallExternalCanisterOperationInput, CanisterExecutionAndValidationMethodPairInput, CanisterInstallMode, CanisterInstallModeArgs, CanisterMethod, CanisterReinstallModeArgs, @@ -20,10 +23,11 @@ use crate::{ CreateExternalCanisterOperationKind, CreateExternalCanisterOperationKindAddExisting, CreateExternalCanisterOperationKindCreateNew, CycleObtainStrategy, DefiniteCanisterSettingsInput, DisasterRecoveryCommittee, EditAccountOperation, - EditAccountOperationInput, EditAddressBookEntryOperation, EditPermissionOperation, - EditPermissionOperationInput, EditRequestPolicyOperation, EditRequestPolicyOperationInput, - EditUserGroupOperation, EditUserOperation, EditUserOperationInput, - ExternalCanisterCallPermission, ExternalCanisterCallPermissionExecMethodEntryInput, + EditAccountOperationInput, EditAddressBookEntryOperation, EditAssetOperation, + EditAssetOperationInput, EditPermissionOperation, EditPermissionOperationInput, + EditRequestPolicyOperation, EditRequestPolicyOperationInput, EditUserGroupOperation, + EditUserOperation, EditUserOperationInput, ExternalCanisterCallPermission, + ExternalCanisterCallPermissionExecMethodEntryInput, ExternalCanisterCallPermissionMethodPairInput, ExternalCanisterCallPermissionsExecMethodInput, ExternalCanisterCallRequestPoliciesExecMethodInput, @@ -35,14 +39,15 @@ use crate::{ ExternalCanisterPermissionsUpdateInput, ExternalCanisterRequestPoliciesCreateInput, ExternalCanisterRequestPoliciesUpdateInput, FundExternalCanisterOperation, LogVisibility, ManageSystemInfoOperation, ManageSystemInfoOperationInput, RemoveAddressBookEntryOperation, - RemoveRequestPolicyOperation, RemoveRequestPolicyOperationInput, RemoveUserGroupOperation, - RequestOperation, SetDisasterRecoveryOperation, SetDisasterRecoveryOperationInput, - SystemUpgradeOperation, SystemUpgradeOperationInput, SystemUpgradeTarget, - TransferOperation, User, WasmModuleExtraChunks, + RemoveAssetOperation, RemoveAssetOperationInput, RemoveRequestPolicyOperation, + RemoveRequestPolicyOperationInput, RemoveUserGroupOperation, RequestOperation, + SetDisasterRecoveryOperation, SetDisasterRecoveryOperationInput, SystemUpgradeOperation, + SystemUpgradeOperationInput, SystemUpgradeTarget, TransferOperation, User, + WasmModuleExtraChunks, }, repositories::{ - AccountRepository, AddressBookRepository, UserRepository, ACCOUNT_REPOSITORY, - USER_GROUP_REPOSITORY, + AccountRepository, AddressBookRepository, AssetRepository, UserRepository, + ACCOUNT_REPOSITORY, USER_GROUP_REPOSITORY, }, }; use orbit_essentials::repository::Repository; @@ -59,6 +64,7 @@ impl TransferOperation { pub fn to_dto(self, account: Option) -> TransferOperationDTO { TransferOperationDTO { from_account: account.map(|account| account.to_dto()), + from_asset: self.asset.into(), network: NetworkDTO { id: self.input.network.clone(), name: self.input.network.clone(), @@ -67,6 +73,10 @@ impl TransferOperation { from_account_id: Uuid::from_bytes(self.input.from_account_id) .hyphenated() .to_string(), + from_asset_id: Uuid::from_bytes(self.input.from_asset_id) + .hyphenated() + .to_string(), + with_standard: self.input.with_standard.to_string(), amount: self.input.amount, to: self.input.to, fee: self.input.fee, @@ -90,8 +100,12 @@ impl AddAccountOperation { account: account.map(|account: Account| account.to_dto()), input: station_api::AddAccountOperationInput { name: self.input.name, - blockchain: self.input.blockchain.to_string(), - standard: self.input.standard.to_string(), + assets: self + .input + .assets + .into_iter() + .map(|id| Uuid::from_bytes(id).hyphenated().to_string()) + .collect(), metadata: self.input.metadata.into_vec_dto(), read_permission: self.input.read_permission.into(), transfer_permission: self.input.transfer_permission.into(), @@ -120,10 +134,15 @@ impl From for AddAccountOperationInput { fn from(input: station_api::AddAccountOperationInput) -> AddAccountOperationInput { AddAccountOperationInput { name: input.name, - blockchain: BlockchainMapper::to_blockchain(input.blockchain.clone()) - .expect("Invalid blockchain"), - standard: BlockchainMapper::to_blockchain_standard(input.standard) - .expect("Invalid blockchain standard"), + assets: input + .assets + .iter() + .map(|id| { + *HelperMapper::to_uuid(id.clone()) + .expect("Invalid asset id") + .as_bytes() + }) + .collect(), metadata: input.metadata.into(), read_permission: input.read_permission.into(), configs_permission: input.configs_permission.into(), @@ -142,6 +161,10 @@ impl From for EditAccountOperationDTO { .hyphenated() .to_string(), name: operation.input.name, + change_assets: operation + .input + .change_assets + .map(|change_assets| change_assets.into()), read_permission: operation.input.read_permission.map(|policy| policy.into()), transfer_permission: operation .input @@ -170,6 +193,9 @@ impl From for EditAccountOperationInput account_id: *HelperMapper::to_uuid(input.account_id) .expect("Invalid account id") .as_bytes(), + change_assets: input + .change_assets + .map(|change_assets| change_assets.into()), name: input.name, read_permission: input.read_permission.map(|policy| policy.into()), transfer_permission: input.transfer_permission.map(|policy| policy.into()), @@ -191,6 +217,7 @@ impl AddAddressBookEntryOperation { input: station_api::AddAddressBookEntryOperationInput { address_owner: self.input.address_owner, address: self.input.address, + address_format: self.input.address_format.to_string(), blockchain: self.input.blockchain.to_string(), metadata: self.input.metadata.into_iter().map(Into::into).collect(), labels: self.input.labels, @@ -205,6 +232,8 @@ impl From for AddAddressBookEntr ) -> AddAddressBookEntryOperationInput { AddAddressBookEntryOperationInput { address_owner: input.address_owner, + address_format: AddressFormat::from_str(&input.address_format) + .expect("Invalid address format"), address: input.address, blockchain: BlockchainMapper::to_blockchain(input.blockchain.clone()) .expect("Invalid blockchain"), @@ -1525,6 +1554,117 @@ impl From for ManageSystemInfoOperati } } +impl AddAssetOperation { + pub fn to_dto(self, asset: Option) -> station_api::AddAssetOperationDTO { + station_api::AddAssetOperationDTO { + asset: asset.map(|asset| asset.into()), + input: station_api::AddAssetOperationInput { + name: self.input.name, + blockchain: self.input.blockchain.to_string(), + standards: self.input.standards.iter().map(|s| s.to_string()).collect(), + symbol: self.input.symbol, + decimals: self.input.decimals, + metadata: self.input.metadata.into_vec_dto(), + }, + } + } +} + +impl From for AddAssetOperationInput { + fn from(input: station_api::AddAssetOperationInput) -> AddAssetOperationInput { + AddAssetOperationInput { + name: input.name, + symbol: input.symbol, + decimals: input.decimals, + metadata: input.metadata.into(), + blockchain: input.blockchain.parse().expect("Invalid blockchain"), + standards: input + .standards + .iter() + .map(|s| s.parse().expect("Invalid standard")) + .collect(), + } + } +} + +impl From for station_api::EditAssetOperationDTO { + fn from(operation: EditAssetOperation) -> station_api::EditAssetOperationDTO { + station_api::EditAssetOperationDTO { + input: operation.input.into(), + } + } +} + +impl From for station_api::EditAssetOperationInput { + fn from(input: EditAssetOperationInput) -> station_api::EditAssetOperationInput { + station_api::EditAssetOperationInput { + asset_id: Uuid::from_bytes(input.asset_id).hyphenated().to_string(), + name: input.name, + symbol: input.symbol, + change_metadata: input + .change_metadata + .map(|change_metadata| change_metadata.into()), + blockchain: input.blockchain.map(|blockchain| blockchain.to_string()), + standards: input + .standards + .map(|standards| standards.into_iter().map(|s| s.to_string()).collect()), + } + } +} + +impl From for EditAssetOperationInput { + fn from(input: station_api::EditAssetOperationInput) -> EditAssetOperationInput { + EditAssetOperationInput { + asset_id: *HelperMapper::to_uuid(input.asset_id) + .expect("Invalid asset id") + .as_bytes(), + name: input.name, + symbol: input.symbol, + change_metadata: input + .change_metadata + .map(|change_metadata| change_metadata.into()), + blockchain: input.blockchain.map(|blockchain_dto| { + BlockchainMapper::to_blockchain(blockchain_dto).expect("Invalid blockchain") + }), + standards: input.standards.map(|standards| { + standards + .into_iter() + .map(|s| { + BlockchainMapper::to_blockchain_standard(s) + .expect("Invalid blockchain standard") + }) + .collect() + }), + } + } +} + +impl From for station_api::RemoveAssetOperationDTO { + fn from(operation: RemoveAssetOperation) -> station_api::RemoveAssetOperationDTO { + station_api::RemoveAssetOperationDTO { + input: operation.input.into(), + } + } +} + +impl From for station_api::RemoveAssetOperationInput { + fn from(input: RemoveAssetOperationInput) -> station_api::RemoveAssetOperationInput { + station_api::RemoveAssetOperationInput { + asset_id: Uuid::from_bytes(input.asset_id).hyphenated().to_string(), + } + } +} + +impl From for RemoveAssetOperationInput { + fn from(input: station_api::RemoveAssetOperationInput) -> RemoveAssetOperationInput { + RemoveAssetOperationInput { + asset_id: *HelperMapper::to_uuid(input.asset_id) + .expect("Invalid asset id") + .as_bytes(), + } + } +} + impl From for RequestOperationDTO { fn from(operation: RequestOperation) -> RequestOperationDTO { match operation { @@ -1618,6 +1758,19 @@ impl From for RequestOperationDTO { RequestOperation::ManageSystemInfo(operation) => { RequestOperationDTO::ManageSystemInfo(Box::new(operation.into())) } + RequestOperation::AddAsset(operation) => { + let asset = operation + .asset_id + .and_then(|id| AssetRepository::default().get(&id)); + + RequestOperationDTO::AddAsset(Box::new(operation.to_dto(asset))) + } + RequestOperation::EditAsset(operation) => { + RequestOperationDTO::EditAsset(Box::new(operation.into())) + } + RequestOperation::RemoveAsset(operation) => { + RequestOperationDTO::RemoveAsset(Box::new(operation.into())) + } } } } @@ -1798,6 +1951,21 @@ impl RequestOperation { RequestOperation::ManageSystemInfo(_) => { vec![Resource::System(SystemResourceAction::ManageSystemInfo)] } + RequestOperation::AddAsset(_) => { + vec![Resource::Asset(ResourceAction::Create)] + } + RequestOperation::EditAsset(EditAssetOperation { input }) => { + vec![ + Resource::Asset(ResourceAction::Update(ResourceId::Id(input.asset_id))), + Resource::Asset(ResourceAction::Update(ResourceId::Any)), + ] + } + RequestOperation::RemoveAsset(RemoveAssetOperation { input }) => { + vec![ + Resource::Asset(ResourceAction::Delete(ResourceId::Id(input.asset_id))), + Resource::Asset(ResourceAction::Delete(ResourceId::Any)), + ] + } } } } diff --git a/core/station/impl/src/mappers/request_operation_type.rs b/core/station/impl/src/mappers/request_operation_type.rs index 2ed83634a..1b919d274 100644 --- a/core/station/impl/src/mappers/request_operation_type.rs +++ b/core/station/impl/src/mappers/request_operation_type.rs @@ -78,6 +78,15 @@ impl From for ListRequestsOperationTy station_api::ListRequestsOperationTypeDTO::SetDisasterRecovery => { ListRequestsOperationType::SetDisasterRecovery } + station_api::ListRequestsOperationTypeDTO::AddAsset => { + ListRequestsOperationType::AddAsset + } + station_api::ListRequestsOperationTypeDTO::EditAsset => { + ListRequestsOperationType::EditAsset + } + station_api::ListRequestsOperationTypeDTO::RemoveAsset => { + ListRequestsOperationType::RemoveAsset + } } } } @@ -128,6 +137,9 @@ impl From for RequestOperationType { RequestOperationTypeDTO::ConfigureExternalCanister => { RequestOperationType::ConfigureExternalCanister } + RequestOperationTypeDTO::AddAsset => RequestOperationType::AddAsset, + RequestOperationTypeDTO::EditAsset => RequestOperationType::EditAsset, + RequestOperationTypeDTO::RemoveAsset => RequestOperationType::RemoveAsset, } } } @@ -178,6 +190,9 @@ impl From for RequestOperationTypeDTO { RequestOperationType::ConfigureExternalCanister => { RequestOperationTypeDTO::ConfigureExternalCanister } + RequestOperationType::AddAsset => RequestOperationTypeDTO::AddAsset, + RequestOperationType::EditAsset => RequestOperationTypeDTO::EditAsset, + RequestOperationType::RemoveAsset => RequestOperationTypeDTO::RemoveAsset, } } } @@ -216,6 +231,9 @@ impl From for RequestOperationType { RequestOperation::RemoveRequestPolicy(_) => RequestOperationType::RemoveRequestPolicy, RequestOperation::ManageSystemInfo(_) => RequestOperationType::ManageSystemInfo, RequestOperation::SetDisasterRecovery(_) => RequestOperationType::SetDisasterRecovery, + RequestOperation::AddAsset(_) => RequestOperationType::AddAsset, + RequestOperation::EditAsset(_) => RequestOperationType::EditAsset, + RequestOperation::RemoveAsset(_) => RequestOperationType::RemoveAsset, } } } diff --git a/core/station/impl/src/mappers/request_policy.rs b/core/station/impl/src/mappers/request_policy.rs index 9fd8ba598..23134ed7f 100644 --- a/core/station/impl/src/mappers/request_policy.rs +++ b/core/station/impl/src/mappers/request_policy.rs @@ -282,6 +282,13 @@ impl From for station_api::RequestSpecifierDTO { RequestSpecifier::ManageSystemInfo => { station_api::RequestSpecifierDTO::ManageSystemInfo } + RequestSpecifier::AddAsset => station_api::RequestSpecifierDTO::AddAsset, + RequestSpecifier::EditAsset(resource_ids) => { + station_api::RequestSpecifierDTO::EditAsset(resource_ids.into()) + } + RequestSpecifier::RemoveAsset(resource_ids) => { + station_api::RequestSpecifierDTO::RemoveAsset(resource_ids.into()) + } } } } @@ -347,6 +354,13 @@ impl From for RequestSpecifier { station_api::RequestSpecifierDTO::ManageSystemInfo => { RequestSpecifier::ManageSystemInfo } + station_api::RequestSpecifierDTO::AddAsset => RequestSpecifier::AddAsset, + station_api::RequestSpecifierDTO::EditAsset(resource_ids) => { + RequestSpecifier::EditAsset(resource_ids.into()) + } + station_api::RequestSpecifierDTO::RemoveAsset(resource_ids) => { + RequestSpecifier::RemoveAsset(resource_ids.into()) + } } } } @@ -494,6 +508,22 @@ impl RequestSpecifier { .map(|id| Resource::UserGroup(ResourceAction::Delete(ResourceId::Id(*id)))) .collect::<_>(), }, + + RequestSpecifier::AddAsset => vec![Resource::Asset(ResourceAction::Create)], + RequestSpecifier::EditAsset(resource_ids) => match resource_ids { + ResourceIds::Any => vec![Resource::Asset(ResourceAction::Update(ResourceId::Any))], + ResourceIds::Ids(ids) => ids + .iter() + .map(|id| Resource::Asset(ResourceAction::Update(ResourceId::Id(*id)))) + .collect::<_>(), + }, + RequestSpecifier::RemoveAsset(resource_ids) => match resource_ids { + ResourceIds::Any => vec![Resource::Asset(ResourceAction::Delete(ResourceId::Any))], + ResourceIds::Ids(ids) => ids + .iter() + .map(|id| Resource::Asset(ResourceAction::Delete(ResourceId::Id(*id)))) + .collect::<_>(), + }, } } } diff --git a/core/station/impl/src/mappers/resource.rs b/core/station/impl/src/mappers/resource.rs index acb91cb54..4050b131a 100644 --- a/core/station/impl/src/mappers/resource.rs +++ b/core/station/impl/src/mappers/resource.rs @@ -28,6 +28,7 @@ impl From for Resource { station_api::ResourceDTO::Notification(action) => Resource::Notification(action.into()), station_api::ResourceDTO::Request(action) => Resource::Request(action.into()), station_api::ResourceDTO::System(action) => Resource::System(action.into()), + station_api::ResourceDTO::Asset(action) => Resource::Asset(action.into()), } } } @@ -49,6 +50,7 @@ impl From for station_api::ResourceDTO { Resource::Notification(action) => station_api::ResourceDTO::Notification(action.into()), Resource::Request(action) => station_api::ResourceDTO::Request(action.into()), Resource::System(action) => station_api::ResourceDTO::System(action.into()), + Resource::Asset(action) => station_api::ResourceDTO::Asset(action.into()), } } } diff --git a/core/station/impl/src/migration.rs b/core/station/impl/src/migration.rs index a275dcbec..5f2007c30 100644 --- a/core/station/impl/src/migration.rs +++ b/core/station/impl/src/migration.rs @@ -1,32 +1,35 @@ use crate::core::ic_cdk::api::trap; use crate::core::{read_system_info, write_system_info, Memory}; -use crate::models::permission::{Permission, PermissionKey}; +use crate::factories::blockchains::InternetComputer; +use crate::models::permission::{Allow, AuthScope}; use crate::models::request_specifier::RequestSpecifier; -use crate::models::resource::{ExternalCanisterResourceAction, Resource, SystemResourceAction}; +use crate::models::resource::{Resource, SystemResourceAction}; +use crate::models::resource::{ResourceAction, ResourceId, ResourceIds}; use crate::models::{ - Account, AccountKey, AddressBookEntry, AddressBookEntryKey, ExternalCanister, - ExternalCanisterKey, ListRequestsOperationType, Request, RequestKey, RequestOperation, - RequestPolicy, User, UserGroup, UserKey, + Account, AccountAddress, AccountAsset, AccountBalance, AccountId, AccountKey, AccountSeed, + AddAccountOperationInput, AddAddressBookEntryOperationInput, AddRequestPolicyOperationInput, + AddressBookEntry, AddressBookEntryId, AddressBookEntryKey, AddressFormat, Asset, AssetId, + Blockchain, EditPermissionOperationInput, Metadata, MetadataItem, Request, RequestKey, + RequestPolicyRule, TokenStandard, Transfer, TransferId, TransferKey, TransferOperation, + TransferOperationInput, TransferStatus, UserId, }; -use crate::repositories::permission::{PermissionRepository, PERMISSION_REPOSITORY}; +use crate::repositories::permission::PERMISSION_REPOSITORY; use crate::repositories::{ - AccountRepository, AddressBookRepository, ExternalCanisterRepository, RequestPolicyRepository, - RequestRepository, RequestWhereClause, UserGroupRepository, UserRepository, ACCOUNT_REPOSITORY, - ADDRESS_BOOK_REPOSITORY, EXTERNAL_CANISTER_REPOSITORY, REQUEST_POLICY_REPOSITORY, - USER_GROUP_REPOSITORY, USER_REPOSITORY, + AccountRepository, AddressBookRepository, RequestRepository, TransferRepository, + REQUEST_POLICY_REPOSITORY, USER_GROUP_REPOSITORY, USER_REPOSITORY, }; -use crate::{concat_str_arrays, STABLE_MEMORY_VERSION}; -use crate::{core::with_memory_manager, repositories::REQUEST_REPOSITORY}; -use ic_stable_structures::memory_manager::{MemoryId, VirtualMemory}; -use ic_stable_structures::Memory as DefaultMemoryTrait; +use crate::repositories::{ + ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, ASSET_REPOSITORY, REQUEST_REPOSITORY, + TRANSFER_REPOSITORY, +}; +use crate::services::permission::PERMISSION_SERVICE; +use crate::services::{INITIAL_ICP_ASSET, INITIAL_ICP_ASSET_ID, REQUEST_POLICY_SERVICE}; +use crate::STABLE_MEMORY_VERSION; +use ic_stable_structures::memory_manager::VirtualMemory; use orbit_essentials::model::ModelKey; -use orbit_essentials::repository::{IndexedRepository, RebuildRepository, Repository, StableDb}; -use orbit_essentials::storable; -use orbit_essentials::types::UUID; -use serde::de::{self, EnumAccess, VariantAccess, Visitor}; +use orbit_essentials::repository::{RebuildRepository, Repository}; +use orbit_essentials::types::{Timestamp, UUID}; use serde::{Deserialize, Deserializer}; -use std::fmt; -use strum::VariantNames; /// Handles stable memory schema migrations for the station canister. /// @@ -58,6 +61,13 @@ impl MigrationHandler { )); } + if stored_version != STABLE_MEMORY_VERSION - 1 { + trap(&format!( + "Cannot skip upgrades between station memory layout version {} to {}", + stored_version, STABLE_MEMORY_VERSION + )); + } + apply_migration(); // Update the stable memory version to the latest version. @@ -71,532 +81,585 @@ impl MigrationHandler { /// If there is a check that needs to be run on every upgrade, regardless if the memory version has changed, /// it should be added here. -fn post_run() { - // Deserialization of the all requests to make sure an incompatible memory will panic and avoids - // putting the station in an inconsistent state. - // - // This is a temporary addition only for the next release since we've added a breaking change to - // the `ConfigureExternalCanisterSettingsInput` which had a new API not yet used in production. - let where_clause = RequestWhereClause { - operation_types: vec![ListRequestsOperationType::ConfigureExternalCanister(None)], - ..Default::default() - }; - - let ids = REQUEST_REPOSITORY - .find_ids_where(where_clause, None) - .expect("Failed to search for requests with the external canister operation types"); - - for id in ids { - REQUEST_REPOSITORY - .get(&RequestKey { id }) - .expect("Failed to deserialize the request from the stable memory"); - } -} +fn post_run() {} /// The migration to apply to the station canister stable memory. /// /// Please include the migration steps in the `apply_migration` function. fn apply_migration() { - // step 1: clear unused memory ids - with_memory_manager(|memory_manager| { - for memory_id in [ - MemoryId::new(3), // USER_IDENTITY_INDEX_MEMORY_ID, - MemoryId::new(5), // REQUEST_EXPIRATION_TIME_INDEX_MEMORY_ID - MemoryId::new(8), // REQUEST_APPROVER_INDEX_MEMORY_ID - MemoryId::new(9), // REQUEST_STATUS_INDEX_MEMORY_ID - MemoryId::new(10), // REQUEST_SCHEDULED_INDEX_MEMORY_ID - MemoryId::new(15), // USER_GROUP_NAME_INDEX_MEMORY_ID - MemoryId::new(18), // USER_STATUS_GROUP_INDEX_MEMORY_ID - MemoryId::new(20), // ADDRESS_BOOK_INDEX_MEMORY_ID - MemoryId::new(21), // REQUEST_REQUESTER_INDEX_MEMORY_ID - MemoryId::new(22), // REQUEST_CREATION_TIME_INDEX_MEMORY_ID - MemoryId::new(23), // REQUEST_KEY_CREATION_TIME_INDEX_MEMORY_ID - MemoryId::new(24), // REQUEST_KEY_EXPIRATION_TIME_INDEX_MEMORY_ID - MemoryId::new(25), // REQUEST_SORT_INDEX_MEMORY_ID - MemoryId::new(26), // REQUEST_STATUS_MODIFICATION_INDEX_MEMORY_ID - MemoryId::new(27), // NAME_TO_ACCOUNT_ID_INDEX_MEMORY_ID - MemoryId::new(28), // NAME_TO_USER_ID_INDEX_MEMORY_ID - MemoryId::new(29), // OPERATION_TYPE_TO_REQUEST_ID_INDEX_MEMORY_ID - MemoryId::new(34), // EXTERNAL_CANISTER_INDEX_MEMORY_ID - // The following memory ids are still in use for the same purpose, but the datatype - // have changed and the memory needs to be cleaned up and rebuilt later. - MemoryId::new(30), // REQUEST_RESOURCE_INDEX_MEMORY_ID - MemoryId::new(31), // POLICY_RESOURCE_INDEX_MEMORY_ID - ] { - // This cleans up the memory by writing a single zero byte to the memory id, - // this will make the memory id available for reuse in the future. - // - // This makes sure that if `init` is called on the memory id, it will make sure - // it can be reused with a different datatype. - let memory = memory_manager.get(memory_id); - if memory.size() > 0 { - // This marks the memory as unused, this is because the StableBTreeMap - // implementation uses the first three bytes of the memory to store the MAGIC value [66, 84, 82] - // that indicates that the memory is used by the StableBTreeMap, so adding a single different byte - // in those first three bytes will make the memory available for reuse. - memory.write(0, &[0]); + // add new asset permissions: resources available to all users + let public_resources = [ + Resource::Asset(ResourceAction::List), + Resource::Asset(ResourceAction::Read(ResourceId::Any)), + ]; + + // build cache so that model validation can pass + USER_GROUP_REPOSITORY.build_cache(); + USER_REPOSITORY.build_cache(); + PERMISSION_REPOSITORY.build_cache(); + + for resource in public_resources { + let _ = PERMISSION_SERVICE.edit_permission(EditPermissionOperationInput { + resource, + auth_scope: Some(AuthScope::Authenticated), + user_groups: None, + users: None, + }); + } + + // add new asset permissions: inherit config from ManageSystemInfo + let manage_system_info_permissions_allow = PERMISSION_SERVICE + .get_permission(&Resource::System(SystemResourceAction::ManageSystemInfo)) + .allow; + + let sensitive_resources = [ + Resource::Asset(ResourceAction::Create), + Resource::Asset(ResourceAction::Update(ResourceId::Any)), + Resource::Asset(ResourceAction::Delete(ResourceId::Any)), + ]; + + for resource in sensitive_resources { + if let Err(err) = PERMISSION_SERVICE.edit_permission(EditPermissionOperationInput { + resource, + auth_scope: Some(manage_system_info_permissions_allow.auth_scope.clone()), + user_groups: Some(manage_system_info_permissions_allow.user_groups.clone()), + users: Some(manage_system_info_permissions_allow.users.clone()), + }) { + ic_cdk::println!("Failed to create new asset permission: {:?}", err); + } + } + + // add new asset policies + let policy_specifiers = [ + RequestSpecifier::AddAsset, + RequestSpecifier::EditAsset(ResourceIds::Any), + RequestSpecifier::RemoveAsset(ResourceIds::Any), + ]; + + let policies_to_copy = REQUEST_POLICY_REPOSITORY + .find_by_resource(Resource::System(SystemResourceAction::ManageSystemInfo)); + + for policy in policies_to_copy { + for specifier in policy_specifiers.iter() { + if let Err(err) = + REQUEST_POLICY_SERVICE.add_request_policy(AddRequestPolicyOperationInput { + specifier: specifier.clone(), + rule: policy.rule.clone(), + }) + { + ic_cdk::println!("Failed to create new asset policy: {:?}", err); } } - }); + } - // step 2: rebuilds the repositories to ensure the data is up-to-date - USER_GROUP_REPOSITORY.rebuild(); - USER_REPOSITORY.rebuild(); - ACCOUNT_REPOSITORY.rebuild(); - EXTERNAL_CANISTER_REPOSITORY.rebuild(); + ASSET_REPOSITORY.insert(INITIAL_ICP_ASSET.key(), INITIAL_ICP_ASSET.clone()); + + // rebuild repositories to apply the changes ADDRESS_BOOK_REPOSITORY.rebuild(); - PERMISSION_REPOSITORY.rebuild(); - REQUEST_POLICY_REPOSITORY.rebuild(); + TRANSFER_REPOSITORY.rebuild(); + ACCOUNT_REPOSITORY.rebuild(); REQUEST_REPOSITORY.rebuild(); } -impl<'de> Deserialize<'de> for Resource { +#[cfg(test)] +thread_local! { + pub static MIGRATED_ENTRIES: std::cell::RefCell = const { std::cell::RefCell::new(0) }; + + pub static MIGRATED_ACCOUNTS: std::cell::RefCell> = const { std::cell::RefCell::new(vec![]) }; +} + +#[derive(Debug, Deserialize)] +pub enum BlockchainStandard { + Native, + ICRC1, + ERC20, +} + +impl<'de> Deserialize<'de> for AddressBookEntry { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - const ENUM_NAME: &str = "Resource"; + #[derive(Debug, Deserialize)] + struct PreMigrationAddressBookEntry { + pub id: AddressBookEntryId, + pub address_owner: String, + pub address: String, + pub blockchain: Blockchain, + pub address_format: Option, + pub metadata: Metadata, + #[serde(default)] + pub labels: Vec, + pub last_modification_timestamp: Timestamp, + } - const CURRENT_VARIANTS: &[&str] = Resource::VARIANTS; - const REMOVED_VARIANTS: [&str; 1] = ["ChangeCanister"]; + let mut pre_migration_entry = PreMigrationAddressBookEntry::deserialize(deserializer)?; - // IMPORTANT: The size of the array must be hardcoded, to make sure it can be checked at compile-time. - static EXPECTED_VARIANTS: [&str; 11] = { - let variants: [&str; CURRENT_VARIANTS.len() + REMOVED_VARIANTS.len()] = [""; 11]; - concat_str_arrays!(CURRENT_VARIANTS, REMOVED_VARIANTS); + #[cfg(test)] + if pre_migration_entry.address_format.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); + } - variants - }; + // the frontend used to add BlockchainStandard.Native = "native" label to new address book entries + // this label is not needed anymore + pre_migration_entry.labels.retain(|label| label != "native"); + + Ok(AddressBookEntry { + id: pre_migration_entry.id, + address_owner: pre_migration_entry.address_owner, + address: pre_migration_entry.address, + blockchain: pre_migration_entry.blockchain, + address_format: pre_migration_entry + .address_format + .unwrap_or(AddressFormat::ICPAccountIdentifier), + metadata: pre_migration_entry.metadata, + labels: pre_migration_entry.labels, + last_modification_timestamp: pre_migration_entry.last_modification_timestamp, + }) + } +} - // Define the old version of the types for migration purposes - #[storable] - #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] - pub enum OldExternalCanisterResourceAction { - Create(OldCreateCanisterTarget), +impl<'de> Deserialize<'de> for Transfer { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Debug, Deserialize)] + struct PreMigrationTransfer { + pub id: TransferId, + pub initiator_user: UserId, + pub from_account: AccountId, + pub to_address: String, + pub status: TransferStatus, + pub amount: candid::Nat, + pub request_id: UUID, + pub fee: candid::Nat, + pub blockchain_network: String, + pub metadata: Metadata, + pub last_modification_timestamp: Timestamp, + pub created_timestamp: Timestamp, + pub from_asset: Option, + pub with_standard: Option, } - #[storable] - #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] - pub enum OldCreateCanisterTarget { - Any, - } + let pre_migration_entry = PreMigrationTransfer::deserialize(deserializer)?; - #[storable] - #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] - pub enum OldChangeCanisterResourceAction { - Create, + #[cfg(test)] + if pre_migration_entry.from_asset.is_none() || pre_migration_entry.with_standard.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); } - /// This enum facilitates the deserialization of the ExternalCanisterResourceAction enum. - /// - /// By creating it as an untagged enum, we can handle both the old and new formats of the enum and - /// serde will automatically choose the correct format based on the input data. - #[derive(Deserialize)] - #[serde(untagged)] - enum ExternalCanisterActionWrapper { - NewFormat(ExternalCanisterResourceAction), - OldFormat(OldExternalCanisterResourceAction), - } + Ok(Transfer { + id: pre_migration_entry.id, + initiator_user: pre_migration_entry.initiator_user, + from_account: pre_migration_entry.from_account, + to_address: pre_migration_entry.to_address, + status: pre_migration_entry.status, + amount: pre_migration_entry.amount, + request_id: pre_migration_entry.request_id, + fee: pre_migration_entry.fee, + blockchain_network: pre_migration_entry.blockchain_network, + metadata: pre_migration_entry.metadata, + last_modification_timestamp: pre_migration_entry.last_modification_timestamp, + created_timestamp: pre_migration_entry.created_timestamp, + from_asset: pre_migration_entry + .from_asset + .unwrap_or(INITIAL_ICP_ASSET_ID), + with_standard: pre_migration_entry + .with_standard + .unwrap_or(TokenStandard::InternetComputerNative), + }) + } +} - struct ResourceVisitor; +impl<'de> Deserialize<'de> for Account { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[allow(dead_code)] + #[derive(Debug, Deserialize)] + struct PreMigrationAccount { + pub id: AccountId, + pub name: String, + pub metadata: Metadata, + pub transfer_request_policy_id: Option, + pub configs_request_policy_id: Option, + pub last_modification_timestamp: Timestamp, + + // removed fields + pub balance: Option>, + pub blockchain: Option, + pub address: Option, + pub standard: Option, + pub symbol: Option, + pub decimals: Option, + + // new fields + pub seed: Option, + pub assets: Option>, + pub addresses: Option>, + } - impl<'de> Visitor<'de> for ResourceVisitor { - type Value = Resource; + let pre_migration_entry = PreMigrationAccount::deserialize(deserializer)?; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(&format!("a valid {} enum variant", ENUM_NAME)) - } + #[cfg(test)] + if pre_migration_entry.seed.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); - fn visit_enum(self, data: A) -> Result - where - A: EnumAccess<'de>, - { - let (variant, variant_access) = data.variant::()?; - - // Due to the fact that serde serialization uses a string representation of the enum variant, - // it is not possible to do a compile-time check for all variants of the enum. - match variant.as_str() { - // First the new formats - "ExternalCanister" => { - // Deserialize into the wrapper, which can handle both formats - let wrapper = - variant_access.newtype_variant::()?; - - // Try deserializing as the new format - match wrapper { - ExternalCanisterActionWrapper::NewFormat(new_format) => { - Ok(Resource::ExternalCanister(new_format)) - } - ExternalCanisterActionWrapper::OldFormat(_) => Ok( - Resource::ExternalCanister(ExternalCanisterResourceAction::Create), - ), - } - } - // `ChangeCanister` does not exist anymore, so we need to handle it here - "ChangeCanister" => { - // Consume the old format variant, this is to make sure there is no - // trailing data is left in the end of the deserialization, which would cause an error. - // - // The use of `Option`` is to make sure that the deserialization is successful. - let _ = variant_access.newtype_variant::(); - // The `ChangeCanister` variant was removed, so we need to handle it here - // and map it to the correct variant. - Ok(Resource::System(SystemResourceAction::Upgrade)) - } - // Then all the default cases - "Permission" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::Permission(value)) - } - "Account" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::Account(value)) - } - "AddressBook" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::AddressBook(value)) - } - "Notification" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::Notification(value)) - } - "Request" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::Request(value)) - } - "RequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::RequestPolicy(value)) - } - "System" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::System(value)) - } - "User" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::User(value)) - } - "UserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(Resource::UserGroup(value)) - } - _ => Err(de::Error::unknown_variant(&variant, &EXPECTED_VARIANTS)), - } + if let Some(address) = &pre_migration_entry.address { + MIGRATED_ACCOUNTS.with(|accounts| { + accounts + .borrow_mut() + .push((pre_migration_entry.id, address.clone())); + }); } } - deserializer.deserialize_enum(ENUM_NAME, &EXPECTED_VARIANTS, ResourceVisitor) + let seed = pre_migration_entry.seed.unwrap_or(pre_migration_entry.id); + + Ok(Account { + id: pre_migration_entry.id, + name: pre_migration_entry.name, + metadata: pre_migration_entry.metadata, + transfer_request_policy_id: pre_migration_entry.transfer_request_policy_id, + configs_request_policy_id: pre_migration_entry.configs_request_policy_id, + last_modification_timestamp: pre_migration_entry.last_modification_timestamp, + seed, + assets: pre_migration_entry.assets.unwrap_or(vec![AccountAsset { + asset_id: INITIAL_ICP_ASSET_ID, + balance: pre_migration_entry.balance.unwrap_or(None), + }]), + addresses: pre_migration_entry.addresses.unwrap_or_else(|| { + let blockchain = InternetComputer::create(); + vec![ + AccountAddress { + address: pre_migration_entry + .address + .unwrap_or(blockchain.generate_account_identifier(&seed)), + format: AddressFormat::ICPAccountIdentifier, + }, + AccountAddress { + address: blockchain.generate_icrc1_address(&seed), + format: AddressFormat::ICRC1Account, + }, + ] + }), + }) } } -impl<'de> Deserialize<'de> for RequestSpecifier { +impl<'de> Deserialize<'de> for TransferOperationInput { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - const ENUM_NAME: &str = "RequestSpecifier"; - - const CURRENT_VARIANTS: &[&str] = RequestSpecifier::VARIANTS; - const REMOVED_VARIANTS: [&str; 1] = ["ChangeCanister"]; - - // IMPORTANT: The size of the array must be hardcoded, to make sure it can be checked at compile-time. - static EXPECTED_VARIANTS: [&str; 23] = { - let variants: [&str; CURRENT_VARIANTS.len() + REMOVED_VARIANTS.len()] = - concat_str_arrays!(CURRENT_VARIANTS, REMOVED_VARIANTS); - - variants - }; - - // Define the old version of the types for migration purposes - #[derive(Deserialize)] - enum OldCreateExternalCanisterTarget { - Any, + #[derive(Debug, Deserialize)] + struct PreMigrationTransferOperationInput { + pub from_account_id: AccountId, + pub to: String, + pub amount: candid::Nat, + pub metadata: Metadata, + pub network: String, + pub fee: Option, + + pub from_asset_id: Option, + pub with_standard: Option, } - struct RequestSpecifierVisitor; - - impl<'de> Visitor<'de> for RequestSpecifierVisitor { - type Value = RequestSpecifier; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(&format!("a valid {} enum variant", ENUM_NAME)) - } + let pre_migration_entry = PreMigrationTransferOperationInput::deserialize(deserializer)?; - fn visit_enum(self, data: A) -> Result - where - A: EnumAccess<'de>, - { - let (variant, variant_access) = data.variant::()?; - - // Due to the fact that serde serialization uses a string representation of the enum variant, - // it is not possible to do a compile-time check for all variants of the enum. - match variant.as_str() { - // First the new formats - "CreateExternalCanister" => { - // Even though the value of the variant is not used, we still need to consume it - // to make sure there is no trailing data left in the end of the deserialization. - let _ = variant_access - .newtype_variant::>(); - - Ok(RequestSpecifier::CreateExternalCanister) - } - // `ChangeCanister` does not exist anymore, so we need to handle it here - "ChangeCanister" => Ok(RequestSpecifier::SystemUpgrade), - // Then all the default cases - "AddAccount" => Ok(RequestSpecifier::AddAccount), - "AddUser" => Ok(RequestSpecifier::AddUser), - "EditAccount" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditAccount(value)) - } - "EditUser" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditUser(value)) - } - "AddAddressBookEntry" => Ok(RequestSpecifier::AddAddressBookEntry), - "EditAddressBookEntry" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditAddressBookEntry(value)) - } - "RemoveAddressBookEntry" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::RemoveAddressBookEntry(value)) - } - "Transfer" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::Transfer(value)) - } - "SystemUpgrade" => Ok(RequestSpecifier::SystemUpgrade), - "SetDisasterRecovery" => Ok(RequestSpecifier::SetDisasterRecovery), - "ChangeExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::ChangeExternalCanister(value)) - } - "CallExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::CallExternalCanister(value)) - } - "EditPermission" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditPermission(value)) - } - "AddRequestPolicy" => Ok(RequestSpecifier::AddRequestPolicy), - "EditRequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditRequestPolicy(value)) - } - "RemoveRequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::RemoveRequestPolicy(value)) - } - "AddUserGroup" => Ok(RequestSpecifier::AddUserGroup), - "EditUserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::EditUserGroup(value)) - } - "RemoveUserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::RemoveUserGroup(value)) - } - "ManageSystemInfo" => Ok(RequestSpecifier::ManageSystemInfo), - "FundExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestSpecifier::FundExternalCanister(value)) - } - _ => Err(de::Error::unknown_variant(&variant, &EXPECTED_VARIANTS)), - } - } + #[cfg(test)] + if pre_migration_entry.from_asset_id.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); } - deserializer.deserialize_enum(ENUM_NAME, &EXPECTED_VARIANTS, RequestSpecifierVisitor) + Ok(TransferOperationInput { + from_account_id: pre_migration_entry.from_account_id, + to: pre_migration_entry.to, + amount: pre_migration_entry.amount, + metadata: pre_migration_entry.metadata, + network: pre_migration_entry.network, + fee: pre_migration_entry.fee, + from_asset_id: pre_migration_entry + .from_asset_id + .unwrap_or(INITIAL_ICP_ASSET_ID), + with_standard: pre_migration_entry + .with_standard + .unwrap_or(TokenStandard::InternetComputerNative), + }) } } -impl<'de> Deserialize<'de> for RequestOperation { +impl<'de> Deserialize<'de> for TransferOperation { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - const ENUM_NAME: &str = "RequestOperation"; + #[derive(Debug, Deserialize)] + struct PreMigrationTransferOperation { + pub transfer_id: Option, + pub input: TransferOperationInput, + pub fee: Option, - const CURRENT_VARIANTS: &[&str] = RequestOperation::VARIANTS; - const REMOVED_VARIANTS: [&str; 1] = ["ChangeCanister"]; + pub asset: Option, + } - // IMPORTANT: The size of the array must be hardcoded, to make sure it can be checked at compile-time. - static EXPECTED_VARIANTS: [&str; 24] = { - let variants: [&str; CURRENT_VARIANTS.len() + REMOVED_VARIANTS.len()] = - concat_str_arrays!(CURRENT_VARIANTS, REMOVED_VARIANTS); + let pre_migration_entry = PreMigrationTransferOperation::deserialize(deserializer)?; - variants - }; + #[cfg(test)] + if pre_migration_entry.asset.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); + } - struct RequestOperationVisitor; + Ok(TransferOperation { + transfer_id: pre_migration_entry.transfer_id, + input: pre_migration_entry.input, + fee: pre_migration_entry.fee, + asset: pre_migration_entry + .asset + .unwrap_or_else(|| INITIAL_ICP_ASSET.clone()), + }) + } +} - impl<'de> Visitor<'de> for RequestOperationVisitor { - type Value = RequestOperation; +impl<'de> Deserialize<'de> for AddAccountOperationInput { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[allow(dead_code)] + #[derive(Debug, Deserialize)] + struct PreMigrationAddAccountOperationInput { + pub name: String, + pub metadata: Metadata, + pub read_permission: Allow, + pub configs_permission: Allow, + pub transfer_permission: Allow, + pub configs_request_policy: Option, + pub transfer_request_policy: Option, + + // removed fields + pub blockchain: Option, + pub standard: Option, + + // new fields + pub assets: Option>, + } - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(&format!("a valid {} enum variant", ENUM_NAME)) - } + let pre_migration_entry = PreMigrationAddAccountOperationInput::deserialize(deserializer)?; - fn visit_enum(self, data: A) -> Result - where - A: EnumAccess<'de>, - { - let (variant, variant_access) = data.variant::()?; - - // Due to the fact that serde serialization uses a string representation of the enum variant, - // it is not possible to do a compile-time check for all variants of the enum. - match variant.as_str() { - // First the new formats - // `ChangeCanister` does not exist anymore, so we need to handle it here - "ChangeCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::SystemUpgrade(value)) - } - // Then all the default cases - "Transfer" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::Transfer(value)) - } - "AddAccount" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::AddAccount(value)) - } - "EditAccount" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditAccount(value)) - } - "AddAddressBookEntry" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::AddAddressBookEntry(value)) - } - "EditAddressBookEntry" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditAddressBookEntry(value)) - } - "RemoveAddressBookEntry" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::RemoveAddressBookEntry(value)) - } - "AddUser" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::AddUser(value)) - } - "EditUser" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditUser(value)) - } - "EditPermission" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditPermission(value)) - } - "AddUserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::AddUserGroup(value)) - } - "EditUserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditUserGroup(value)) - } - "RemoveUserGroup" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::RemoveUserGroup(value)) - } - "SystemUpgrade" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::SystemUpgrade(value)) - } - "ChangeExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::ChangeExternalCanister(value)) - } - "ConfigureExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::ConfigureExternalCanister(value)) - } - "CreateExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::CreateExternalCanister(value)) - } - "CallExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::CallExternalCanister(value)) - } - "FundExternalCanister" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::FundExternalCanister(value)) - } - "AddRequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::AddRequestPolicy(value)) - } - "EditRequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::EditRequestPolicy(value)) - } - "RemoveRequestPolicy" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::RemoveRequestPolicy(value)) - } - "ManageSystemInfo" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::ManageSystemInfo(value)) - } - "SetDisasterRecovery" => { - let value = variant_access.newtype_variant()?; - Ok(RequestOperation::SetDisasterRecovery(value)) - } - _ => Err(de::Error::unknown_variant(&variant, &EXPECTED_VARIANTS)), - } - } + #[cfg(test)] + if pre_migration_entry.assets.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); } - deserializer.deserialize_enum(ENUM_NAME, &EXPECTED_VARIANTS, RequestOperationVisitor) + Ok(AddAccountOperationInput { + name: pre_migration_entry.name, + metadata: pre_migration_entry.metadata, + read_permission: pre_migration_entry.read_permission, + configs_permission: pre_migration_entry.configs_permission, + transfer_permission: pre_migration_entry.transfer_permission, + configs_request_policy: pre_migration_entry.configs_request_policy, + transfer_request_policy: pre_migration_entry.transfer_request_policy, + assets: pre_migration_entry + .assets + .unwrap_or_else(|| vec![INITIAL_ICP_ASSET_ID]), + }) } } -// Repositories should only implement the `RebuildRepository` trait if they are affected by the migration, -// otherwise, they should not implement the trait. -// -// The ones affected should have the implementation here. - -impl RebuildRepository> for RequestRepository { - fn rebuild(&self) { - let mut requests = Vec::with_capacity(self.len()); - Self::with_db(|db| db.iter().for_each(|(_, v)| requests.push(v))); - - // Then clear the repository to drop the existing data. - Self::with_db(|db| db.clear_new()); - - // Clear the indexes to avoid duplicates. - self.clear_indexes(); - - for mut request in requests.into_iter() { - // Then add the updated indexes. - self.add_entry_indexes(&request); - // Clear the module field if the request is finalized to save memory. - if request.is_finalized() { - if let RequestOperation::SystemUpgrade(operation) = &mut request.operation { - operation.input.module = Vec::new(); - } - } +impl<'de> Deserialize<'de> for AddAddressBookEntryOperationInput { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[allow(dead_code)] + #[derive(Debug, Deserialize)] + struct PreMigrationAddAddressBookEntryOperationInput { + pub address_owner: String, + pub address: String, + pub blockchain: Blockchain, + #[serde(default)] + pub labels: Vec, + pub metadata: Vec, + + // added fields + pub address_format: Option, + } - Self::with_db(|db| db.insert(request.key(), request)); + let pre_migration_entry = + PreMigrationAddAddressBookEntryOperationInput::deserialize(deserializer)?; + + #[cfg(test)] + if pre_migration_entry.address_format.is_none() { + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() += 1; + }); } + + Ok(AddAddressBookEntryOperationInput { + address_owner: pre_migration_entry.address_owner, + address: pre_migration_entry.address, + blockchain: pre_migration_entry.blockchain, + labels: pre_migration_entry.labels, + metadata: pre_migration_entry.metadata, + address_format: pre_migration_entry + .address_format + .unwrap_or(AddressFormat::ICPAccountIdentifier), + }) } } -impl RebuildRepository> for PermissionRepository {} -impl RebuildRepository> for AccountRepository {} impl RebuildRepository> for AddressBookRepository { } -impl RebuildRepository> - for ExternalCanisterRepository -{ + +impl RebuildRepository> for TransferRepository {} +impl RebuildRepository> for AccountRepository {} +impl RebuildRepository> for RequestRepository {} + +#[cfg(test)] +mod test { + use std::{borrow::BorrowMut, fs}; + + use ic_stable_structures::{memory_manager::MemoryId, Memory}; + use orbit_essentials::repository::{RebuildRepository, Repository}; + + use crate::{ + core::{ + ACCOUNT_MEMORY_ID, ADDRESS_BOOK_MEMORY_ID, MEMORY_MANAGER, REQUEST_MEMORY_ID, + TRANSFER_MEMORY_ID, WASM_PAGE_SIZE, + }, + migration::{INITIAL_ICP_ASSET_ID, MIGRATED_ACCOUNTS, MIGRATED_ENTRIES}, + models::AddressFormat, + repositories::{ + address_book, ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, REQUEST_REPOSITORY, + TRANSFER_REPOSITORY, + }, + STABLE_MEMORY_VERSION, + }; + + fn restore_snapshot(label: &str, memory_id: MemoryId) { + let snapshot = fs::read(format!( + "src/migration_tests/snapshots/{}_v{}.bin", + label, + STABLE_MEMORY_VERSION - 1 + )) + .unwrap(); + + let mut memory = MEMORY_MANAGER.with(|mm| mm.borrow_mut().get(memory_id)); + memory.grow(snapshot.len() as u64 / WASM_PAGE_SIZE as u64 + 1u64); + memory.borrow_mut().write(0, &snapshot); + } + + #[test] + fn test_address_book_migration() { + restore_snapshot("address_book_repository", ADDRESS_BOOK_MEMORY_ID); + + address_book::ADDRESS_BOOK_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) > 0); + + ADDRESS_BOOK_REPOSITORY.rebuild(); + + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() = 0; + }); + + address_book::ADDRESS_BOOK_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) == 0); + } + + #[test] + fn test_transfer_migration() { + restore_snapshot("transfer_repository", TRANSFER_MEMORY_ID); + + TRANSFER_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) > 0); + + TRANSFER_REPOSITORY.rebuild(); + + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() = 0; + }); + + TRANSFER_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) == 0); + } + + #[test] + fn test_account_migration() { + restore_snapshot("account_repository", ACCOUNT_MEMORY_ID); + + ACCOUNT_REPOSITORY.list(); + assert!(MIGRATED_ACCOUNTS.with(|entries| entries.borrow_mut().len()) > 0); + + ACCOUNT_REPOSITORY.rebuild(); + + let accounts = ACCOUNT_REPOSITORY.list(); + for account in accounts { + assert!(account.seed == account.id); + assert!( + account.assets.first().expect("No assets found").asset_id == INITIAL_ICP_ASSET_ID + ); + + assert!(account.addresses.len() == 2); + + let migrated_account = MIGRATED_ACCOUNTS.with(|accounts| { + accounts + .borrow() + .iter() + .find(|(id, _)| *id == account.id) + .expect("Account not found in migrated accounts") + .clone() + }); + + assert!(account + .addresses + .iter() + .any(|address| address.address == migrated_account.1 + && address.format == AddressFormat::ICPAccountIdentifier)); + assert!(account + .addresses + .iter() + .any(|address| address.format == AddressFormat::ICRC1Account)); + } + + MIGRATED_ACCOUNTS.with(|entries| { + entries.borrow_mut().clear(); + }); + + ACCOUNT_REPOSITORY.list(); + assert!(MIGRATED_ACCOUNTS.with(|entries| entries.borrow_mut().len()) == 0); + } + + #[test] + fn test_request_migration() { + restore_snapshot("request_repository", REQUEST_MEMORY_ID); + + REQUEST_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) > 0); + + REQUEST_REPOSITORY.rebuild(); + + MIGRATED_ENTRIES.with(|entries| { + *entries.borrow_mut() = 0; + }); + + REQUEST_REPOSITORY.list(); + assert!(MIGRATED_ENTRIES.with(|entries| *entries.borrow_mut()) == 0); + } } -impl RebuildRepository> for UserGroupRepository {} -impl RebuildRepository> for UserRepository {} -impl RebuildRepository> for RequestPolicyRepository {} diff --git a/core/station/impl/src/migration_tests/mod.rs b/core/station/impl/src/migration_tests/mod.rs new file mode 100644 index 000000000..c21637cfb --- /dev/null +++ b/core/station/impl/src/migration_tests/mod.rs @@ -0,0 +1,280 @@ +#[cfg(test)] +mod test { + + use std::fs; + + use ic_cdk::api::stable::WASM_PAGE_SIZE_IN_BYTES; + use ic_stable_structures::{memory_manager::MemoryId, Memory}; + use orbit_essentials::{model::ModelKey, repository::Repository}; + + use crate::{ + core::{ + with_memory_manager, ACCOUNT_MEMORY_ID, ADDRESS_BOOK_MEMORY_ID, REQUEST_MEMORY_ID, + TRANSFER_MEMORY_ID, + }, + models::{ + permission::Allow, Account, AccountAddress, AccountAsset, AccountBalance, + AddAccountOperation, AddAccountOperationInput, AddAddressBookEntryOperation, + AddAddressBookEntryOperationInput, AddressBookEntry, AddressFormat, Blockchain, + ChangeAssets, EditAccountOperation, EditAccountOperationInput, Metadata, Request, + RequestExecutionPlan, RequestOperation, RequestPolicyRule, RequestPolicyRuleInput, + RequestStatus, TokenStandard, Transfer, TransferOperation, TransferOperationInput, + TransferStatus, + }, + repositories::{ + ACCOUNT_REPOSITORY, ADDRESS_BOOK_REPOSITORY, REQUEST_REPOSITORY, TRANSFER_REPOSITORY, + }, + services::{INITIAL_ICP_ASSET, INITIAL_ICP_ASSET_ID}, + STABLE_MEMORY_VERSION, + }; + + fn save_memory_snapshot(label: &str, memory_id: MemoryId) { + let snapshot = with_memory_manager(|memory_manager| { + let mem = memory_manager.get(memory_id); + let mut snapshot = vec![0; mem.size() as usize * WASM_PAGE_SIZE_IN_BYTES as usize]; + mem.read(0, &mut snapshot); + snapshot + }); + + fs::write( + format!( + "src/migration_tests/snapshots/{}_v{}.bin", + label, STABLE_MEMORY_VERSION + ), + snapshot, + ) + .unwrap(); + } + + fn generate_address_book_repo_snapshot() { + let entries: Vec = vec![ + AddressBookEntry { + id: [0u8; 16], + address: "0x1234567890abcdef".to_string(), + address_format: AddressFormat::ICPAccountIdentifier, + address_owner: "Alice".to_string(), + blockchain: crate::models::Blockchain::InternetComputer, + labels: vec!["Alice".to_string(), "Bob".to_string()], + last_modification_timestamp: 0, + metadata: Metadata::default(), + }, + AddressBookEntry { + id: [1u8; 16], + address: "0x1234567890abcdef".to_string(), + address_format: AddressFormat::ICPAccountIdentifier, + address_owner: "Alice".to_string(), + blockchain: crate::models::Blockchain::InternetComputer, + labels: vec!["Alice".to_string(), "Bob".to_string()], + last_modification_timestamp: 0, + metadata: Metadata::new( + [ + ("key1".to_string(), "value1".to_string()), + ("key2".to_string(), "value2".to_string()), + ] + .into_iter() + .collect(), + ), + }, + ]; + + for entry in entries { + ADDRESS_BOOK_REPOSITORY.insert(entry.key(), entry); + } + + save_memory_snapshot("address_book_repository", ADDRESS_BOOK_MEMORY_ID); + } + + fn generate_transfer_repo_snapshot() { + let entries: Vec = vec![Transfer { + id: [0u8; 16], + initiator_user: [0u8; 16], + from_account: [0u8; 16], + from_asset: [0u8; 16], + with_standard: TokenStandard::InternetComputerNative, + to_address: "0x1234567890abcdef".to_string(), + status: TransferStatus::Completed { + signature: None, + hash: None, + completed_at: 0, + }, + amount: 100u64.into(), + request_id: [0u8; 16], + fee: 100u64.into(), + blockchain_network: "mainnet".to_string(), + metadata: Metadata::default(), + last_modification_timestamp: 0, + created_timestamp: 0, + }]; + + for entry in entries { + TRANSFER_REPOSITORY.insert(entry.key(), entry); + } + + save_memory_snapshot("transfer_repository", TRANSFER_MEMORY_ID); + } + + fn generate_account_repo_snapshot() { + let entries: Vec = vec![Account { + id: [0u8; 16], + name: "Test account".to_string(), + assets: vec![AccountAsset { + asset_id: [0u8; 16], + balance: Some(AccountBalance { + balance: 100u64.into(), + last_modification_timestamp: 0, + }), + }], + seed: [0u8; 16], + addresses: vec![ + AccountAddress { + address: "0x1234567890abcdef".to_string(), + format: AddressFormat::ICPAccountIdentifier, + }, + AccountAddress { + address: "0x1234567890abcdef".to_string(), + format: AddressFormat::ICRC1Account, + }, + ], + metadata: Metadata::default(), + transfer_request_policy_id: None, + configs_request_policy_id: None, + last_modification_timestamp: 0, + }]; + + for entry in entries { + ACCOUNT_REPOSITORY.insert(entry.key(), entry); + } + + save_memory_snapshot("account_repository", ACCOUNT_MEMORY_ID); + } + + fn generate_request_repo_snapshot() { + let entries: Vec = vec![ + Request { + id: [0u8; 16], + title: "Test transfer".to_string(), + summary: None, + requested_by: [0u8; 16], + status: RequestStatus::Approved, + operation: RequestOperation::Transfer(TransferOperation { + fee: None, + transfer_id: Some([0u8; 16]), + asset: INITIAL_ICP_ASSET.clone(), + input: TransferOperationInput { + from_account_id: [0u8; 16], + from_asset_id: INITIAL_ICP_ASSET_ID, + with_standard: TokenStandard::InternetComputerNative, + to: "0x1234567890abcdef".to_string(), + amount: 100u64.into(), + metadata: Metadata::default(), + network: "mainnet".to_string(), + fee: None, + }, + }), + expiration_dt: 0, + execution_plan: RequestExecutionPlan::Immediate, + approvals: vec![], + created_timestamp: 0, + last_modification_timestamp: 0, + }, + Request { + id: [1u8; 16], + title: "Test add account".to_string(), + summary: None, + requested_by: [0u8; 16], + status: RequestStatus::Approved, + operation: RequestOperation::AddAccount(AddAccountOperation { + account_id: None, + input: AddAccountOperationInput { + name: "Test account".to_string(), + assets: vec![[0u8; 16]], + metadata: Metadata::new( + [ + ("key1".to_string(), "value1".to_string()), + ("key2".to_string(), "value2".to_string()), + ] + .into_iter() + .collect(), + ), + read_permission: Allow::default(), + configs_permission: Allow::default(), + transfer_permission: Allow::default(), + configs_request_policy: Some(RequestPolicyRule::AutoApproved), + transfer_request_policy: Some(RequestPolicyRule::AutoApproved), + }, + }), + expiration_dt: 0, + execution_plan: RequestExecutionPlan::Immediate, + approvals: vec![], + created_timestamp: 0, + last_modification_timestamp: 0, + }, + Request { + id: [2u8; 16], + title: "Test edit account".to_string(), + summary: None, + requested_by: [0u8; 16], + status: RequestStatus::Approved, + operation: RequestOperation::EditAccount(EditAccountOperation { + input: EditAccountOperationInput { + account_id: [0u8; 16], + name: Some("Test account".to_string()), + change_assets: Some(ChangeAssets::Change { + add_assets: vec![[0u8; 16], [1u8; 16]], + remove_assets: vec![[2u8; 16], [3u8; 16]], + }), + read_permission: Some(Allow::default()), + configs_permission: Some(Allow::default()), + transfer_permission: Some(Allow::default()), + configs_request_policy: Some(RequestPolicyRuleInput::Set( + RequestPolicyRule::AutoApproved, + )), + transfer_request_policy: Some(RequestPolicyRuleInput::Remove), + }, + }), + expiration_dt: 0, + execution_plan: RequestExecutionPlan::Immediate, + approvals: vec![], + created_timestamp: 0, + last_modification_timestamp: 0, + }, + Request { + id: [3u8; 16], + title: "Test add address book entry".to_string(), + summary: None, + requested_by: [0u8; 16], + status: RequestStatus::Approved, + operation: RequestOperation::AddAddressBookEntry(AddAddressBookEntryOperation { + input: AddAddressBookEntryOperationInput { + address_owner: "Alice".to_string(), + address: "0x1234567890abcdef".to_string(), + address_format: AddressFormat::ICPAccountIdentifier, + blockchain: Blockchain::InternetComputer, + labels: vec!["label_1".to_string(), "label_2".to_string()], + metadata: vec![], + }, + address_book_entry_id: Some([0u8; 16]), + }), + expiration_dt: 0, + execution_plan: RequestExecutionPlan::Immediate, + approvals: vec![], + created_timestamp: 0, + last_modification_timestamp: 0, + }, + ]; + + for entry in entries { + REQUEST_REPOSITORY.insert(entry.key(), entry); + } + + save_memory_snapshot("request_repository", REQUEST_MEMORY_ID); + } + + #[test] + fn make_repository_snapshots() { + generate_address_book_repo_snapshot(); + generate_transfer_repo_snapshot(); + generate_account_repo_snapshot(); + generate_request_repo_snapshot(); + } +} diff --git a/core/station/impl/src/migration_tests/snapshots/account_repository_v1.bin b/core/station/impl/src/migration_tests/snapshots/account_repository_v1.bin new file mode 100644 index 000000000..bcf400472 Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/account_repository_v1.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/account_repository_v2.bin b/core/station/impl/src/migration_tests/snapshots/account_repository_v2.bin new file mode 100644 index 000000000..6f399b1f9 Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/account_repository_v2.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/address_book_repository_v1.bin b/core/station/impl/src/migration_tests/snapshots/address_book_repository_v1.bin new file mode 100644 index 000000000..b53d45fdb Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/address_book_repository_v1.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/address_book_repository_v2.bin b/core/station/impl/src/migration_tests/snapshots/address_book_repository_v2.bin new file mode 100644 index 000000000..9d9b778e9 Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/address_book_repository_v2.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/request_repository_v1.bin b/core/station/impl/src/migration_tests/snapshots/request_repository_v1.bin new file mode 100644 index 000000000..a7c10969b Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/request_repository_v1.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/request_repository_v2.bin b/core/station/impl/src/migration_tests/snapshots/request_repository_v2.bin new file mode 100644 index 000000000..935f58a6d Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/request_repository_v2.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/transfer_repository_v1.bin b/core/station/impl/src/migration_tests/snapshots/transfer_repository_v1.bin new file mode 100644 index 000000000..8ba23bd6d Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/transfer_repository_v1.bin differ diff --git a/core/station/impl/src/migration_tests/snapshots/transfer_repository_v2.bin b/core/station/impl/src/migration_tests/snapshots/transfer_repository_v2.bin new file mode 100644 index 000000000..9933d78c8 Binary files /dev/null and b/core/station/impl/src/migration_tests/snapshots/transfer_repository_v2.bin differ diff --git a/core/station/impl/src/models/account.rs b/core/station/impl/src/models/account.rs index 4fc52ce3e..b614a7086 100644 --- a/core/station/impl/src/models/account.rs +++ b/core/station/impl/src/models/account.rs @@ -1,8 +1,11 @@ -use super::{AccountBalance, Blockchain, BlockchainStandard}; -use crate::errors::AccountError; +use super::{AccountBalance, AssetId}; +use crate::core::validation::{EnsureAsset, EnsureIdExists}; +use crate::core::ACCOUNT_BALANCE_FRESHNESS_IN_MS; +use crate::errors::{AccountError, RecordValidationError}; use crate::models::Metadata; use crate::repositories::request_policy::REQUEST_POLICY_REPOSITORY; use candid::{CandidType, Deserialize}; +use ic_ledger_types::AccountIdentifier; use orbit_essentials::model::ModelKey; use orbit_essentials::repository::Repository; use orbit_essentials::storable; @@ -10,37 +13,31 @@ use orbit_essentials::{ model::{ModelValidator, ModelValidatorResult}, types::{Timestamp, UUID}, }; +use std::fmt; +use std::str::FromStr; use std::{collections::HashMap, hash::Hash}; -/// The account metadata key for the asset symbol; -pub const ACCOUNT_METADATA_SYMBOL_KEY: &str = "symbol"; - /// The account id, which is a UUID. pub type AccountId = UUID; +pub type AccountSeed = UUID; /// Represents a account in the system. /// -/// A account can be associated with one or more users and can only hold one type of asset, -/// which is defined by the blockchain, standard and symbol. -#[storable] +/// A account can be associated with one or more users and can hold multiple types of assets. An account +/// can have multiple addresses, one of each address format that the assets support. +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Account { /// The account id, which is a UUID. pub id: AccountId, - /// The blockchain type (e.g. `icp`, `eth`, `btc`) - pub blockchain: Blockchain, - /// The account address (e.g. `0x1234`, etc.) - pub address: String, - /// The blockchain standard (e.g. `native`, `icrc1`, `erc20`, etc.) - pub standard: BlockchainStandard, - /// The asset symbol (e.g. `ICP`, `ETH`, `BTC`, etc.) - pub symbol: String, - /// The asset decimals (e.g. `8` for `BTC`, `18` for `ETH`, etc.) - pub decimals: u32, /// The account name (e.g. `My Main Account`) pub name: String, - /// The account balance, which is the amount of the asset that the account holds. - pub balance: Option, + /// The seed for address creation. + pub seed: AccountSeed, + /// The list of assets this account holds. + pub assets: Vec, + /// The list of addresses that belong to this account. + pub addresses: Vec, /// The account metadata, which is a list of key-value pairs, /// where the key is unique and the first entry in the tuple, /// and the value is the second entry in the tuple. @@ -72,40 +69,109 @@ impl ModelKey for Account { } } -#[derive(CandidType, Deserialize, Debug, Clone)] -pub struct AccountCallerPrivileges { - pub id: UUID, - pub can_edit: bool, - pub can_transfer: bool, +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct AccountAsset { + pub asset_id: AssetId, + pub balance: Option, } -fn validate_symbol(symbol: &str) -> ModelValidatorResult { - if (symbol.len() < Account::SYMBOL_RANGE.0 as usize) - || (symbol.len() > Account::SYMBOL_RANGE.1 as usize) - { - return Err(AccountError::ValidationError { - info: format!( - "Account symbol length must be between {} and {}", - Account::SYMBOL_RANGE.0, - Account::SYMBOL_RANGE.1 - ), - }); +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct AccountAddress { + pub address: String, + pub format: AddressFormat, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum AddressFormat { + ICPAccountIdentifier, + ICRC1Account, + EthereumAddress, + BitcoinAddressP2WPKH, + BitcoinAddressP2TR, +} + +impl fmt::Display for AddressFormat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AddressFormat::ICPAccountIdentifier => write!(f, "icp_account_identifier"), + AddressFormat::ICRC1Account => write!(f, "icrc1_account"), + AddressFormat::EthereumAddress => write!(f, "ethereum_address"), + AddressFormat::BitcoinAddressP2WPKH => write!(f, "bitcoin_address_p2wpkh"), + AddressFormat::BitcoinAddressP2TR => write!(f, "bitcoin_address_p2tr"), + } } +} - Ok(()) +impl FromStr for AddressFormat { + type Err = AccountError; + + fn from_str(s: &str) -> Result { + match s { + "icp_account_identifier" => Ok(AddressFormat::ICPAccountIdentifier), + "icrc1_account" => Ok(AddressFormat::ICRC1Account), + "ethereum_address" => Ok(AddressFormat::EthereumAddress), + "bitcoin_address_p2wpkh" => Ok(AddressFormat::BitcoinAddressP2WPKH), + "bitcoin_address_p2tr" => Ok(AddressFormat::BitcoinAddressP2TR), + _ => Err(AccountError::UnknownAddressFormat { + address_format: s.to_string(), + }), + } + } } -fn validate_address(address: &str) -> ModelValidatorResult { - if (address.len() < Account::ADDRESS_RANGE.0 as usize) - || (address.len() > Account::ADDRESS_RANGE.1 as usize) - { - return Err(AccountError::InvalidAddressLength { - min_length: Account::ADDRESS_RANGE.0, - max_length: Account::ADDRESS_RANGE.1, - }); +impl AddressFormat { + pub fn validate_address(&self, address: &str) -> ModelValidatorResult { + match self { + AddressFormat::ICPAccountIdentifier => AccountIdentifier::from_hex(address) + .map_err(|_| AccountError::InvalidAddress { + address: address.to_string(), + address_format: self.to_string(), + }) + .map(|_| ()), + AddressFormat::ICRC1Account => { + icrc_ledger_types::icrc1::account::Account::from_str(address) + .map_err(|_| AccountError::InvalidAddress { + address: address.to_string(), + address_format: self.to_string(), + }) + .map(|_| ()) + } + AddressFormat::EthereumAddress => todo!(), + AddressFormat::BitcoinAddressP2WPKH => todo!(), + AddressFormat::BitcoinAddressP2TR => todo!(), + } } +} - Ok(()) +impl AccountAddress { + const ADDRESS_RANGE: (u8, u8) = (1, 255); +} + +impl ModelValidator for AccountAddress { + fn validate(&self) -> ModelValidatorResult { + if (self.address.len() < AccountAddress::ADDRESS_RANGE.0 as usize) + || (self.address.len() > AccountAddress::ADDRESS_RANGE.1 as usize) + { + return Err(AccountError::InvalidAddressLength { + min_length: AccountAddress::ADDRESS_RANGE.0, + max_length: AccountAddress::ADDRESS_RANGE.1, + }); + } + + self.format.validate_address(&self.address)?; + + Ok(()) + } +} + +#[derive(CandidType, Deserialize, Debug, Clone)] +pub struct AccountCallerPrivileges { + pub id: UUID, + pub can_edit: bool, + pub can_transfer: bool, } fn validate_policy_id(policy_id: &UUID, field_name: &str) -> ModelValidatorResult { @@ -117,11 +183,40 @@ fn validate_policy_id(policy_id: &UUID, field_name: &str) -> ModelValidatorResul Ok(()) } +fn validate_asset_id(asset_id: &AssetId) -> ModelValidatorResult { + EnsureAsset::id_exists(asset_id).map_err(|err| match err { + RecordValidationError::NotFound { id, .. } => AccountError::AssetDoesNotExist { id }, + })?; + + Ok(()) +} + +fn validate_account_name(name: &str) -> ModelValidatorResult { + if (name.len() < Account::NAME_RANGE.0 as usize) + || (name.len() > Account::NAME_RANGE.1 as usize) + { + return Err(AccountError::InvalidNameLength { + min_length: Account::NAME_RANGE.0, + max_length: Account::NAME_RANGE.1, + }); + } + + Ok(()) +} + impl ModelValidator for Account { fn validate(&self) -> ModelValidatorResult { self.metadata.validate()?; - validate_symbol(&self.symbol)?; - validate_address(&self.address)?; + + validate_account_name(&self.name)?; + + for asset in &self.assets { + validate_asset_id(&asset.asset_id)?; + } + + for address in &self.addresses { + address.validate()?; + } if let Some(transfer_request_policy_id) = &self.transfer_request_policy_id { validate_policy_id(transfer_request_policy_id, "transfer_request_policy_id")?; @@ -137,6 +232,7 @@ impl ModelValidator for Account { impl Account { pub const OWNERS_RANGE: (u8, u8) = (1, 10); pub const ADDRESS_RANGE: (u8, u8) = (1, 255); + pub const NAME_RANGE: (u8, u8) = (1, 64); pub const SYMBOL_RANGE: (u8, u8) = (1, 8); pub const MAX_POLICIES: u8 = 10; @@ -154,59 +250,63 @@ impl Account { } } -#[cfg(test)] -mod tests { - use super::account_test_utils::mock_account; - use super::*; - - #[test] - fn fail_symbol_validation_too_short() { - let mut account = mock_account(); - account.symbol = "a".repeat(0); - - let result = validate_symbol(&account.symbol); +pub enum BalanceQueryState { + StaleRefreshing, + Stale, + Fresh, +} - assert!(result.is_err()); - assert_eq!( - result.unwrap_err(), - AccountError::ValidationError { - info: "Account symbol length must be between 1 and 8".to_string() - } - ); +impl fmt::Display for BalanceQueryState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BalanceQueryState::StaleRefreshing => write!(f, "stale_refreshing"), + BalanceQueryState::Stale => write!(f, "stale"), + BalanceQueryState::Fresh => write!(f, "fresh"), + } } +} - #[test] - fn fail_symbol_validation_too_long() { - let mut account = mock_account(); - account.symbol = "a".repeat(Account::SYMBOL_RANGE.1 as usize + 1); +impl From<&AccountBalance> for BalanceQueryState { + fn from(balance: &AccountBalance) -> Self { + let balance_age_ms = crate::core::ic_cdk::api::time() + .saturating_sub(balance.last_modification_timestamp) + / 1_000_000; + if balance_age_ms <= ACCOUNT_BALANCE_FRESHNESS_IN_MS { + BalanceQueryState::Fresh + } else { + BalanceQueryState::Stale + } + } +} - let result = validate_symbol(&account.symbol); +#[cfg(test)] +mod tests { + use super::account_test_utils::mock_account; + use super::*; - assert!(result.is_err()); - assert_eq!( - result.unwrap_err(), - AccountError::ValidationError { - info: "Account symbol length must be between 1 and 8".to_string() - } - ); - } + const VALID_ACCOUNT_IDENTIFIER: &str = + "5c76bc95e544204de4928e4d901e52b49df248b9c346807040e7af75aa61f4b3"; #[test] - fn test_symbol_validation() { - let mut account = mock_account(); - account.symbol = "a".to_string(); + fn fail_address_format_invalid() { + let format = AddressFormat::ICPAccountIdentifier; - let result = validate_symbol(&account.symbol); + format + .validate_address("foo") + .expect_err("foo is not a valid AccountIdentifier"); - assert!(result.is_ok()); + format + .validate_address(VALID_ACCOUNT_IDENTIFIER) + .expect("The address is valid"); } - #[test] - fn fail_address_too_short() { - let mut account = mock_account(); - account.address = "".to_string(); + fn fail_address_length_invalid() { + let mut account_address: AccountAddress = AccountAddress { + address: "".to_string(), + format: AddressFormat::ICPAccountIdentifier, + }; - let result = validate_address(&account.address); + let result = account_address.validate(); assert!(result.is_err()); assert_eq!( @@ -216,14 +316,10 @@ mod tests { max_length: 255 } ); - } - #[test] - fn fail_address_too_long() { - let mut account = mock_account(); - account.address = "a".repeat(Account::ADDRESS_RANGE.1 as usize + 1); + account_address.address = "a".repeat(Account::ADDRESS_RANGE.1 as usize + 1); - let result = validate_address(&account.address); + let result = account_address.validate(); assert!(result.is_err()); assert_eq!( @@ -235,16 +331,6 @@ mod tests { ); } - #[test] - fn test_address_validation() { - let mut account = mock_account(); - account.address = "a".to_string(); - - let result = validate_address(&account.address); - - assert!(result.is_ok()); - } - #[test] fn fail_missing_policy_id() { let mut account = mock_account(); @@ -279,21 +365,33 @@ mod tests { pub mod account_test_utils { use super::*; use crate::repositories::ACCOUNT_REPOSITORY; + use candid::Principal; + use ic_ledger_types::Subaccount; use orbit_essentials::repository::Repository; use uuid::Uuid; pub fn mock_account() -> Account { + let id = *Uuid::new_v4().as_bytes(); + Account { - id: *Uuid::new_v4().as_bytes(), - address: "0x1234".to_string(), - balance: None, - blockchain: Blockchain::InternetComputer, - decimals: 0u32, + id, name: "foo".to_string(), - standard: BlockchainStandard::Native, + + seed: id, + + assets: vec![AccountAsset { + asset_id: [0; 16], + balance: None, + }], + + addresses: vec![AccountAddress { + address: AccountIdentifier::new(&Principal::anonymous(), &Subaccount([0; 32])) + .to_hex(), + format: AddressFormat::ICPAccountIdentifier, + }], + last_modification_timestamp: 0, metadata: Metadata::mock(), - symbol: "ICP".to_string(), transfer_request_policy_id: None, configs_request_policy_id: None, } diff --git a/core/station/impl/src/models/address_book.rs b/core/station/impl/src/models/address_book.rs index fc4120dfd..ca658bb9a 100644 --- a/core/station/impl/src/models/address_book.rs +++ b/core/station/impl/src/models/address_book.rs @@ -1,4 +1,4 @@ -use super::Blockchain; +use super::{AddressFormat, Blockchain}; use crate::errors::AddressBookError; use crate::models::Metadata; use candid::{CandidType, Deserialize}; @@ -14,7 +14,7 @@ use std::{collections::HashMap, hash::Hash}; pub type AddressBookEntryId = UUID; /// Represents an address book entry in the system. -#[storable] +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct AddressBookEntry { /// The address book entry id, which is a UUID. @@ -25,6 +25,8 @@ pub struct AddressBookEntry { pub address: String, /// The blockchain type (e.g. `icp`, `eth`, `btc`) pub blockchain: Blockchain, + /// The address' format. + pub address_format: AddressFormat, /// The address' metadata. pub metadata: Metadata, /// The labels associated with the address. @@ -135,12 +137,13 @@ impl AddressBookEntry { } } -#[derive(CandidType, Deserialize, Debug, Clone)] +#[derive(Deserialize, Debug, Clone)] pub struct ListAddressBookEntriesInput { pub ids: Option>, pub addresses: Option>, pub blockchain: Option, pub labels: Option>, + pub address_formats: Option>, } #[derive(CandidType, Deserialize, Debug, Clone)] @@ -265,6 +268,7 @@ pub mod address_book_entry_test_utils { id: *Uuid::new_v4().as_bytes(), address_owner: "foo".to_string(), address: "0x1234".to_string(), + address_format: AddressFormat::ICPAccountIdentifier, labels: Vec::new(), blockchain: Blockchain::InternetComputer, metadata: Metadata::mock(), diff --git a/core/station/impl/src/models/asset.rs b/core/station/impl/src/models/asset.rs index 883ab4319..11071a846 100644 --- a/core/station/impl/src/models/asset.rs +++ b/core/station/impl/src/models/asset.rs @@ -1,28 +1,53 @@ -use super::{Blockchain, BlockchainStandard}; -use crate::models::Metadata; -use std::hash::{Hash, Hasher}; +use orbit_essentials::{ + model::{ModelKey, ModelValidator, ModelValidatorResult}, + storable, + types::UUID, +}; -#[derive(Clone, Debug, PartialEq, Eq)] +use super::{Blockchain, TokenStandard}; +use crate::{errors::AssetError, models::Metadata, repositories::ASSET_REPOSITORY}; +use std::{ + collections::BTreeSet, + hash::{Hash, Hasher}, +}; + +pub type AssetId = UUID; + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Asset { + pub id: AssetId, /// The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) pub blockchain: Blockchain, - // The asset standard that is supported (e.g. `erc20`, `native`, etc.), canonically + // The asset standard that is supported (e.g. `erc20`, `icp_native`, etc.), canonically // represented as a lowercase string with spaces replaced with underscores. - pub standard: BlockchainStandard, + pub standards: BTreeSet, /// The asset symbol (e.g. `ICP`, `BTC`, `ETH`, etc.) pub symbol: String, /// The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) pub name: String, - /// The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`), - /// also, in the case of non-native assets, it can contain other required - /// information (e.g. `{"address": "0x1234"}`). + /// The number of decimal places that the asset supports (e.g. `8` for `BTC`, `18` for `ETH`, etc.) + pub decimals: u32, + /// The asset metadata (e.g. `{"logo": "https://example.com/logo.png"}`). pub metadata: Metadata, } +impl Asset { + pub const DECIMALS_RANGE: (u32, u32) = (0, 18); + pub const SYMBOL_RANGE: (u16, u16) = (1, 32); + pub const NAME_RANGE: (u16, u16) = (1, 64); +} + +impl ModelKey for Asset { + fn key(&self) -> AssetId { + self.id + } +} + impl Hash for Asset { fn hash(&self, state: &mut H) { self.blockchain.hash(state); - self.standard.hash(state); + self.standards.hash(state); self.symbol.hash(state); self.name.hash(state); @@ -32,3 +57,191 @@ impl Hash for Asset { keys.hash(state); } } + +#[derive(Debug, Clone)] +pub struct AssetCallerPrivileges { + pub id: AssetId, + pub can_edit: bool, + pub can_delete: bool, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct AssetEntryKey { + /// The address book entry id, which is a UUID. + pub id: AssetId, +} + +fn validate_symbol(symbol: &str) -> ModelValidatorResult { + if (symbol.len() < Asset::SYMBOL_RANGE.0 as usize) + || (symbol.len() > Asset::SYMBOL_RANGE.1 as usize) + { + return Err(AssetError::InvalidSymbolLength { + min_length: Asset::SYMBOL_RANGE.0, + max_length: Asset::SYMBOL_RANGE.1, + }); + } + + if !symbol.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(AssetError::InvalidSymbol); + } + + Ok(()) +} + +fn validate_name(name: &str) -> ModelValidatorResult { + if (name.len() < Asset::NAME_RANGE.0 as usize) || (name.len() > Asset::NAME_RANGE.1 as usize) { + return Err(AssetError::InvalidNameLength { + min_length: Asset::NAME_RANGE.0, + max_length: Asset::NAME_RANGE.1, + }); + } + + Ok(()) +} + +fn validate_decimals(decimals: u32) -> ModelValidatorResult { + if (decimals < Asset::DECIMALS_RANGE.0) || (decimals > Asset::DECIMALS_RANGE.1) { + return Err(AssetError::InvalidDecimals { + min: Asset::DECIMALS_RANGE.0, + max: Asset::DECIMALS_RANGE.1, + }); + } + + Ok(()) +} + +fn validate_uniqueness( + asset_id: &AssetId, + symbol: &str, + blockchain: &Blockchain, +) -> ModelValidatorResult { + if let Some(existing_asset_id) = + ASSET_REPOSITORY.exists_unique(blockchain.to_string().as_str(), symbol) + { + if existing_asset_id != *asset_id { + return Err(AssetError::AlreadyExists { + symbol: symbol.to_string(), + blockchain: blockchain.to_string(), + }); + } + } + + Ok(()) +} + +impl ModelValidator for Asset { + fn validate(&self) -> ModelValidatorResult { + validate_symbol(&self.symbol)?; + validate_name(&self.name)?; + validate_decimals(self.decimals)?; + validate_uniqueness(&self.id, &self.symbol, &self.blockchain)?; + + self.metadata.validate()?; + + Ok(()) + } +} + +#[cfg(any(test, feature = "canbench"))] +pub mod asset_test_utils { + + use std::collections::{BTreeMap, BTreeSet}; + + use crate::models::{Blockchain, Metadata, TokenStandard}; + + use super::Asset; + + pub fn mock_asset() -> Asset { + Asset { + id: [0; 16], + blockchain: Blockchain::InternetComputer, + standards: BTreeSet::from([TokenStandard::InternetComputerNative]), + symbol: "ICP".to_string(), + name: "Internet Computer".to_string(), + metadata: Metadata::new(BTreeMap::from([ + ( + "ledger_canister_id".to_string(), + "ryjl3-tyaaa-aaaaa-aaaba-cai".to_string(), + ), + ( + "index_canister_id".to_string(), + "qhbym-qaaaa-aaaaa-aaafq-cai".to_string(), + ), + ])), + decimals: 8, + } + } + + pub fn mock_asset_b() -> Asset { + Asset { + id: [1; 16], + blockchain: Blockchain::InternetComputer, + standards: BTreeSet::from([TokenStandard::InternetComputerNative]), + symbol: "TEST".to_string(), + name: "Other Test Asset".to_string(), + decimals: 8, + metadata: Metadata::default(), + } + } +} + +#[cfg(test)] +mod test { + + use orbit_essentials::repository::Repository; + + use super::*; + + #[test] + fn test_name_validation() { + let mut asset = asset_test_utils::mock_asset(); + assert!(asset.validate().is_ok()); + + asset.name = "".to_string(); + assert!(asset.validate().is_err()); + + asset.name = "a".repeat(Asset::NAME_RANGE.1 as usize + 1); + assert!(asset.validate().is_err()); + } + + #[test] + fn test_symbol_validation() { + let mut asset = asset_test_utils::mock_asset(); + assert!(asset.validate().is_ok()); + + asset.symbol = "".to_string(); + assert!(asset.validate().is_err()); + + asset.symbol = "a".repeat(Asset::SYMBOL_RANGE.1 as usize + 1); + assert!(asset.validate().is_err()); + } + + #[test] + fn test_decimals_validation() { + let mut asset = asset_test_utils::mock_asset(); + assert!(asset.validate().is_ok()); + + asset.decimals = Asset::DECIMALS_RANGE.1 + 1; + assert!(asset.validate().is_err()); + } + + #[test] + fn test_validate_uniqueness() { + let mut asset = asset_test_utils::mock_asset(); + assert!(asset.validate().is_ok()); + + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + + // this passes uniqueness test because the asset id is the same + assert!(asset.validate().is_ok()); + + // this fails uniqueness test because the asset id is different + asset.id = [1; 16]; + + assert!(matches!( + asset.validate().expect_err("Asset should not be unique"), + AssetError::AlreadyExists { .. } + )); + } +} diff --git a/core/station/impl/src/models/blockchain.rs b/core/station/impl/src/models/blockchain.rs index 224e67866..205b74be3 100644 --- a/core/station/impl/src/models/blockchain.rs +++ b/core/station/impl/src/models/blockchain.rs @@ -1,4 +1,4 @@ -use super::BlockchainStandard; +use super::TokenStandard; use candid::CandidType; use orbit_essentials::storable; use std::fmt::{Display, Formatter}; @@ -23,13 +23,13 @@ impl Blockchain { } /// The list of standards that the blockchain supports. - pub fn supported_standards(&self) -> Vec { + pub fn supported_standards(&self) -> Vec { match self { Blockchain::InternetComputer => { - vec![BlockchainStandard::Native, BlockchainStandard::ICRC1] + vec![TokenStandard::InternetComputerNative, TokenStandard::ICRC1] } - Blockchain::Ethereum => vec![BlockchainStandard::Native, BlockchainStandard::ERC20], - Blockchain::Bitcoin => vec![BlockchainStandard::Native], + Blockchain::Ethereum => vec![], + Blockchain::Bitcoin => vec![], } } } @@ -85,18 +85,9 @@ mod tests { fn match_supported_standards() { assert!(Blockchain::InternetComputer .supported_standards() - .contains(&BlockchainStandard::Native)); + .contains(&TokenStandard::InternetComputerNative)); assert!(Blockchain::InternetComputer .supported_standards() - .contains(&BlockchainStandard::ICRC1)); - assert!(Blockchain::Ethereum - .supported_standards() - .contains(&BlockchainStandard::Native)); - assert!(Blockchain::Ethereum - .supported_standards() - .contains(&BlockchainStandard::ERC20)); - assert!(Blockchain::Bitcoin - .supported_standards() - .contains(&BlockchainStandard::Native)); + .contains(&TokenStandard::ICRC1)); } } diff --git a/core/station/impl/src/models/blockchain_standard.rs b/core/station/impl/src/models/blockchain_standard.rs index b5d801498..866df4165 100644 --- a/core/station/impl/src/models/blockchain_standard.rs +++ b/core/station/impl/src/models/blockchain_standard.rs @@ -1,37 +1,98 @@ -use candid::CandidType; use orbit_essentials::storable; use std::{ fmt::{Display, Formatter}, str::FromStr, }; +use super::AddressFormat; + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TokenStandardInfo { + pub name: String, + pub address_formats: Vec, +} + #[storable] -#[derive(CandidType, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub enum BlockchainStandard { - Native, +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum TokenStandard { + InternetComputerNative, ICRC1, - ERC20, + // ERC20, +} + +impl TokenStandard { + pub fn get_info(&self) -> TokenStandardInfo { + match self { + TokenStandard::InternetComputerNative => TokenStandardInfo { + name: "icp_native".to_owned(), + address_formats: vec![AddressFormat::ICPAccountIdentifier], + }, + TokenStandard::ICRC1 => TokenStandardInfo { + name: "icrc1".to_owned(), + address_formats: vec![AddressFormat::ICRC1Account], + }, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum StandardOperation { + Balance, + Transfer, + ListTransfers, +} +impl std::fmt::Display for StandardOperation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + StandardOperation::Balance => write!(f, "balance"), + StandardOperation::Transfer => write!(f, "transfer"), + StandardOperation::ListTransfers => write!(f, "list_transfers"), + } + } +} + +impl TokenStandard { + pub const METADATA_KEY_LEDGER_CANISTER_ID: &'static str = "ledger_canister_id"; + pub const METADATA_KEY_INDEX_CANISTER_ID: &'static str = "index_canister_id"; + + pub fn get_required_metadata(&self) -> Vec { + match self { + TokenStandard::ICRC1 | TokenStandard::InternetComputerNative => vec![ + Self::METADATA_KEY_LEDGER_CANISTER_ID.to_string(), + // index canister is optional + ], + } + } + + pub fn get_supported_operations(&self) -> Vec { + match self { + TokenStandard::InternetComputerNative | TokenStandard::ICRC1 => vec![ + StandardOperation::Balance, + StandardOperation::Transfer, + StandardOperation::ListTransfers, + ], + } + } } -impl FromStr for BlockchainStandard { +impl FromStr for TokenStandard { type Err = (); - fn from_str(variant: &str) -> Result { + fn from_str(variant: &str) -> Result { match variant { - "native" => Ok(BlockchainStandard::Native), - "icrc1" => Ok(BlockchainStandard::ICRC1), - "erc20" => Ok(BlockchainStandard::ERC20), + "icp_native" => Ok(TokenStandard::InternetComputerNative), + "icrc1" => Ok(TokenStandard::ICRC1), _ => Err(()), } } } -impl Display for BlockchainStandard { +impl Display for TokenStandard { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - BlockchainStandard::Native => write!(f, "native"), - BlockchainStandard::ERC20 => write!(f, "erc20"), - BlockchainStandard::ICRC1 => write!(f, "icrc1"), + TokenStandard::InternetComputerNative => write!(f, "icp_native"), + TokenStandard::ICRC1 => write!(f, "icrc1"), } } } @@ -42,20 +103,18 @@ mod tests { #[test] fn blockchain_standard_match_string_representation() { - assert_eq!(BlockchainStandard::Native.to_string(), "native"); assert_eq!( - BlockchainStandard::from_str("native").unwrap(), - BlockchainStandard::Native + TokenStandard::InternetComputerNative.to_string(), + "icp_native" ); - assert_eq!(BlockchainStandard::ICRC1.to_string(), "icrc1"); assert_eq!( - BlockchainStandard::from_str("icrc1").unwrap(), - BlockchainStandard::ICRC1 + TokenStandard::from_str("icp_native").unwrap(), + TokenStandard::InternetComputerNative ); - assert_eq!(BlockchainStandard::ERC20.to_string(), "erc20"); + assert_eq!(TokenStandard::ICRC1.to_string(), "icrc1"); assert_eq!( - BlockchainStandard::from_str("erc20").unwrap(), - BlockchainStandard::ERC20 + TokenStandard::from_str("icrc1").unwrap(), + TokenStandard::ICRC1 ); } } diff --git a/core/station/impl/src/models/indexes/transfer_account_index.rs b/core/station/impl/src/models/indexes/transfer_account_index.rs index 6c901dab3..08ce941dd 100644 --- a/core/station/impl/src/models/indexes/transfer_account_index.rs +++ b/core/station/impl/src/models/indexes/transfer_account_index.rs @@ -53,6 +53,8 @@ mod tests { request_id: [0; 16], fee: candid::Nat(BigUint::from(0u32)), from_account: [1; 16], + from_asset: [2; 16], + with_standard: crate::models::TokenStandard::InternetComputerNative, to_address: "0x1234".to_string(), status: TransferStatus::Created, initiator_user: [2; 16], diff --git a/core/station/impl/src/models/indexes/unique_index.rs b/core/station/impl/src/models/indexes/unique_index.rs index 384a97e21..3056208f6 100644 --- a/core/station/impl/src/models/indexes/unique_index.rs +++ b/core/station/impl/src/models/indexes/unique_index.rs @@ -1,6 +1,6 @@ use crate::{ core::utils::format_unique_string, - models::{Account, AddressBookEntry, ExternalCanister, User, UserGroup}, + models::{Account, AddressBookEntry, Asset, ExternalCanister, User, UserGroup}, }; use candid::Principal; use orbit_essentials::{storable, types::UUID}; @@ -18,6 +18,10 @@ pub enum UniqueIndexKey { UserGroupName(String), UserIdentity(Principal), UserName(String), + AssetSymbolBlockchain( + String, // Blockchain + String, // Symbol + ), } impl AddressBookEntry { @@ -80,6 +84,28 @@ impl UserGroup { } } +impl Asset { + /// Converts the asset to it's unique index by name. + fn to_unique_index(&self) -> (UniqueIndexKey, UUID) { + ( + Self::to_unique_index_by_symbol_blockchain(&self.symbol, self.blockchain.to_string()), + self.id, + ) + } + + pub fn to_unique_index_by_symbol_blockchain( + symbol: &str, + blockchain: String, + ) -> UniqueIndexKey { + UniqueIndexKey::AssetSymbolBlockchain(symbol.to_uppercase(), blockchain.to_string()) + } + + /// Extracts all unique indexes for the asset. + pub fn to_unique_indexes(&self) -> Vec<(UniqueIndexKey, UUID)> { + vec![self.to_unique_index()] + } +} + impl ExternalCanister { /// Converts the external canister to it's unique index by name. fn to_unique_index_by_name(&self) -> (UniqueIndexKey, UUID) { @@ -123,6 +149,7 @@ impl Account { #[cfg(test)] mod tests { + use super::*; use crate::models::{ account_test_utils::mock_account, address_book_entry_test_utils::mock_address_book_entry, diff --git a/core/station/impl/src/models/request.rs b/core/station/impl/src/models/request.rs index a9aa28593..057b61727 100644 --- a/core/station/impl/src/models/request.rs +++ b/core/station/impl/src/models/request.rs @@ -1,7 +1,7 @@ use super::request_policy_rule::{RequestEvaluationResult, RequestPolicyRuleInput}; use super::{ - ConfigureExternalCanisterOperationKind, DisplayUser, EvaluationStatus, RequestApproval, - RequestApprovalStatus, RequestOperation, RequestStatus, UserId, UserKey, + ChangeAssets, ConfigureExternalCanisterOperationKind, DisplayUser, EvaluationStatus, + RequestApproval, RequestApprovalStatus, RequestOperation, RequestStatus, UserId, UserKey, }; use crate::core::evaluation::{ Evaluate, REQUEST_APPROVE_RIGHTS_REQUEST_POLICY_RULE_EVALUATOR, REQUEST_POLICY_RULE_EVALUATOR, @@ -13,8 +13,8 @@ use crate::core::request::{ RequestApprovalRightsEvaluator, RequestEvaluator, RequestPossibleApproversFinder, }; use crate::core::validation::{ - EnsureAccount, EnsureAddressBookEntry, EnsureIdExists, EnsureRequestPolicy, EnsureUser, - EnsureUserGroup, + EnsureAccount, EnsureAddressBookEntry, EnsureAsset, EnsureIdExists, EnsureRequestPolicy, + EnsureUser, EnsureUserGroup, }; use crate::errors::{EvaluateError, RequestError, ValidationError}; use crate::models::resource::{ExecutionMethodResourceTarget, ValidationMethodResourceTarget}; @@ -198,6 +198,7 @@ fn validate_request_operation_foreign_keys( RequestOperation::ManageSystemInfo(_) => (), RequestOperation::Transfer(op) => { EnsureAccount::id_exists(&op.input.from_account_id)?; + EnsureAsset::id_exists(&op.input.from_asset_id)?; } RequestOperation::AddAccount(op) => { op.input.read_permission.validate()?; @@ -236,6 +237,19 @@ fn validate_request_operation_foreign_keys( { policy_rule.validate()?; } + + if let Some(ChangeAssets::ReplaceWith { assets }) = &op.input.change_assets { + EnsureAsset::id_list_exists(assets)?; + } + + if let Some(ChangeAssets::Change { + add_assets, + remove_assets, + }) = &op.input.change_assets + { + EnsureAsset::id_list_exists(add_assets)?; + EnsureAsset::id_list_exists(remove_assets)?; + } } RequestOperation::AddAddressBookEntry(_) => (), RequestOperation::EditAddressBookEntry(op) => { @@ -318,6 +332,13 @@ fn validate_request_operation_foreign_keys( EnsureUserGroup::id_exists(&committee.user_group_id)?; } } + RequestOperation::AddAsset(_) => (), + RequestOperation::EditAsset(op) => { + EnsureAsset::id_exists(&op.input.asset_id)?; + } + RequestOperation::RemoveAsset(op) => { + EnsureAsset::id_exists(&op.input.asset_id)?; + } } Ok(()) } @@ -484,12 +505,15 @@ impl Request { #[cfg(test)] mod tests { use crate::core::validation::disable_mock_resource_validation; + use crate::models::asset_test_utils::mock_asset; use crate::models::permission::Allow; use crate::models::{ - AddAccountOperationInput, AddUserOperation, AddUserOperationInput, Metadata, - TransferOperation, TransferOperationInput, + Account, AccountKey, AddAccountOperationInput, AddAssetOperationInput, AddUserOperation, + AddUserOperationInput, Blockchain, Metadata, TokenStandard, TransferOperation, + TransferOperationInput, }; - use crate::services::AccountService; + use crate::repositories::ACCOUNT_REPOSITORY; + use crate::services::{AccountService, AssetService}; use super::request_test_utils::mock_request; use super::*; @@ -658,13 +682,26 @@ mod tests { async fn test_request_operation_is_valid() { disable_mock_resource_validation(); + let asset = AssetService::default() + .create( + AddAssetOperationInput { + name: "a".to_owned(), + symbol: "a".to_owned(), + decimals: 0, + metadata: Metadata::default(), + blockchain: Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + }, + None, + ) + .expect("Failed to create asset"); + let account_service = AccountService::default(); let account = account_service .create_account( AddAccountOperationInput { name: "a".to_owned(), - blockchain: crate::models::Blockchain::InternetComputer, - standard: crate::models::BlockchainStandard::Native, + assets: vec![asset.id], metadata: Metadata::default(), read_permission: Allow::default(), configs_permission: Allow::default(), @@ -688,7 +725,10 @@ mod tests { metadata: Metadata::default(), to: "0x1234".to_string(), from_account_id: account.id, + from_asset_id: asset.id, + with_standard: TokenStandard::InternetComputerNative, }, + asset, }); let result = validate_request_operation_foreign_keys(&operation); @@ -710,7 +750,10 @@ mod tests { metadata: Metadata::default(), to: "0x1234".to_string(), from_account_id: [0; 16], + from_asset_id: [0; 16], + with_standard: TokenStandard::InternetComputerNative, }, + asset: mock_asset(), })) .expect_err("Invalid account id should fail"); @@ -779,8 +822,7 @@ mod tests { account_id: None, input: crate::models::AddAccountOperationInput { name: "a".to_owned(), - blockchain: crate::models::Blockchain::InternetComputer, - standard: crate::models::BlockchainStandard::Native, + assets: vec![], metadata: Metadata::default(), read_permission: Allow { auth_scope: crate::models::permission::AuthScope::Restricted, @@ -800,6 +842,7 @@ mod tests { crate::models::EditAccountOperation { input: crate::models::EditAccountOperationInput { account_id: [0; 16], + change_assets: None, read_permission: None, configs_permission: None, transfer_permission: None, @@ -811,6 +854,41 @@ mod tests { )) .expect_err("Invalid account id should fail"); + ACCOUNT_REPOSITORY.insert( + AccountKey { id: [0; 16] }, + Account { + id: [0; 16], + name: "a".to_owned(), + seed: [0; 16], + assets: vec![], + addresses: vec![], + metadata: Metadata::default(), + transfer_request_policy_id: None, + configs_request_policy_id: None, + last_modification_timestamp: 0, + }, + ); + + validate_request_operation_foreign_keys(&RequestOperation::EditAccount( + crate::models::EditAccountOperation { + input: crate::models::EditAccountOperationInput { + account_id: [0; 16], + change_assets: Some(ChangeAssets::ReplaceWith { + assets: vec![[0; 16]], + }), + read_permission: None, + configs_permission: None, + transfer_permission: None, + configs_request_policy: None, + transfer_request_policy: None, + name: None, + }, + }, + )) + .expect_err("Invalid asset id should fail"); + + ACCOUNT_REPOSITORY.clear(); + validate_request_operation_foreign_keys(&RequestOperation::EditAddressBookEntry( crate::models::EditAddressBookEntryOperation { input: crate::models::EditAddressBookEntryOperationInput { @@ -868,7 +946,8 @@ mod tests { pub mod request_test_utils { use super::*; use crate::models::{ - Metadata, RequestApprovalStatus, TransferOperation, TransferOperationInput, + asset_test_utils::mock_asset, Metadata, RequestApprovalStatus, TokenStandard, + TransferOperation, TransferOperationInput, }; use num_bigint::BigUint; use uuid::Uuid; @@ -892,7 +971,10 @@ pub mod request_test_utils { metadata: Metadata::default(), to: "0x1234".to_string(), from_account_id: [1; 16], + from_asset_id: [0; 16], + with_standard: TokenStandard::InternetComputerNative, }, + asset: mock_asset(), }), approvals: vec![RequestApproval { approver_id: [1; 16], diff --git a/core/station/impl/src/models/request_operation.rs b/core/station/impl/src/models/request_operation.rs index b4b3041cc..505e5d077 100644 --- a/core/station/impl/src/models/request_operation.rs +++ b/core/station/impl/src/models/request_operation.rs @@ -3,9 +3,9 @@ use super::{ request_policy_rule::{RequestPolicyRule, RequestPolicyRuleInput}, request_specifier::RequestSpecifier, resource::{Resource, ValidationMethodResourceTarget}, - AccountId, AddressBookEntryId, Blockchain, BlockchainStandard, ChangeMetadata, - CycleObtainStrategy, DisasterRecoveryCommittee, ExternalCanisterCallPermission, - ExternalCanisterState, MetadataItem, UserGroupId, UserId, UserStatus, + AccountAsset, AccountId, AddressBookEntryId, AddressFormat, Asset, AssetId, Blockchain, + ChangeMetadata, CycleObtainStrategy, DisasterRecoveryCommittee, ExternalCanisterCallPermission, + ExternalCanisterState, MetadataItem, TokenStandard, UserGroupId, UserId, UserStatus, }; use crate::core::validation::EnsureExternalCanister; use crate::errors::ValidationError; @@ -15,9 +15,9 @@ use orbit_essentials::cdk::api::management_canister::main::{self as mgmt}; use orbit_essentials::cmc::SubnetSelection; use orbit_essentials::model::{ModelValidator, ModelValidatorResult}; use orbit_essentials::{storable, types::UUID}; -use std::fmt::Display; +use std::{collections::HashSet, fmt::Display}; -#[storable(skip_deserialize = true)] +#[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, strum::VariantNames)] #[strum(serialize_all = "PascalCase")] pub enum RequestOperation { @@ -44,6 +44,9 @@ pub enum RequestOperation { RemoveRequestPolicy(RemoveRequestPolicyOperation), ManageSystemInfo(ManageSystemInfoOperation), SetDisasterRecovery(SetDisasterRecoveryOperation), + AddAsset(AddAssetOperation), + EditAsset(EditAssetOperation), + RemoveAsset(RemoveAssetOperation), } impl Display for RequestOperation { @@ -74,22 +77,75 @@ impl Display for RequestOperation { RequestOperation::RemoveRequestPolicy(_) => write!(f, "remove_request_policy"), RequestOperation::ManageSystemInfo(_) => write!(f, "manage_system_info"), RequestOperation::SetDisasterRecovery(_) => write!(f, "set_disaster_recovery"), + RequestOperation::AddAsset(_) => write!(f, "add_asset"), + RequestOperation::EditAsset(_) => write!(f, "edit_asset"), + RequestOperation::RemoveAsset(_) => write!(f, "remove_asset"), } } } #[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct AddAssetOperation { + pub asset_id: Option, + pub input: AddAssetOperationInput, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct AddAssetOperationInput { + pub name: String, + pub symbol: String, + pub decimals: u32, + pub metadata: Metadata, + pub blockchain: Blockchain, + pub standards: Vec, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct EditAssetOperation { + pub input: EditAssetOperationInput, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct EditAssetOperationInput { + pub asset_id: AssetId, + pub name: Option, + pub symbol: Option, + pub change_metadata: Option, + pub blockchain: Option, + pub standards: Option>, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct RemoveAssetOperation { + pub input: RemoveAssetOperationInput, +} + +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct RemoveAssetOperationInput { + pub asset_id: AssetId, +} + +#[storable(skip_deserialize = true)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TransferOperation { pub transfer_id: Option, pub input: TransferOperationInput, + pub asset: Asset, pub fee: Option, } -#[storable] +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TransferOperationInput { pub from_account_id: AccountId, + pub from_asset_id: AssetId, + pub with_standard: TokenStandard, pub to: String, pub amount: candid::Nat, pub metadata: Metadata, @@ -105,12 +161,11 @@ pub struct AddAccountOperation { pub input: AddAccountOperationInput, } -#[storable] +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct AddAccountOperationInput { pub name: String, - pub blockchain: Blockchain, - pub standard: BlockchainStandard, + pub assets: Vec, pub metadata: Metadata, pub read_permission: Allow, pub configs_permission: Allow, @@ -125,10 +180,55 @@ pub struct EditAccountOperation { pub input: EditAccountOperationInput, } +#[storable] +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ChangeAssets { + ReplaceWith { + assets: Vec, + }, + Change { + add_assets: Vec, + remove_assets: Vec, + }, +} + +impl ChangeAssets { + pub fn apply(&self, assets: &mut Vec) { + match self { + ChangeAssets::ReplaceWith { assets: new_assets } => { + *assets = new_assets + .iter() + .map(|asset_id| AccountAsset { + asset_id: *asset_id, + balance: None, + }) + .collect(); + } + ChangeAssets::Change { + add_assets, + remove_assets, + } => { + let existing_assets: HashSet<_> = assets.iter().map(|a| a.asset_id).collect(); + for asset_id in add_assets { + if !existing_assets.contains(asset_id) { + assets.push(AccountAsset { + asset_id: *asset_id, + balance: None, + }); + } + } + + assets.retain(|a| !remove_assets.contains(&a.asset_id)); + } + } + } +} + #[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct EditAccountOperationInput { pub account_id: AccountId, + pub change_assets: Option, pub name: Option, pub read_permission: Option, pub configs_permission: Option, @@ -145,11 +245,12 @@ pub struct AddAddressBookEntryOperation { pub input: AddAddressBookEntryOperationInput, } -#[storable] +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct AddAddressBookEntryOperationInput { pub address_owner: String, pub address: String, + pub address_format: AddressFormat, pub blockchain: Blockchain, #[serde(default)] pub labels: Vec, @@ -678,3 +779,42 @@ pub struct ManageSystemInfoOperationInput { pub struct ManageSystemInfoOperation { pub input: ManageSystemInfoOperationInput, } + +#[cfg(test)] +mod test { + use crate::models::AccountAsset; + + use super::ChangeAssets; + + #[test] + fn test_change_assets() { + let mut assets: Vec = [[3; 16], [9; 16], [10; 16], [11; 16], [13; 16]] + .into_iter() + .map(|id| AccountAsset { + asset_id: id, + balance: None, + }) + .collect(); + + ChangeAssets::Change { + // 3 already exists, should not be added twice + add_assets: vec![[0; 16], [1; 16], [2; 16], [3; 16]], + // 12 doesn't exist, should not be in an issue + remove_assets: vec![[10; 16], [11; 16], [12; 16]], + } + .apply(&mut assets); + + assert_eq!(assets.len(), 5 + 3 - 2); + + assert!(!assets.iter().any(|a| a.asset_id == [10; 16])); + assert!(!assets.iter().any(|a| a.asset_id == [11; 16])); + assert!(!assets.iter().any(|a| a.asset_id == [12; 16])); + + assert!(assets.iter().any(|a| a.asset_id == [0; 16])); + assert!(assets.iter().any(|a| a.asset_id == [1; 16])); + assert!(assets.iter().any(|a| a.asset_id == [2; 16])); + assert!(assets.iter().any(|a| a.asset_id == [3; 16])); + + assert_eq!(assets.iter().filter(|a| a.asset_id == [3; 16]).count(), 1); + } +} diff --git a/core/station/impl/src/models/request_operation_filter_type.rs b/core/station/impl/src/models/request_operation_filter_type.rs index e7221cb66..746120ba1 100644 --- a/core/station/impl/src/models/request_operation_filter_type.rs +++ b/core/station/impl/src/models/request_operation_filter_type.rs @@ -28,6 +28,9 @@ pub enum RequestOperationFilterType { ManageSystemInfo, ConfigureExternalCanister(Principal), FundExternalCanister(Principal), + AddAsset, + EditAsset, + RemoveAsset, } impl From for RequestOperationFilterType { @@ -80,6 +83,9 @@ impl From for RequestOperationFilterType { RequestOperation::FundExternalCanister(operation) => { RequestOperationFilterType::FundExternalCanister(operation.canister_id) } + RequestOperation::AddAsset(_) => RequestOperationFilterType::AddAsset, + RequestOperation::EditAsset(_) => RequestOperationFilterType::EditAsset, + RequestOperation::RemoveAsset(_) => RequestOperationFilterType::RemoveAsset, } } } diff --git a/core/station/impl/src/models/request_operation_type.rs b/core/station/impl/src/models/request_operation_type.rs index bf027f6a3..90f6fd86f 100644 --- a/core/station/impl/src/models/request_operation_type.rs +++ b/core/station/impl/src/models/request_operation_type.rs @@ -33,6 +33,9 @@ pub enum RequestOperationType { SetDisasterRecovery = 23, ConfigureExternalCanister = 24, FundExternalCanister = 25, + AddAsset = 26, + EditAsset = 27, + RemoveAsset = 28, } /// A helper enum to filter the requests based on the operation type and @@ -62,6 +65,9 @@ pub enum ListRequestsOperationType { EditAddressBookEntry, RemoveAddressBookEntry, ManageSystemInfo, + AddAsset, + EditAsset, + RemoveAsset, } impl PartialEq for RequestOperationFilterType { @@ -164,6 +170,15 @@ impl PartialEq for RequestOperationFilterType { ListRequestsOperationType::ManageSystemInfo => { matches!(self, RequestOperationFilterType::ManageSystemInfo) } + ListRequestsOperationType::AddAsset => { + matches!(self, RequestOperationFilterType::AddAsset) + } + ListRequestsOperationType::EditAsset => { + matches!(self, RequestOperationFilterType::EditAsset) + } + ListRequestsOperationType::RemoveAsset => { + matches!(self, RequestOperationFilterType::RemoveAsset) + } } } } @@ -231,6 +246,9 @@ impl Display for RequestOperationType { write!(f, "configure_external_canister") } RequestOperationType::FundExternalCanister => write!(f, "fund_external_canister"), + RequestOperationType::AddAsset => write!(f, "add_asset"), + RequestOperationType::EditAsset => write!(f, "edit_asset"), + RequestOperationType::RemoveAsset => write!(f, "remove_asset"), } } } diff --git a/core/station/impl/src/models/request_policy_rule.rs b/core/station/impl/src/models/request_policy_rule.rs index bf805c464..167e068df 100644 --- a/core/station/impl/src/models/request_policy_rule.rs +++ b/core/station/impl/src/models/request_policy_rule.rs @@ -8,14 +8,18 @@ use super::{ use crate::{ core::{ic_cdk::api::print, utils::calculate_minimum_threshold}, errors::{MatchError, ValidationError}, - repositories::{UserWhereClause, ADDRESS_BOOK_REPOSITORY, USER_REPOSITORY}, + repositories::{UserWhereClause, ADDRESS_BOOK_REPOSITORY, ASSET_REPOSITORY, USER_REPOSITORY}, services::ACCOUNT_SERVICE, }; -use orbit_essentials::model::{ModelKey, ModelValidator, ModelValidatorResult}; use orbit_essentials::storable; +use orbit_essentials::{ + model::{ModelKey, ModelValidator, ModelValidatorResult}, + repository::Repository, +}; use station_api::EvaluationSummaryReasonDTO; use std::{cmp, hash::Hash}; use std::{collections::HashSet, sync::Arc}; +use uuid::Uuid; #[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -413,14 +417,27 @@ impl }); } Ok(account) => { - let is_in_address_book = ADDRESS_BOOK_REPOSITORY - .exists(account.blockchain, transfer.input.to.clone()); - - if is_in_address_book { - return Ok(RequestPolicyRuleResult { - status: EvaluationStatus::Approved, - evaluated_rule: EvaluatedRequestPolicyRule::AllowListed, - }); + for account_asset in account.assets { + let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) + else { + print(format!( + "Asset `{}` not found in account `{}`.", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(account.id).hyphenated() + )); + + continue; + }; + + let is_in_address_book = ADDRESS_BOOK_REPOSITORY + .exists(asset.blockchain, transfer.input.to.clone()); + + if is_in_address_book { + return Ok(RequestPolicyRuleResult { + status: EvaluationStatus::Approved, + evaluated_rule: EvaluatedRequestPolicyRule::AllowListed, + }); + } } } } diff --git a/core/station/impl/src/models/request_specifier.rs b/core/station/impl/src/models/request_specifier.rs index 646520bca..07b316a40 100644 --- a/core/station/impl/src/models/request_specifier.rs +++ b/core/station/impl/src/models/request_specifier.rs @@ -1,19 +1,21 @@ use super::resource::{Resource, ResourceIds}; use super::{MetadataItem, Request, RequestId, RequestOperation, RequestOperationType}; use crate::core::validation::{ - EnsureAccount, EnsureAddressBookEntry, EnsureIdExists, EnsureRequestPolicy, + EnsureAccount, EnsureAddressBookEntry, EnsureAsset, EnsureIdExists, EnsureRequestPolicy, EnsureResourceIdExists, EnsureUser, EnsureUserGroup, }; use crate::errors::ValidationError; use crate::models::resource::{CallExternalCanisterResourceTarget, ExternalCanisterId}; use crate::models::user::User; -use crate::repositories::ADDRESS_BOOK_REPOSITORY; +use crate::repositories::{ADDRESS_BOOK_REPOSITORY, ASSET_REPOSITORY}; use crate::services::ACCOUNT_SERVICE; use crate::{errors::MatchError, repositories::USER_REPOSITORY}; +use orbit_essentials::cdk::api::print; use orbit_essentials::model::{ModelValidator, ModelValidatorResult}; use orbit_essentials::repository::Repository; use orbit_essentials::storable; use orbit_essentials::types::UUID; +use uuid::Uuid; #[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -50,7 +52,7 @@ pub enum ResourceSpecifier { Resource(Resource), } -#[storable(skip_deserialize = true)] +#[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, strum::VariantNames)] #[strum(serialize_all = "PascalCase")] pub enum RequestSpecifier { @@ -76,6 +78,9 @@ pub enum RequestSpecifier { RemoveUserGroup(ResourceIds), ManageSystemInfo, SystemUpgrade, + AddAsset, + EditAsset(ResourceIds), + RemoveAsset(ResourceIds), } impl ModelValidator for RequestSpecifier { @@ -91,7 +96,8 @@ impl ModelValidator for RequestSpecifier { | RequestSpecifier::AddRequestPolicy | RequestSpecifier::ManageSystemInfo | RequestSpecifier::SetDisasterRecovery - | RequestSpecifier::AddUserGroup => (), + | RequestSpecifier::AddUserGroup + | RequestSpecifier::AddAsset => (), RequestSpecifier::CallExternalCanister(target) => { target.validate()?; @@ -121,6 +127,11 @@ impl ModelValidator for RequestSpecifier { | RequestSpecifier::RemoveUserGroup(resource_ids) => { EnsureUserGroup::resource_ids_exist(resource_ids)? } + + RequestSpecifier::EditAsset(resource_ids) + | RequestSpecifier::RemoveAsset(resource_ids) => { + EnsureAsset::resource_ids_exist(resource_ids)? + } } Ok(()) } @@ -157,6 +168,10 @@ impl From<&RequestSpecifier> for RequestOperationType { RequestSpecifier::RemoveUserGroup(_) => RequestOperationType::RemoveUserGroup, RequestSpecifier::ManageSystemInfo => RequestOperationType::ManageSystemInfo, RequestSpecifier::SetDisasterRecovery => RequestOperationType::SetDisasterRecovery, + + RequestSpecifier::AddAsset => RequestOperationType::AddAsset, + RequestSpecifier::EditAsset(_) => RequestOperationType::EditAsset, + RequestSpecifier::RemoveAsset(_) => RequestOperationType::RemoveAsset, } } } @@ -234,13 +249,30 @@ impl Match for AddressBookMetadataMatcher { Ok(match request.operation.to_owned() { RequestOperation::Transfer(transfer) => { if let Ok(account) = ACCOUNT_SERVICE.get_account(&transfer.input.from_account_id) { - if let Some(address_book_entry) = ADDRESS_BOOK_REPOSITORY - .find_by_address(account.blockchain, transfer.input.to) - { - address_book_entry.metadata.contains(&metadata) - } else { - false + let mut found = false; + + for account_asset in account.assets { + let Some(asset) = ASSET_REPOSITORY.get(&account_asset.asset_id) else { + print(format!( + "Could not load asset `{}` in account `{}`", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(account.id).hyphenated(), + )); + + continue; + }; + + if let Some(address_book_entry) = ADDRESS_BOOK_REPOSITORY + .find_by_address(asset.blockchain, transfer.input.to.clone()) + { + if address_book_entry.metadata.contains(&metadata) { + found = true; + break; + } + } } + + found } else { false } @@ -255,6 +287,7 @@ mod tests { use crate::{ core::{validation::disable_mock_resource_validation, write_system_info}, models::{ + asset_test_utils::mock_asset, request_specifier::{ Match, RequestSpecifier, UserInvolvedInPolicyRuleForRequestResource, UserMatcher, UserSpecifier, @@ -267,11 +300,11 @@ mod tests { system::SystemInfo, CanisterMethod, RequestKey, }, - repositories::REQUEST_REPOSITORY, + repositories::{ASSET_REPOSITORY, REQUEST_REPOSITORY}, }; use candid::Principal; - use orbit_essentials::cdk::mocks::api::id; use orbit_essentials::cdk::mocks::TEST_CANISTER_ID; + use orbit_essentials::{cdk::mocks::api::id, model::ModelKey}; use orbit_essentials::{model::ModelValidator, repository::Repository}; #[tokio::test] @@ -345,6 +378,9 @@ mod tests { let system_info = SystemInfo::new(upgrader_canister_id, Vec::new()); write_system_info(system_info); + let icp_asset = mock_asset(); + ASSET_REPOSITORY.insert(icp_asset.key(), icp_asset); + RequestSpecifier::AddAccount .validate() .expect("AddAccount should be valid"); diff --git a/core/station/impl/src/models/resource.rs b/core/station/impl/src/models/resource.rs index 9ffd9dcb7..a93fa52d9 100644 --- a/core/station/impl/src/models/resource.rs +++ b/core/station/impl/src/models/resource.rs @@ -7,6 +7,7 @@ use orbit_essentials::{ use std::fmt::{Display, Formatter}; use uuid::Uuid; +use crate::core::validation::EnsureAsset; use crate::{ core::validation::{ EnsureAccount, EnsureAddressBookEntry, EnsureNotification, EnsureRequest, @@ -19,7 +20,7 @@ use crate::{ /// The deserile implementation is available in the migration module for the `Resource` enum, this is /// because the enum had a backward incompatible change in the past and the migration module is handling /// the deserialization of the old data. -#[storable(skip_deserialize = true)] +#[storable] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, strum::VariantNames)] #[strum(serialize_all = "PascalCase")] pub enum Resource { @@ -33,6 +34,7 @@ pub enum Resource { System(SystemResourceAction), User(UserResourceAction), UserGroup(ResourceAction), + Asset(ResourceAction), } impl ModelValidator for Resource { @@ -106,6 +108,14 @@ impl ModelValidator for Resource { EnsureUserGroup::resource_id_exists(resource_id)? } }, + Resource::Asset(action) => match action { + ResourceAction::List | ResourceAction::Create => (), + ResourceAction::Read(resource_id) + | ResourceAction::Update(resource_id) + | ResourceAction::Delete(resource_id) => { + EnsureAsset::resource_id_exists(resource_id)? + } + }, } Ok(()) } @@ -614,6 +624,51 @@ impl Resource { vec![Resource::UserGroup(ResourceAction::Delete(ResourceId::Any))] } }, + + Resource::Asset(action) => match action { + ResourceAction::Create => vec![Resource::Asset(ResourceAction::Create)], + ResourceAction::List => vec![Resource::Asset(ResourceAction::List)], + + // Any resource id + ResourceAction::Update(ResourceId::Any) => { + vec![Resource::Asset(ResourceAction::Update(ResourceId::Any))] + } + ResourceAction::Read(ResourceId::Any) => { + vec![Resource::Asset(ResourceAction::Read(ResourceId::Any))] + } + ResourceAction::Delete(ResourceId::Any) => { + vec![Resource::Asset(ResourceAction::Delete(ResourceId::Any))] + } + + // Specific resource id + ResourceAction::Delete(ResourceId::Id(id)) => { + let mut associated_resources = + Resource::Asset(ResourceAction::Delete(ResourceId::Any)).to_expanded_list(); + + associated_resources + .push(Resource::Asset(ResourceAction::Delete(ResourceId::Id(*id)))); + + associated_resources + } + ResourceAction::Read(ResourceId::Id(id)) => { + let mut associated_resources = + Resource::Asset(ResourceAction::Read(ResourceId::Any)).to_expanded_list(); + + associated_resources + .push(Resource::Asset(ResourceAction::Read(ResourceId::Id(*id)))); + + associated_resources + } + ResourceAction::Update(ResourceId::Id(id)) => { + let mut associated_resources = + Resource::Asset(ResourceAction::Update(ResourceId::Any)).to_expanded_list(); + + associated_resources + .push(Resource::Asset(ResourceAction::Update(ResourceId::Id(*id)))); + + associated_resources + } + }, } } } @@ -633,6 +688,7 @@ impl Display for Resource { Resource::System(action) => write!(f, "System({})", action), Resource::User(action) => write!(f, "User({})", action), Resource::UserGroup(action) => write!(f, "UserGroup({})", action), + Resource::Asset(action) => write!(f, "Asset({})", action), } } } diff --git a/core/station/impl/src/models/transfer.rs b/core/station/impl/src/models/transfer.rs index 746ed3b6f..b326dbf41 100644 --- a/core/station/impl/src/models/transfer.rs +++ b/core/station/impl/src/models/transfer.rs @@ -1,4 +1,4 @@ -use super::{AccountId, UserId}; +use super::{AccountId, AssetId, TokenStandard, UserId}; use crate::core::ic_cdk::next_time; use crate::core::validation::{EnsureAccount, EnsureIdExists, EnsureRequest, EnsureUser}; use crate::errors::{RecordValidationError, TransferError}; @@ -49,7 +49,7 @@ impl Display for TransferStatus { } /// Represents a transfer in the system. -#[storable] +#[storable(skip_deserialize = true)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Transfer { /// The transfer id, which is a UUID. @@ -58,6 +58,10 @@ pub struct Transfer { pub initiator_user: UserId, /// The account id that the transfer is from. pub from_account: AccountId, + /// The asset id that the transfer is from. + pub from_asset: AssetId, + /// The token standard that the transfer is associated with. + pub with_standard: TokenStandard, /// The destination address of the transfer. pub to_address: String, /// The current status of the transfer. @@ -114,6 +118,8 @@ impl Transfer { transfer_id: UUID, initiator_user: UUID, from_account: UUID, + from_asset: UUID, + with_standard: TokenStandard, to_address: String, metadata: Metadata, amount: candid::Nat, @@ -126,6 +132,8 @@ impl Transfer { id: transfer_id, initiator_user, from_account, + from_asset, + with_standard, to_address, request_id, status: TransferStatus::Created, @@ -318,6 +326,8 @@ pub mod transfer_test_utils { id: *Uuid::new_v4().as_bytes(), initiator_user: [0; 16], from_account: [0; 16], + from_asset: [0; 16], + with_standard: TokenStandard::InternetComputerNative, request_id: [2; 16], to_address: "x".repeat(255), status: TransferStatus::Created, diff --git a/core/station/impl/src/repositories/account.rs b/core/station/impl/src/repositories/account.rs index 5b1733c97..9fa81c3fd 100644 --- a/core/station/impl/src/repositories/account.rs +++ b/core/station/impl/src/repositories/account.rs @@ -1,11 +1,14 @@ -use super::indexes::unique_index::UniqueIndexRepository; +use super::{indexes::unique_index::UniqueIndexRepository, InsertEntryObserverArgs}; use crate::{ core::{ metrics::ACCOUNT_METRICS, observer::Observer, utils::format_unique_string, with_memory_manager, Memory, ACCOUNT_MEMORY_ID, }, models::{indexes::unique_index::UniqueIndexKey, Account, AccountId, AccountKey}, - services::disaster_recovery_observes_insert_account, + services::{ + disaster_recovery_sync_accounts_and_assets_on_insert, + disaster_recovery_sync_accounts_and_assets_on_remove, + }, }; use ic_stable_structures::{memory_manager::VirtualMemory, StableBTreeMap}; use lazy_static::lazy_static; @@ -30,16 +33,21 @@ lazy_static! { #[derive(Debug)] pub struct AccountRepository { unique_index: UniqueIndexRepository, - change_observer: Observer<(Account, Option)>, + insert_observer: Observer>, + remove_observer: Observer<()>, } impl Default for AccountRepository { fn default() -> Self { - let mut change_observer = Observer::default(); - disaster_recovery_observes_insert_account(&mut change_observer); + let mut remove_observer = Observer::default(); + disaster_recovery_sync_accounts_and_assets_on_remove(&mut remove_observer); + + let mut insert_observer = Observer::default(); + disaster_recovery_sync_accounts_and_assets_on_insert(&mut insert_observer); Self { - change_observer, + insert_observer, + remove_observer, unique_index: UniqueIndexRepository::default(), } } @@ -94,10 +102,14 @@ impl Repository> for AccountRepositor self.save_entry_indexes(&value, prev.as_ref()); - let args = (value, prev); - self.change_observer.notify(&args); + let args = InsertEntryObserverArgs { + current: value, + prev, + }; - args.1 + self.insert_observer.notify(&args); + + args.prev }) } @@ -118,6 +130,8 @@ impl Repository> for AccountRepositor self.remove_entry_indexes(prev); } + self.remove_observer.notify(&()); + prev }) } @@ -152,13 +166,6 @@ impl AccountRepository { self.unique_index .get(&UniqueIndexKey::AccountName(format_unique_string(name))) } - - pub fn with_empty_observers() -> Self { - Self { - change_observer: Observer::default(), - ..Default::default() - } - } } #[derive(Debug, Clone)] diff --git a/core/station/impl/src/repositories/address_book.rs b/core/station/impl/src/repositories/address_book.rs index 69499bb1b..ee0a057f6 100644 --- a/core/station/impl/src/repositories/address_book.rs +++ b/core/station/impl/src/repositories/address_book.rs @@ -6,7 +6,7 @@ use crate::{ }, models::{ indexes::unique_index::UniqueIndexKey, AddressBookEntry, AddressBookEntryId, - AddressBookEntryKey, Blockchain, + AddressBookEntryKey, AddressFormat, Blockchain, }, }; use ic_stable_structures::{memory_manager::VirtualMemory, StableBTreeMap}; @@ -207,6 +207,10 @@ impl AddressBookRepository { entries.retain(|entry| addresses.contains(&entry.address)); } + if let Some(address_formats) = where_clause.address_formats { + entries.retain(|entry| address_formats.contains(&entry.address_format)); + } + entries.sort(); entries @@ -219,6 +223,7 @@ pub struct AddressBookWhereClause { pub labels: Option>, pub addresses: Option>, pub ids: Option>, + pub address_formats: Option>, } #[cfg(test)] @@ -280,4 +285,39 @@ mod tests { assert!(result.contains(&address_book_entry_0)); assert!(result.contains(&address_book_entry_1)); } + + #[test] + fn test_find_by_address_formats() { + let repository = AddressBookRepository::default(); + let mut address_book_entry_0 = address_book_entry_test_utils::mock_address_book_entry(); + let mut address_book_entry_1 = address_book_entry_test_utils::mock_address_book_entry(); + address_book_entry_0.id = [1; 16]; + address_book_entry_1.id = [2; 16]; + + address_book_entry_0.address_format = AddressFormat::ICPAccountIdentifier; + address_book_entry_1.address_format = AddressFormat::ICRC1Account; + + repository.insert(address_book_entry_0.to_key(), address_book_entry_0.clone()); + repository.insert(address_book_entry_1.to_key(), address_book_entry_1.clone()); + + let result = repository.find_where(AddressBookWhereClause { + blockchain: None, + labels: None, + addresses: None, + ids: None, + address_formats: Some(vec![AddressFormat::ICPAccountIdentifier]), + }); + assert!(result.contains(&address_book_entry_0)); + assert_eq!(result.len(), 1); + + let result = repository.find_where(AddressBookWhereClause { + blockchain: None, + labels: None, + addresses: None, + ids: None, + address_formats: Some(vec![AddressFormat::ICRC1Account]), + }); + assert!(result.contains(&address_book_entry_1)); + assert_eq!(result.len(), 1); + } } diff --git a/core/station/impl/src/repositories/asset.rs b/core/station/impl/src/repositories/asset.rs new file mode 100644 index 000000000..e77c689e8 --- /dev/null +++ b/core/station/impl/src/repositories/asset.rs @@ -0,0 +1,255 @@ +use super::{indexes::unique_index::UniqueIndexRepository, InsertEntryObserverArgs}; +use crate::{ + core::{ + cache::Cache, ic_cdk::api::print, metrics::ASSET_METRICS, observer::Observer, + with_memory_manager, Memory, ASSET_MEMORY_ID, + }, + models::{indexes::unique_index::UniqueIndexKey, Asset, AssetId}, + services::{ + disaster_recovery_sync_accounts_and_assets_on_insert, + disaster_recovery_sync_accounts_and_assets_on_remove, + }, +}; +use ic_stable_structures::{memory_manager::VirtualMemory, StableBTreeMap}; +use lazy_static::lazy_static; +use orbit_essentials::{ + repository::{IndexedRepository, Repository, StableDb}, + types::UUID, +}; +use std::{cell::RefCell, sync::Arc}; + +thread_local! { + static DB: RefCell>> = with_memory_manager(|memory_manager| { + RefCell::new( + StableBTreeMap::init(memory_manager.get(ASSET_MEMORY_ID)) + ) + }); + + static CACHE: RefCell> = RefCell::new(Cache::new(AssetRepository::MAX_CACHE_SIZE)); +} + +lazy_static! { + pub static ref ASSET_REPOSITORY: Arc = Arc::new(AssetRepository::default()); +} + +/// A repository that enables managing assets in stable memory. +#[derive(Debug)] +pub struct AssetRepository { + unique_index: UniqueIndexRepository, + insert_observer: Observer>, + remove_observer: Observer<()>, +} + +impl Default for AssetRepository { + fn default() -> Self { + let mut remove_observer = Observer::default(); + disaster_recovery_sync_accounts_and_assets_on_remove(&mut remove_observer); + + let mut insert_observer = Observer::default(); + disaster_recovery_sync_accounts_and_assets_on_insert(&mut insert_observer); + + Self { + insert_observer, + remove_observer, + unique_index: UniqueIndexRepository::default(), + } + } +} + +impl StableDb> for AssetRepository { + fn with_db(f: F) -> R + where + F: FnOnce(&mut StableBTreeMap>) -> R, + { + DB.with(|m| f(&mut m.borrow_mut())) + } +} + +impl IndexedRepository> for AssetRepository { + fn remove_entry_indexes(&self, entry: &Asset) { + entry + .to_unique_indexes() + .into_iter() + .for_each(|(index, _)| { + self.unique_index.remove(&index); + }); + } + + fn add_entry_indexes(&self, entry: &Asset) { + entry + .to_unique_indexes() + .into_iter() + .for_each(|(index, id)| { + self.unique_index.insert(index, id); + }); + } + + /// Clears all the indexes for the asset. + fn clear_indexes(&self) { + CACHE.with(|cache| cache.borrow_mut().clear()); + + self.unique_index + .clear_when(|key| matches!(key, UniqueIndexKey::AssetSymbolBlockchain(_, _))); + } +} + +impl Repository> for AssetRepository { + fn list(&self) -> Vec { + let mut assets = Vec::with_capacity(self.len()); + + if self.use_only_cache() { + CACHE.with(|cache| { + cache.borrow().iter().for_each(|(_, asset)| { + assets.push(asset.clone()); + }); + }); + } else { + Self::with_db(|db| { + db.iter().for_each(|(_, asset)| { + assets.push(asset); + }); + }); + } + + assets + } + + fn get(&self, key: &AssetId) -> Option { + let maybe_cache_hit = CACHE.with(|cache| cache.borrow().get(key).cloned()); + + match self.use_only_cache() { + true => maybe_cache_hit, + false => maybe_cache_hit.or_else(|| Self::with_db(|db| db.get(key))), + } + } + + fn insert(&self, key: AssetId, value: Asset) -> Option { + DB.with(|m| { + CACHE.with(|cache| cache.borrow_mut().insert(key, value.clone())); + + let prev = m.borrow_mut().insert(key, value.clone()); + + // Update metrics when an asset is upserted. + ASSET_METRICS.with(|metrics| { + metrics + .iter() + .for_each(|metric| metric.borrow_mut().sum(&value, prev.as_ref())) + }); + + self.save_entry_indexes(&value, prev.as_ref()); + + let args = InsertEntryObserverArgs { + current: value, + prev, + }; + + self.insert_observer.notify(&args); + + args.prev + }) + } + + fn remove(&self, key: &AssetId) -> Option { + DB.with(|m| { + CACHE.with(|cache| cache.borrow_mut().remove(key)); + + let prev = m.borrow_mut().remove(key); + + // Update metrics when a asset is removed. + if let Some(prev) = &prev { + ASSET_METRICS.with(|metrics| { + metrics + .iter() + .for_each(|metric| metric.borrow_mut().sub(prev)) + }); + + self.remove_entry_indexes(prev); + } + + self.remove_observer.notify(&()); + + prev + }) + } +} + +impl AssetRepository { + /// Currently the cache uses around 100 bytes per entry (UUID, Asset), + /// so the max cache storage size is around 10MiB. + pub const MAX_CACHE_SIZE: usize = 100_000; + + /// Checks if every asset in the repository is in the cache. + fn use_only_cache(&self) -> bool { + self.len() <= Self::MAX_CACHE_SIZE + } + + /// Builds the cache from the stable memory repository. + /// + /// This method should only be called during init or upgrade hooks to ensure that the cache is + /// up-to-date with the repository and that we have enough instructions to rebuild the cache. + pub fn build_cache(&self) { + if self.len() > Self::MAX_CACHE_SIZE { + print(format!( + "Only the first {} assets will be added to the cache, the reposity has {} assets.", + Self::MAX_CACHE_SIZE, + self.len(), + )); + } + + CACHE.with(|cache| { + cache.borrow_mut().clear(); + + DB.with(|db| { + for (_, asset) in db.borrow().iter().take(Self::MAX_CACHE_SIZE) { + cache.borrow_mut().insert(asset.id, asset); + } + }); + }); + } + + pub fn exists_unique(&self, blockchain: &str, symbol: &str) -> Option { + let key = Asset::to_unique_index_by_symbol_blockchain(symbol, blockchain.to_owned()); + + self.unique_index.get(&key) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::asset_test_utils; + + #[test] + fn test_crud() { + let repository = AssetRepository::default(); + let asset = asset_test_utils::mock_asset(); + + assert!(repository.get(&asset.id).is_none()); + + repository.insert(asset.id.to_owned(), asset.clone()); + + assert!(repository.get(&asset.id).is_some()); + assert!(repository.remove(&asset.id).is_some()); + assert!(repository.get(&asset.id).is_none()); + } + + #[test] + fn test_unqiueness() { + let repository = AssetRepository::default(); + let asset = asset_test_utils::mock_asset(); + + assert!(repository + .exists_unique(&asset.blockchain.to_string(), &asset.symbol) + .is_none()); + + repository.insert(asset.id.to_owned(), asset.clone()); + + assert!(repository.exists_unique("icp", "icp").is_some()); + + assert!(repository.exists_unique("icp", "ICP").is_some()); + + assert!(repository.exists_unique("icp", "ICP2").is_none()); + + assert!(repository.exists_unique("eth", "ICP").is_none()); + } +} diff --git a/core/station/impl/src/repositories/mod.rs b/core/station/impl/src/repositories/mod.rs index af9c21929..17e5d68ad 100644 --- a/core/station/impl/src/repositories/mod.rs +++ b/core/station/impl/src/repositories/mod.rs @@ -30,6 +30,14 @@ pub use request_policy::*; pub mod request_evaluation_result; pub use request_evaluation_result::*; +pub mod asset; +pub use asset::*; + pub mod permission; pub mod indexes; + +pub struct InsertEntryObserverArgs { + pub current: T, + pub prev: Option, +} diff --git a/core/station/impl/src/repositories/user_group.rs b/core/station/impl/src/repositories/user_group.rs index 256a00b7d..87d9cc6fb 100644 --- a/core/station/impl/src/repositories/user_group.rs +++ b/core/station/impl/src/repositories/user_group.rs @@ -29,7 +29,7 @@ lazy_static! { Arc::new(UserGroupRepository::default()); } -/// A repository that enables managing users in stable memory. +/// A repository that enables managing user groups in stable memory. #[derive(Default, Debug)] pub struct UserGroupRepository { unique_index: UniqueIndexRepository, diff --git a/core/station/impl/src/services/account.rs b/core/station/impl/src/services/account.rs index 44c56b707..c84c86822 100644 --- a/core/station/impl/src/services/account.rs +++ b/core/station/impl/src/services/account.rs @@ -2,7 +2,7 @@ use crate::{ core::{ authorization::Authorization, generate_uuid_v4, - ic_cdk::next_time, + ic_cdk::{api::time, next_time}, read_system_info, utils::{paginated_items, retain_accessible_resources, PaginatedData, PaginatedItemsArgs}, write_system_info, CallContext, ACCOUNT_BALANCE_FRESHNESS_IN_MS, @@ -14,22 +14,37 @@ use crate::{ request_policy_rule::RequestPolicyRuleInput, request_specifier::RequestSpecifier, resource::{AccountResourceAction, Resource, ResourceId, ResourceIds}, - Account, AccountBalance, AccountCallerPrivileges, AccountId, AddAccountOperationInput, - AddRequestPolicyOperationInput, Blockchain, BlockchainStandard, CycleObtainStrategy, - EditAccountOperationInput, EditPermissionOperationInput, + Account, AccountAddress, AccountBalance, AccountCallerPrivileges, AccountId, AccountKey, + AddAccountOperationInput, AddRequestPolicyOperationInput, AddressFormat, AssetId, + BalanceQueryState, Blockchain, CycleObtainStrategy, EditAccountOperationInput, + EditPermissionOperationInput, MetadataItem, TokenStandard, + }, + repositories::{ + AccountRepository, AccountWhereClause, AssetRepository, ACCOUNT_REPOSITORY, + ASSET_REPOSITORY, }, - repositories::{AccountRepository, AccountWhereClause, ACCOUNT_REPOSITORY}, services::{ permission::{PermissionService, PERMISSION_SERVICE}, RequestPolicyService, REQUEST_POLICY_SERVICE, }, }; +use ic_ledger_types::MAINNET_LEDGER_CANISTER_ID; use lazy_static::lazy_static; use orbit_essentials::{ - api::ServiceResult, model::ModelValidator, repository::Repository, types::UUID, + api::ServiceResult, + model::ModelValidator, + repository::Repository, + types::UUID, + utils::{CallerGuard, State}, }; use station_api::{AccountBalanceDTO, FetchAccountBalancesInput, ListAccountsInput}; -use std::sync::Arc; +use std::{ + cell::RefCell, + collections::{BTreeMap, HashSet}, + rc::Rc, + sync::Arc, + time::Duration, +}; use uuid::Uuid; use super::SYSTEM_SERVICE; @@ -39,14 +54,29 @@ lazy_static! { Arc::clone(&REQUEST_POLICY_SERVICE), Arc::clone(&PERMISSION_SERVICE), Arc::clone(&ACCOUNT_REPOSITORY), + Arc::clone(&ASSET_REPOSITORY) )); } +thread_local! { + + pub static BALANCE_FETCH_GUARD_STATE: + Rc>> + = Rc::new(RefCell::new(State::default())); +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct BalanceFetchGuardKey { + account_id: AccountId, + asset_id: AssetId, +} + #[derive(Default, Debug)] pub struct AccountService { request_policy_service: Arc, permission_service: Arc, account_repository: Arc, + asset_repository: Arc, } impl AccountService { @@ -57,11 +87,13 @@ impl AccountService { request_policy_service: Arc, permission_service: Arc, account_repository: Arc, + asset_repository: Arc, ) -> Self { Self { request_policy_service, permission_service, account_repository, + asset_repository, } } @@ -143,16 +175,49 @@ impl AccountService { info: format!("Account with id {} already exists", uuid.hyphenated()), })? } - let blockchain_api = - BlockchainApiFactory::build(&input.blockchain.clone(), &input.standard.clone())?; + let mut new_account = AccountMapper::from_create_input(input.to_owned(), *uuid.as_bytes(), None)?; - // The account address is generated after the account is created from the user input and - // all the validations are successfully completed. - if new_account.address.is_empty() { - let account_address = blockchain_api.generate_address(&new_account).await?; - new_account.address = account_address; + let deduplicated_asset_ids = input.assets.iter().cloned().collect::>(); + + for asset_id in deduplicated_asset_ids.iter() { + let asset = self.asset_repository.get(asset_id).ok_or_else(|| { + AccountError::ValidationError { + info: format!( + "Asset with id {} not found", + Uuid::from_bytes(*asset_id).hyphenated() + ), + } + })?; + + for standard in asset.standards.iter() { + let blockchain_api = BlockchainApiFactory::build(&asset.blockchain.clone())?; + + let mut account_addresses = Vec::::new(); + + for address_format in standard.get_info().address_formats.into_iter() { + if account_addresses + .iter() + .any(|address| address.format == address_format) + || new_account + .addresses + .iter() + .any(|address| address.format == address_format) + { + // the account already has this address + continue; + } + + let address = blockchain_api + .generate_address(&new_account.seed, address_format.clone()) + .await?; + + account_addresses.push(address); + } + + new_account.addresses.extend(account_addresses); + } } if let Some(criteria) = &input.transfer_request_policy { @@ -166,10 +231,6 @@ impl AccountService { input.configs_permission.validate()?; input.transfer_permission.validate()?; - // The decimals of the asset are fetched from the blockchain and stored in the account, - // depending on the blockchain standard used by the account the decimals used by each asset can vary. - new_account.decimals = blockchain_api.decimals(&new_account).await?; - // Validate here before database operations. new_account.validate()?; @@ -248,23 +309,41 @@ impl AccountService { // if this is the first account created, and there is no cycle minting account set, set this account as the cycle minting account if system_info.get_cycle_obtain_strategy() == &CycleObtainStrategy::Disabled && ACCOUNT_REPOSITORY.len() == 1 - && matches!(new_account.blockchain, Blockchain::InternetComputer) - && new_account.standard == BlockchainStandard::Native - && new_account.symbol == "ICP" { - ic_cdk::println!("Setting cycle minting account to {}", uuid); - - system_info.set_cycle_obtain_strategy(CycleObtainStrategy::MintFromNativeToken { - account_id: *uuid.as_bytes(), - }); - write_system_info(system_info); - - #[cfg(target_arch = "wasm32")] - crate::services::SYSTEM_SERVICE.set_fund_manager_obtain_cycles( - &CycleObtainStrategy::MintFromNativeToken { - account_id: new_account.id, - }, - ); + // find the mainnet ICP asset that minting can be done from + if let Some(icp_asset) = self.asset_repository.list().iter().find(|asset| { + asset.blockchain == Blockchain::InternetComputer + && asset + .standards + .contains(&TokenStandard::InternetComputerNative) + && asset.metadata.contains(&MetadataItem { + key: TokenStandard::METADATA_KEY_LEDGER_CANISTER_ID.to_string(), + value: MAINNET_LEDGER_CANISTER_ID.to_string(), + }) + }) { + // check if the new account has the ICP asset + if new_account + .assets + .iter() + .any(|account_asset| account_asset.asset_id == icp_asset.id) + { + ic_cdk::println!("Setting cycle minting account to {}", uuid); + + system_info.set_cycle_obtain_strategy( + CycleObtainStrategy::MintFromNativeToken { + account_id: *uuid.as_bytes(), + }, + ); + write_system_info(system_info); + + #[cfg(target_arch = "wasm32")] + crate::services::SYSTEM_SERVICE.set_fund_manager_obtain_cycles( + &CycleObtainStrategy::MintFromNativeToken { + account_id: new_account.id, + }, + ); + } + } } } @@ -289,6 +368,56 @@ impl AccountService { } } + if let Some(change_assets) = input.change_assets { + change_assets.apply(&mut account.assets); + + // get all supported address formats of the account + let mut current_address_formats: HashSet<(Blockchain, AddressFormat)> = HashSet::new(); + + for account_asset in account.assets.iter() { + let Some(asset) = self.asset_repository.get(&account_asset.asset_id) else { + ic_cdk::println!( + "Asset `{}` does not exist in account `{}`", + Uuid::from_bytes(account_asset.asset_id).hyphenated(), + Uuid::from_bytes(account.id).hyphenated() + ); + continue; + }; + + for standard in asset.standards.iter() { + standard.get_info().address_formats.iter().for_each(|f| { + current_address_formats.insert((asset.blockchain.clone(), f.to_owned())); + }); + } + } + + // remove addresses which don't belong to any account_assets any more + account.addresses.retain(|account_address| { + current_address_formats + .iter() + .any(|(_, format)| &account_address.format == format) + }); + + for (blockchain, address_format) in current_address_formats { + if account + .addresses + .iter() + .any(|address| address.format == address_format) + { + // the account already has this address + continue; + } + + let blockchain_api = BlockchainApiFactory::build(&blockchain)?; + + let address = blockchain_api + .generate_address(&account.seed, address_format.clone()) + .await?; + + account.addresses.push(address); + } + } + if let Some(RequestPolicyRuleInput::Set(criteria)) = &input.transfer_request_policy { criteria.validate()?; }; @@ -373,7 +502,7 @@ impl AccountService { pub async fn fetch_account_balances( &self, input: FetchAccountBalancesInput, - ) -> ServiceResult> { + ) -> ServiceResult>> { if input.account_ids.is_empty() || input.account_ids.len() > 5 { Err(AccountError::AccountBalancesBatchRange { min: 1, max: 5 })? } @@ -382,46 +511,182 @@ impl AccountService { .account_ids .iter() .map(|id| HelperMapper::to_uuid(id.clone())) - .collect::, _>>()?; + .collect::, _>>()?; let accounts = self .account_repository .find_by_ids(account_ids.iter().map(|id| *id.as_bytes()).collect()); - let mut balances = Vec::new(); - for mut account in accounts { - let balance_considered_fresh = match &account.balance { - Some(balance) => { - let balance_age_ns = next_time() - balance.last_modification_timestamp; - (balance_age_ns / 1_000_000) < ACCOUNT_BALANCE_FRESHNESS_IN_MS - } - None => false, - }; - let balance: AccountBalance = match (&account.balance, balance_considered_fresh) { - (None, _) | (_, false) => { - let blockchain_api = - BlockchainApiFactory::build(&account.blockchain, &account.standard)?; - let fetched_balance = blockchain_api.balance(&account).await?; - let new_balance = AccountBalance { - balance: candid::Nat(fetched_balance), - last_modification_timestamp: next_time(), + struct BalanceQueryResult { + balance: Option, + update: Option<(AccountId, AssetId, AccountBalance)>, + } + + let queries = accounts + .iter() + .flat_map(|account| { + account.assets.iter().map(|account_asset| async { + let balance_considered_fresh = match &account_asset.balance { + Some(balance) => { + let balance_age_ns = next_time() - balance.last_modification_timestamp; + (balance_age_ns / 1_000_000) < ACCOUNT_BALANCE_FRESHNESS_IN_MS + } + None => false, + }; + + let Some(asset) = self.asset_repository.get(&account_asset.asset_id) else { + return BalanceQueryResult { + balance: None, + update: None, + }; }; - account.balance = Some(new_balance.clone()); + match (&account_asset.balance, balance_considered_fresh) { + (None, _) | (_, false) => { + let balance_update_guard_key = BalanceFetchGuardKey { + account_id: account.id, + asset_id: asset.id, + }; + + let _lock = BALANCE_FETCH_GUARD_STATE.with(|state| { + CallerGuard::new( + state.clone(), + balance_update_guard_key, + Some(time() + Duration::from_secs(5 * 60).as_nanos() as u64), + ) + }); + + if _lock.is_none() { + if let Some(stale_balance) = &account_asset.balance { + BalanceQueryResult { + balance: Some(AccountMapper::to_balance_dto( + stale_balance.to_owned(), + asset.decimals, + account.id, + asset.id, + BalanceQueryState::StaleRefreshing, + )), + update: None, + } + } else { + BalanceQueryResult { + balance: None, + update: None, + } + } + } else { + let blockchain_api = + match BlockchainApiFactory::build(&asset.blockchain) { + Ok(api) => api, + Err(err) => { + ic_cdk::println!( + "Could not build blockchain api for asset with id {}. Error: {}", + Uuid::from_bytes(asset.id).hyphenated(), + err + ); + return BalanceQueryResult { + balance: None, + update: None, + }; + } + }; + + let fetched_balance = match blockchain_api + .balance(&asset, &account.addresses) + .await + { + Ok(balance) => balance, + Err(err) => { + ic_cdk::println!( + "Could not fetch balance for account with id {} and asset with id {}. Error: {}", + Uuid::from_bytes(account.id).hyphenated(), + Uuid::from_bytes(asset.id).hyphenated(), + err + ); + return BalanceQueryResult { + balance: None, + update: None, + }; + } + }; + + let new_balance = AccountBalance { + balance: candid::Nat(fetched_balance), + last_modification_timestamp: next_time(), + }; + + BalanceQueryResult { + update: Some((account.id, asset.id, new_balance.clone())), + balance: Some(AccountMapper::to_balance_dto( + new_balance, + asset.decimals, + account.id, + asset.id, + BalanceQueryState::Fresh, + )), + } + } + } + (Some(balance), true) => BalanceQueryResult { + balance: Some(AccountMapper::to_balance_dto( + balance.to_owned(), + asset.decimals, + account.id, + asset.id, + BalanceQueryState::Fresh, + )), + update: None, + }, + } + }) + }) + .collect::>(); + + let balance_query_results = futures::future::join_all(queries).await; + + let mut account_balance_updates: BTreeMap> = + Default::default(); + let mut balances = Vec::new(); + + for result in balance_query_results { + // group updates by account id to avoid multiple updates to the same account + if let Some((account_id, asset_id, balance)) = result.update { + account_balance_updates + .entry(account_id) + .or_default() + .push((asset_id, balance)); + } - self.account_repository - .insert(account.to_key(), account.clone()); + balances.push(result.balance); + } - new_balance + for (account_id, asset_balances) in account_balance_updates.into_iter() { + if let Some(mut account) = self.account_repository.get(&AccountKey { id: account_id }) { + for (asset_id, account_balance) in asset_balances.into_iter() { + if let Some(account_asset) = account + .assets + .iter_mut() + .find(|asset| asset.asset_id == asset_id) + { + account_asset.balance = Some(account_balance); + } else { + // Account no longer has the asset after the balance was fetched + ic_cdk::println!( + "Could not store new balance. Account with id {} no longer has asset with id {}", + Uuid::from_bytes(account_id).hyphenated(), + Uuid::from_bytes(asset_id).hyphenated() + ); + } } - (Some(balance), _) => balance.to_owned(), - }; - - balances.push(AccountMapper::to_balance_dto( - balance, - account.decimals, - account.id, - )); + + self.account_repository.insert(account.to_key(), account); + } else { + // Account no longer exists after the balance was fetched + ic_cdk::println!( + "Could not store new balance. Account with id {} no longer exists", + Uuid::from_bytes(account_id).hyphenated() + ); + } } Ok(balances) @@ -431,21 +696,27 @@ impl AccountService { #[cfg(test)] mod tests { use candid::Principal; + use orbit_essentials::model::ModelKey; use super::*; use crate::{ core::{test_utils, validation::disable_mock_resource_validation, CallContext}, models::{ - account_test_utils::mock_account, permission::Allow, - request_policy_rule::RequestPolicyRule, request_specifier::UserSpecifier, - user_test_utils::mock_user, AddAccountOperation, AddAccountOperationInput, Blockchain, - BlockchainStandard, Metadata, User, + account_test_utils::mock_account, + asset_test_utils::{mock_asset, mock_asset_b}, + permission::Allow, + request_policy_rule::RequestPolicyRule, + request_specifier::UserSpecifier, + user_test_utils::mock_user, + AddAccountOperation, AddAccountOperationInput, ChangeAssets, Metadata, User, }, repositories::UserRepository, + services::ASSET_SERVICE, }; struct TestContext { repository: AccountRepository, + asset_repository: AssetRepository, service: AccountService, caller_user: User, } @@ -462,6 +733,7 @@ mod tests { TestContext { repository: AccountRepository::default(), service: AccountService::default(), + asset_repository: AssetRepository::default(), caller_user: user, } } @@ -485,8 +757,7 @@ mod tests { account_id: None, input: AddAccountOperationInput { name: "foo".to_string(), - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, + assets: vec![], metadata: Metadata::default(), read_permission: Allow::users(vec![ctx.caller_user.id]), configs_permission: Allow::users(vec![ctx.caller_user.id]), @@ -516,8 +787,7 @@ mod tests { account_id: None, input: AddAccountOperationInput { name: account.name, - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, + assets: vec![], metadata: Metadata::default(), read_permission: Allow::users(vec![ctx.caller_user.id]), configs_permission: Allow::users(vec![ctx.caller_user.id]), @@ -540,8 +810,7 @@ mod tests { let base_input = AddAccountOperationInput { name: "foo".to_string(), - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, + assets: vec![], metadata: Metadata::default(), read_permission: Allow::users(vec![ctx.caller_user.id]), configs_permission: Allow::users(vec![ctx.caller_user.id]), @@ -627,8 +896,7 @@ mod tests { let input = AddAccountOperationInput { name: "foo2".to_string(), - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, + assets: vec![], metadata: Metadata::default(), read_permission: Allow::users(vec![ctx.caller_user.id]), configs_permission: Allow::users(vec![ctx.caller_user.id]), @@ -656,6 +924,7 @@ mod tests { let operation = EditAccountOperationInput { account_id: account.id, name: Some("test_edit".to_string()), + change_assets: None, read_permission: None, transfer_permission: None, configs_permission: None, @@ -672,6 +941,89 @@ mod tests { assert_eq!(updated_account.name, "test_edit"); } + #[tokio::test] + async fn edit_account_assets() { + let ctx = setup(); + + let asset_a = mock_asset(); + ctx.asset_repository.insert(asset_a.key(), asset_a.clone()); + + let asset_b = mock_asset_b(); + ctx.asset_repository.insert(asset_b.key(), asset_b.clone()); + + let mut account = mock_account(); + account.assets = vec![]; + account.addresses = vec![]; + ctx.repository.insert(account.to_key(), account.clone()); + + let operation = EditAccountOperationInput { + account_id: account.id, + name: None, + change_assets: Some(ChangeAssets::Change { + add_assets: vec![asset_a.id], + remove_assets: vec![], + }), + read_permission: None, + transfer_permission: None, + configs_permission: None, + transfer_request_policy: None, + configs_request_policy: None, + }; + + let updated_account = ctx + .service + .edit_account(operation) + .await + .expect("edit account should be successful"); + assert_eq!(updated_account.assets.len(), 1); + assert_eq!(updated_account.assets[0].asset_id, asset_a.id); + + let operation = EditAccountOperationInput { + account_id: account.id, + name: None, + change_assets: Some(ChangeAssets::Change { + add_assets: vec![asset_b.id], + remove_assets: vec![asset_a.id], + }), + read_permission: None, + transfer_permission: None, + configs_permission: None, + transfer_request_policy: None, + configs_request_policy: None, + }; + + let updated_account = ctx + .service + .edit_account(operation) + .await + .expect("edit account should be successful"); + assert_eq!(updated_account.assets.len(), 1); + assert_eq!(updated_account.assets[0].asset_id, asset_b.id); + + let operation = EditAccountOperationInput { + account_id: account.id, + name: None, + change_assets: Some(ChangeAssets::ReplaceWith { + assets: vec![asset_a.id, asset_b.id], + }), + read_permission: None, + transfer_permission: None, + configs_permission: None, + transfer_request_policy: None, + configs_request_policy: None, + }; + + let updated_account = ctx + .service + .edit_account(operation) + .await + .expect("edit account should be successful"); + + assert_eq!(updated_account.assets.len(), 2); + assert_eq!(updated_account.assets[0].asset_id, asset_a.id); + assert_eq!(updated_account.assets[1].asset_id, asset_b.id); + } + #[tokio::test] async fn edit_account_with_duplicate_name_should_fail() { let ctx = setup(); @@ -686,6 +1038,7 @@ mod tests { let operation = EditAccountOperationInput { account_id: account.id, name: Some("bar".to_string()), + change_assets: None, read_permission: None, transfer_permission: None, configs_permission: None, @@ -698,29 +1051,6 @@ mod tests { assert!(result.is_err()); } - #[tokio::test] - async fn fail_create_account_invalid_blockchain_standard() { - let ctx = setup(); - let operation = AddAccountOperation { - account_id: None, - input: AddAccountOperationInput { - name: "foo".to_string(), - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::ERC20, - metadata: Metadata::default(), - read_permission: Allow::users(vec![ctx.caller_user.id]), - configs_permission: Allow::users(vec![ctx.caller_user.id]), - transfer_permission: Allow::users(vec![ctx.caller_user.id]), - configs_request_policy: Some(RequestPolicyRule::AutoApproved), - transfer_request_policy: Some(RequestPolicyRule::AutoApproved), - }, - }; - - let result = ctx.service.create_account(operation.input, None).await; - - assert!(result.is_err()); - } - #[tokio::test] async fn edit_account_with_missing_policy_should_fail() { let ctx = setup(); @@ -729,11 +1059,15 @@ mod tests { let account = mock_account(); + let asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + ctx.repository.insert(account.to_key(), account.clone()); let base_input = EditAccountOperationInput { account_id: account.id, name: Some("test_edit".to_string()), + change_assets: None, read_permission: None, transfer_permission: None, configs_permission: None, @@ -787,4 +1121,40 @@ mod tests { .await .expect_err("transfer_request_policy should be invalid"); } + + #[tokio::test] + async fn can_add_icrc1_asset() { + disable_mock_resource_validation(); + + let asset = ASSET_SERVICE + .create( + crate::models::AddAssetOperationInput { + name: "Test ICRC1 token".to_owned(), + symbol: "TEST".to_owned(), + decimals: 4, + metadata: Metadata::default(), + blockchain: Blockchain::InternetComputer, + standards: vec![TokenStandard::ICRC1], + }, + None, + ) + .expect("asset creation should be successful"); + + ACCOUNT_SERVICE + .create_account( + AddAccountOperationInput { + name: "Test account".to_owned(), + assets: vec![asset.id], + metadata: Metadata::default(), + read_permission: Allow::authenticated(), + configs_permission: Allow::authenticated(), + transfer_permission: Allow::authenticated(), + configs_request_policy: Some(RequestPolicyRule::AutoApproved), + transfer_request_policy: Some(RequestPolicyRule::AutoApproved), + }, + None, + ) + .await + .expect("account creation should be successful"); + } } diff --git a/core/station/impl/src/services/address_book.rs b/core/station/impl/src/services/address_book.rs index 932682d36..eca4df689 100644 --- a/core/station/impl/src/services/address_book.rs +++ b/core/station/impl/src/services/address_book.rs @@ -87,6 +87,7 @@ impl AddressBookService { addresses: input.addresses, blockchain: input.blockchain, labels: input.labels, + address_formats: input.address_formats, }); Ok(paginated_items(PaginatedItemsArgs { @@ -169,7 +170,8 @@ mod tests { core::test_utils, models::{ address_book_entry_test_utils::mock_address_book_entry, AddAddressBookEntryOperation, - AddAddressBookEntryOperationInput, Blockchain, ChangeMetadata, Metadata, MetadataItem, + AddAddressBookEntryOperationInput, AddressFormat, Blockchain, ChangeMetadata, Metadata, + MetadataItem, }, }; use station_api::MetadataDTO; @@ -201,6 +203,7 @@ mod tests { blockchain: Blockchain::InternetComputer, metadata: address_book_entry.metadata.clone().into(), labels: vec![], + address_format: AddressFormat::ICPAccountIdentifier, }, }; diff --git a/core/station/impl/src/services/asset.rs b/core/station/impl/src/services/asset.rs new file mode 100644 index 000000000..be07c252f --- /dev/null +++ b/core/station/impl/src/services/asset.rs @@ -0,0 +1,347 @@ +use std::sync::Arc; + +use crate::{ + core::{authorization::Authorization, utils::retain_accessible_resources, CallContext}, + errors::AssetError, + models::{ + resource::{Resource, ResourceAction, ResourceId}, + AddAssetOperationInput, Asset, AssetCallerPrivileges, AssetId, EditAssetOperationInput, + RemoveAssetOperationInput, + }, + repositories::{AssetRepository, ACCOUNT_REPOSITORY, ASSET_REPOSITORY}, +}; +use lazy_static::lazy_static; +use orbit_essentials::{ + api::ServiceResult, + model::ModelValidator, + pagination::{paginated_items, PaginatedData, PaginatedItemsArgs}, + repository::Repository, +}; +use station_api::ListAssetsInput; +use uuid::Uuid; + +lazy_static! { + pub static ref ASSET_SERVICE: Arc = + Arc::new(AssetService::new(Arc::clone(&ASSET_REPOSITORY),)); +} + +#[derive(Default, Debug)] +pub struct AssetService { + asset_repository: Arc, +} + +impl AssetService { + pub const DEFAULT_LIST_ASSETS_LIMIT: u16 = 100; + pub const MAX_LIST_ASSETS_LIMIT: u16 = 1000; + + pub fn new(asset_repository: Arc) -> Self { + Self { asset_repository } + } + + pub fn get(&self, asset_id: &AssetId) -> ServiceResult { + let asset = self + .asset_repository + .get(asset_id) + .ok_or(AssetError::NotFound { + id: Uuid::from_bytes(*asset_id).hyphenated().to_string(), + })?; + + Ok(asset) + } + + pub fn create( + &self, + input: AddAssetOperationInput, + with_asset_id: Option, + ) -> ServiceResult { + let id = with_asset_id.unwrap_or(*Uuid::new_v4().as_bytes()); + + let asset = Asset { + id, + blockchain: input.blockchain, + standards: input.standards.into_iter().collect(), + symbol: input.symbol, + name: input.name, + decimals: input.decimals, + metadata: input.metadata, + }; + + asset.validate()?; + + self.asset_repository.insert(asset.id, asset.clone()); + + Ok(asset) + } + + pub fn edit(&self, input: EditAssetOperationInput) -> ServiceResult { + let mut asset = self.get(&input.asset_id)?; + + if let Some(name) = input.name { + asset.name = name; + } + + if let Some(symbol) = input.symbol { + asset.symbol = symbol; + } + + if let Some(change_metadata) = input.change_metadata { + asset.metadata.change(change_metadata); + } + + if let Some(blockchain) = input.blockchain { + asset.blockchain = blockchain; + } + + if let Some(standards) = input.standards { + asset.standards = standards.into_iter().collect(); + } + + asset.validate()?; + + self.asset_repository.insert(asset.id, asset.clone()); + + Ok(asset) + } + + pub fn remove(&self, input: RemoveAssetOperationInput) -> ServiceResult { + let asset = self.get(&input.asset_id)?; + + let accounts = ACCOUNT_REPOSITORY.list(); + + for account in accounts { + if account + .assets + .iter() + .any(|account_asset| account_asset.asset_id == asset.id) + { + return Err(AssetError::AssetInUse { + id: Uuid::from_bytes(account.id).hyphenated().to_string(), + resource: "account".to_string(), + })?; + } + } + + self.asset_repository.remove(&input.asset_id); + + Ok(asset) + } + + pub async fn get_caller_privileges_for_asset( + &self, + asset_id: &AssetId, + ctx: &CallContext, + ) -> ServiceResult { + Ok(AssetCallerPrivileges { + id: *asset_id, + can_edit: Authorization::is_allowed( + ctx, + &Resource::Asset(ResourceAction::Update(ResourceId::Id(*asset_id))), + ), + can_delete: Authorization::is_allowed( + ctx, + &Resource::Asset(ResourceAction::Delete(ResourceId::Id(*asset_id))), + ), + }) + } + + pub fn list( + &self, + input: ListAssetsInput, + ctx: Option<&CallContext>, + ) -> ServiceResult> { + let mut assets = self.asset_repository.list(); + + if let Some(ctx) = ctx { + // filter out assets that the caller does not have access to read + retain_accessible_resources(ctx, &mut assets, |asset| { + Resource::Asset(crate::models::resource::ResourceAction::Read( + crate::models::resource::ResourceId::Id(asset.id), + )) + }); + } + + let result = paginated_items(PaginatedItemsArgs { + offset: input.paginate.to_owned().and_then(|p| p.offset), + limit: input.paginate.and_then(|p| p.limit), + default_limit: Some(Self::DEFAULT_LIST_ASSETS_LIMIT), + max_limit: Some(Self::MAX_LIST_ASSETS_LIMIT), + items: &assets, + })?; + + Ok(result) + } +} + +#[cfg(test)] +mod tests { + use orbit_essentials::repository::Repository; + use station_api::ListAssetsInput; + + use crate::{ + models::{ + account_test_utils::mock_account, asset_test_utils::mock_asset, AddAssetOperationInput, + TokenStandard, + }, + repositories::{ACCOUNT_REPOSITORY, ASSET_REPOSITORY}, + }; + + use super::AssetService; + + #[tokio::test] + async fn test_asset_creation() { + let service = AssetService::default(); + + service + .create( + AddAssetOperationInput { + blockchain: crate::models::Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + decimals: 8, + metadata: Default::default(), + name: "ICP".to_string(), + symbol: "ICP".to_string(), + }, + None, + ) + .expect("Failed to create asset"); + + let assets = ASSET_REPOSITORY.list(); + + assert_eq!(assets.len(), 1); + assert_eq!(assets[0].name, "ICP"); + } + + #[tokio::test] + async fn test_asset_edit() { + let service = AssetService::default(); + let mut mock_asset = mock_asset(); + mock_asset.name = "Bitcoin".to_string(); + ASSET_REPOSITORY.insert(mock_asset.id, mock_asset.clone()); + + service + .edit(crate::models::EditAssetOperationInput { + asset_id: mock_asset.id, + name: Some("Internet Computer".to_string()), + symbol: Some("ICP".to_string()), + change_metadata: None, + blockchain: None, + standards: None, + }) + .expect("Failed to edit asset"); + + let assets = ASSET_REPOSITORY.list(); + + assert_eq!(assets.len(), 1); + assert_eq!(assets[0].name, "Internet Computer"); + } + + #[tokio::test] + async fn test_unused_asset_remove() { + let service = AssetService::default(); + let mock_asset = mock_asset(); + ASSET_REPOSITORY.insert(mock_asset.id, mock_asset.clone()); + + service + .remove(crate::models::RemoveAssetOperationInput { + asset_id: mock_asset.id, + }) + .expect("Failed to remove asset"); + + let assets = ASSET_REPOSITORY.list(); + + assert_eq!(assets.len(), 0); + } + + #[tokio::test] + async fn test_used_asset_remove_fails() { + let service = AssetService::default(); + let mock_asset = mock_asset(); + ASSET_REPOSITORY.insert(mock_asset.id, mock_asset.clone()); + + let mock_account = mock_account(); + + ACCOUNT_REPOSITORY.insert(mock_account.to_key(), mock_account.clone()); + + service + .remove(crate::models::RemoveAssetOperationInput { + asset_id: mock_asset.id, + }) + .expect_err("Asset should not be removed"); + + let assets = ASSET_REPOSITORY.list(); + + assert_eq!(assets.len(), 1); + } + + #[tokio::test] + async fn test_asset_list() { + let service = AssetService::default(); + let mock_asset = mock_asset(); + ASSET_REPOSITORY.insert(mock_asset.id, mock_asset.clone()); + + let assets = service + .list(ListAssetsInput { paginate: None }, None) + .expect("Failed to list assets"); + + assert_eq!(assets.items.len(), 1); + assert_eq!(assets.items[0].name, "Internet Computer"); + } + + #[tokio::test] + async fn test_asset_get() { + let service = AssetService::default(); + let mock_asset = mock_asset(); + ASSET_REPOSITORY.insert(mock_asset.id, mock_asset.clone()); + + let asset = service.get(&mock_asset.id).expect("Failed to get asset"); + + assert_eq!(asset.name, "Internet Computer"); + } + + #[tokio::test] + async fn test_asset_uniqueness() { + let service = AssetService::default(); + + service + .create( + AddAssetOperationInput { + blockchain: crate::models::Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + decimals: 8, + metadata: Default::default(), + name: "ICP".to_string(), + symbol: "ICP".to_string(), + }, + None, + ) + .expect("Failed to create asset"); + + service + .create( + AddAssetOperationInput { + blockchain: crate::models::Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + decimals: 8, + metadata: Default::default(), + name: "ICP".to_string(), + symbol: "ICP".to_string(), + }, + None, + ) + .expect_err("Asset with the same symbol and blockchain should not be allowed"); + + service + .create( + AddAssetOperationInput { + blockchain: crate::models::Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + decimals: 8, + metadata: Default::default(), + name: "ICP".to_string(), + symbol: "ICP2".to_string(), + }, + None, + ) + .expect("Failed to create asset"); + } +} diff --git a/core/station/impl/src/services/disaster_recovery.rs b/core/station/impl/src/services/disaster_recovery.rs index 308f6d74a..f03205d8b 100644 --- a/core/station/impl/src/services/disaster_recovery.rs +++ b/core/station/impl/src/services/disaster_recovery.rs @@ -8,8 +8,11 @@ use super::{SystemService, UserService, USER_SERVICE}; use crate::{ core::observer::Observer, errors::DisasterRecoveryError, - models::{Account, User, UserStatus}, - repositories::{AccountRepository, ACCOUNT_REPOSITORY}, + models::{Account, Asset, User, UserStatus}, + repositories::{ + AccountRepository, AssetRepository, InsertEntryObserverArgs, ACCOUNT_REPOSITORY, + ASSET_REPOSITORY, + }, services::SYSTEM_SERVICE, }; use orbit_essentials::repository::Repository; @@ -19,6 +22,7 @@ lazy_static! { system_service: Arc::clone(&SYSTEM_SERVICE), user_service: Arc::clone(&USER_SERVICE), account_repository: Arc::clone(&ACCOUNT_REPOSITORY), + asset_repository: Arc::clone(&ASSET_REPOSITORY), }); } @@ -26,31 +30,22 @@ pub struct DisasterRecoveryService { system_service: Arc, user_service: Arc, account_repository: Arc, + asset_repository: Arc, } impl DisasterRecoveryService { - pub async fn sync_accounts(&self) -> ServiceResult<()> { + pub async fn sync_accounts_and_assets(&self) -> ServiceResult<()> { let upgrader_canister_id = self.system_service.get_upgrader_canister_id(); let accounts = self.account_repository.list(); + let assets = self.asset_repository.list(); ic_cdk::call( upgrader_canister_id, - "set_disaster_recovery_accounts", - (upgrader_api::SetDisasterRecoveryAccountsInput { - accounts: accounts - .iter() - .map(|account| upgrader_api::Account { - id: Uuid::from_bytes(account.id).hyphenated().to_string(), - blockchain: account.blockchain.to_string(), - address: account.address.clone(), - standard: account.standard.to_string(), - symbol: account.symbol.clone(), - decimals: account.decimals, - name: account.name.clone(), - metadata: account.metadata.clone().into(), - }) - .collect(), + "set_disaster_recovery_accounts_and_assets", + (upgrader_api::SetDisasterRecoveryAccountsAndAssetsInput { + accounts: accounts.into_iter().map(Into::into).collect(), + assets: assets.into_iter().map(Into::into).collect(), },), ) .await @@ -106,7 +101,7 @@ impl DisasterRecoveryService { if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_committee().await { crate::core::ic_cdk::api::print(format!("Failed to sync committee: {}", error,)); } - if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_accounts().await { + if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_accounts_and_assets().await { crate::core::ic_cdk::api::print(format!("Failed to sync accounts: {}", error,)); } } @@ -181,19 +176,226 @@ pub fn disaster_recovery_observes_remove_user(observer: &mut Observer) { })); } -pub fn disaster_recovery_observes_insert_account( - observer: &mut Observer<(Account, Option)>, -) { - observer.add_listener(Box::new(|(_account, _prev)| { +#[cfg(test)] +thread_local! { + static SYNC_CALLED: std::cell::RefCell = const { std::cell::RefCell::new(0) }; +} + +pub fn disaster_recovery_sync_accounts_and_assets_on_remove(observer: &mut Observer<()>) { + observer.add_listener(Box::new(|_| { if !SYSTEM_SERVICE.is_healthy() { - // Skip syncing accounts during system init + // Skip syncing during system init return; } + #[cfg(test)] + SYNC_CALLED.with(|sync_called| { + *sync_called.borrow_mut() += 1; + }); + crate::core::ic_cdk::spawn(async { - if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_accounts().await { - crate::core::ic_cdk::api::print(format!("Failed to sync accounts: {}", error,)); + if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_accounts_and_assets().await { + crate::core::ic_cdk::api::print(format!( + "Failed to sync accounts and assets: {}", + error, + )); } }); })); } + +/// A trait for comparing two values for equality in the context of Disaster Recovery. +/// Two values are considered equal if they are the same when serialized into the format +/// stored by the Upgrader. +pub trait SyncEq { + fn sync_eq(&self) -> bool; +} + +impl SyncEq for InsertEntryObserverArgs { + fn sync_eq(&self) -> bool { + if let Some(prev) = &self.prev { + let current_synced: upgrader_api::MultiAssetAccount = self.current.clone().into(); + let prev_synced: upgrader_api::MultiAssetAccount = prev.clone().into(); + + current_synced == prev_synced + } else { + false + } + } +} + +impl SyncEq for InsertEntryObserverArgs { + fn sync_eq(&self) -> bool { + if let Some(prev) = &self.prev { + let current_synced: upgrader_api::Asset = self.current.clone().into(); + let prev_synced: upgrader_api::Asset = prev.clone().into(); + + current_synced == prev_synced + } else { + false + } + } +} + +pub fn disaster_recovery_sync_accounts_and_assets_on_insert(observer: &mut Observer) +where + T: SyncEq, +{ + observer.add_listener(Box::new(|sync_cmp| { + if !SYSTEM_SERVICE.is_healthy() { + // Skip syncing during system init + return; + } + + if sync_cmp.sync_eq() { + // Skip syncing if the account or asset hasn't changed + return; + } + + #[cfg(test)] + SYNC_CALLED.with(|sync_called| { + *sync_called.borrow_mut() += 1; + }); + + crate::core::ic_cdk::spawn(async { + if let Err(error) = DISASTER_RECOVERY_SERVICE.sync_accounts_and_assets().await { + crate::core::ic_cdk::api::print(format!( + "Failed to sync accounts and assets: {}", + error, + )); + } + }); + })); +} + +#[cfg(test)] +mod tests { + + use orbit_essentials::{model::ModelKey, repository::Repository}; + + use crate::{ + core::test_utils::init_canister_system, + models::{ + account_test_utils::mock_account, asset_test_utils::mock_asset, AccountAsset, + AccountBalance, + }, + repositories::{InsertEntryObserverArgs, ACCOUNT_REPOSITORY, ASSET_REPOSITORY}, + services::SyncEq, + }; + + use super::SYNC_CALLED; + + #[test] + fn test_account_eq() { + let prev_account = mock_account(); + let mut current_account = prev_account.clone(); + + assert!(!InsertEntryObserverArgs { + current: current_account.clone(), + prev: None, + } + .sync_eq()); + + assert!(InsertEntryObserverArgs { + current: current_account.clone(), + prev: Some(prev_account.clone()), + } + .sync_eq()); + + current_account.assets[0].balance = Some(AccountBalance { + balance: 1000u64.into(), + last_modification_timestamp: 1, + }); + + // Account has not changed as far as the sync is concerned + assert!(InsertEntryObserverArgs { + current: current_account.clone(), + prev: Some(prev_account.clone()), + } + .sync_eq()); + + current_account.assets.push(AccountAsset { + asset_id: [1; 16], + balance: None, + }); + + // Account has changed + assert!(!InsertEntryObserverArgs { + current: current_account.clone(), + prev: Some(prev_account.clone()), + } + .sync_eq()); + } + + #[test] + fn test_asset_eq() { + let prev_asset = mock_asset(); + let mut current_asset = prev_asset.clone(); + + assert!(!InsertEntryObserverArgs { + current: current_asset.clone(), + prev: None, + } + .sync_eq()); + + assert!(InsertEntryObserverArgs { + current: current_asset.clone(), + prev: Some(prev_asset.clone()), + } + .sync_eq()); + + current_asset + .metadata + .change(crate::models::ChangeMetadata::RemoveKeys(vec![ + "index_canister_id".to_string(), + ])); + + // Asset has changed + assert!(!InsertEntryObserverArgs { + current: current_asset.clone(), + prev: Some(prev_asset.clone()), + } + .sync_eq()); + } + + #[test] + fn test_sync_call() { + init_canister_system(); + + let mut asset = mock_asset(); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 1); + + let mut account = mock_account(); + ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 2); + + account.assets[0].balance = Some(AccountBalance { + balance: 1000u64.into(), + last_modification_timestamp: 1, + }); + ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); + // Account has not changed as far as the sync is concerned + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 2); + + account.assets.push(AccountAsset { + asset_id: [1; 16], + balance: None, + }); + ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); + // Account has changed + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 3); + + asset + .metadata + .change(crate::models::ChangeMetadata::RemoveKeys(vec![ + "index_canister_id".to_string(), + ])); + ASSET_REPOSITORY.insert(asset.key(), asset.clone()); + // Asset has changed + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 4); + + ASSET_REPOSITORY.remove(&asset.key()); + assert_eq!(SYNC_CALLED.with(|sync_called| *sync_called.borrow()), 5); + } +} diff --git a/core/station/impl/src/services/external_canister.rs b/core/station/impl/src/services/external_canister.rs index a9b7a4021..b9da0316a 100644 --- a/core/station/impl/src/services/external_canister.rs +++ b/core/station/impl/src/services/external_canister.rs @@ -330,7 +330,7 @@ impl ExternalCanisterService { }, ); - // filter out requests that the caller does not have access to read + // filter out external canisters that the caller does not have access to read retain_accessible_resources(ctx, &mut found_ids, |id| { Resource::ExternalCanister(ExternalCanisterResourceAction::Read( ExternalCanisterId::Canister(*id), diff --git a/core/station/impl/src/services/mod.rs b/core/station/impl/src/services/mod.rs index 568f7a67c..ea80e5553 100644 --- a/core/station/impl/src/services/mod.rs +++ b/core/station/impl/src/services/mod.rs @@ -37,3 +37,6 @@ pub mod permission; mod disaster_recovery; pub use disaster_recovery::*; + +mod asset; +pub use asset::*; diff --git a/core/station/impl/src/services/request.rs b/core/station/impl/src/services/request.rs index 04ca27e51..da47cf903 100644 --- a/core/station/impl/src/services/request.rs +++ b/core/station/impl/src/services/request.rs @@ -542,6 +542,7 @@ mod tests { core::test_utils, models::{ account_test_utils::mock_account, + asset_test_utils::mock_asset, permission::Allow, request_policy_rule::RequestPolicyRule, request_policy_test_utils::mock_request_policy, @@ -550,16 +551,16 @@ mod tests { resource::ResourceIds, user_test_utils::mock_user, AddAccountOperationInput, AddAddressBookEntryOperation, - AddAddressBookEntryOperationInput, AddUserOperation, AddUserOperationInput, Blockchain, - BlockchainStandard, Metadata, Percentage, RequestApproval, RequestOperation, - RequestPolicy, RequestStatus, TransferOperation, TransferOperationInput, User, - UserGroup, UserStatus, ADMIN_GROUP_ID, + AddAddressBookEntryOperationInput, AddAssetOperationInput, AddUserOperation, + AddUserOperationInput, AddressFormat, Asset, Blockchain, Metadata, Percentage, + RequestApproval, RequestOperation, RequestPolicy, RequestStatus, TokenStandard, + TransferOperation, TransferOperationInput, User, UserGroup, UserStatus, ADMIN_GROUP_ID, }, repositories::{ - request_policy::REQUEST_POLICY_REPOSITORY, AccountRepository, NOTIFICATION_REPOSITORY, - USER_GROUP_REPOSITORY, USER_REPOSITORY, + request_policy::REQUEST_POLICY_REPOSITORY, AccountRepository, AssetRepository, + NOTIFICATION_REPOSITORY, USER_GROUP_REPOSITORY, USER_REPOSITORY, }, - services::AccountService, + services::{AccountService, ASSET_SERVICE}, }; use candid::Principal; use orbit_essentials::{api::ApiError, model::ModelKey}; @@ -570,6 +571,7 @@ mod tests { struct TestContext { repository: RequestRepository, account_repository: AccountRepository, + asset_repository: AssetRepository, service: RequestService, caller_user: User, call_context: CallContext, @@ -600,6 +602,7 @@ mod tests { TestContext { repository: RequestRepository::default(), account_repository: AccountRepository::default(), + asset_repository: AssetRepository::default(), service: RequestService::default(), account_service: AccountService::default(), caller_user: user, @@ -620,12 +623,15 @@ mod tests { fee: None, input: TransferOperationInput { from_account_id: *account_id.as_bytes(), + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), network: "mainnet".to_string(), to: "0x1234".to_string(), }, + asset: mock_asset(), }); ctx.account_repository @@ -651,12 +657,15 @@ mod tests { fee: None, input: TransferOperationInput { from_account_id: *account_id.as_bytes(), + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), network: "mainnet".to_string(), to: "0x1234".to_string(), }, + asset: mock_asset(), }); request.approvals = vec![]; let mut request_policy = mock_request_policy(); @@ -710,6 +719,13 @@ mod tests { USER_REPOSITORY.insert(unrelated_user.to_key(), unrelated_user.clone()); // creates the account for the transfer + let asset = Asset { + id: [1; 16], + ..mock_asset() + }; + + ctx.asset_repository.insert(asset.key(), asset.clone()); + let account = mock_account(); ctx.account_repository @@ -733,6 +749,8 @@ mod tests { from_account_id: Uuid::from_bytes(account.id.to_owned()) .hyphenated() .to_string(), + from_asset_id: Uuid::from_bytes([1; 16]).hyphenated().to_string(), + with_standard: TokenStandard::InternetComputerNative.to_string(), amount: candid::Nat(100u32.into()), fee: None, metadata: vec![], @@ -781,6 +799,7 @@ mod tests { blockchain: "icp".to_owned(), metadata: vec![], labels: vec![], + address_format: AddressFormat::ICPAccountIdentifier.to_string(), }, ), title: None, @@ -806,8 +825,11 @@ mod tests { request.operation = RequestOperation::Transfer(TransferOperation { transfer_id: None, fee: None, + asset: mock_asset(), input: TransferOperationInput { from_account_id: [9; 16], + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), @@ -841,8 +863,11 @@ mod tests { request.operation = RequestOperation::Transfer(TransferOperation { transfer_id: None, fee: None, + asset: mock_asset(), input: TransferOperationInput { from_account_id: [9; 16], + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), @@ -876,8 +901,11 @@ mod tests { request.operation = RequestOperation::Transfer(TransferOperation { transfer_id: None, fee: None, + asset: mock_asset(), input: TransferOperationInput { from_account_id: [9; 16], + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), @@ -932,6 +960,7 @@ mod tests { blockchain: Blockchain::InternetComputer, metadata: vec![], labels: vec![], + address_format: AddressFormat::ICPAccountIdentifier, }, }); request.approvals = vec![ @@ -999,12 +1028,15 @@ mod tests { fee: None, input: TransferOperationInput { from_account_id: [9; 16], + from_asset_id: [1; 16], + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), network: "mainnet".to_string(), to: "0x1234".to_string(), }, + asset: mock_asset(), }); request.created_timestamp = 10; request.approvals = vec![]; @@ -1060,6 +1092,20 @@ mod tests { no_access_user.identities = vec![Principal::from_slice(&[2; 29])]; USER_REPOSITORY.insert(no_access_user.to_key(), no_access_user.clone()); + let asset = ASSET_SERVICE + .create( + AddAssetOperationInput { + name: "foo".to_string(), + symbol: "FOO".to_string(), + decimals: 18, + metadata: Metadata::default(), + blockchain: Blockchain::InternetComputer, + standards: vec![TokenStandard::InternetComputerNative], + }, + None, + ) + .expect("Failed to create asset"); + // create account let account_owners = vec![ctx.caller_user.id, transfer_requester_user.id]; let account = ctx @@ -1067,8 +1113,7 @@ mod tests { .create_account( AddAccountOperationInput { name: "foo".to_string(), - blockchain: Blockchain::InternetComputer, - standard: BlockchainStandard::Native, + assets: vec![asset.id], metadata: Metadata::default(), transfer_request_policy: Some(RequestPolicyRule::QuorumPercentage( UserSpecifier::Id(vec![ctx.caller_user.id, transfer_requester_user.id]), @@ -1116,12 +1161,15 @@ mod tests { fee: None, input: TransferOperationInput { from_account_id: account.id, + from_asset_id: asset.id, + with_standard: TokenStandard::InternetComputerNative, amount: candid::Nat(100u32.into()), fee: None, metadata: Metadata::default(), network: "mainnet".to_string(), to: "0x1234".to_string(), }, + asset: mock_asset(), }); transfer.created_timestamp = 10 + i as u64; transfer.approvals = vec![RequestApproval { diff --git a/core/station/impl/src/services/system.rs b/core/station/impl/src/services/system.rs index 1dd54d956..3e49186eb 100644 --- a/core/station/impl/src/services/system.rs +++ b/core/station/impl/src/services/system.rs @@ -11,13 +11,13 @@ use crate::{ factories::blockchains::InternetComputer, models::{ system::{DisasterRecoveryCommittee, SystemInfo, SystemState}, - CanisterInstallMode, CanisterUpgradeModeArgs, CycleObtainStrategy, - ManageSystemInfoOperationInput, RequestId, RequestKey, RequestOperation, RequestStatus, - SystemUpgradeTarget, WasmModuleExtraChunks, + AccountKey, Asset, Blockchain, CanisterInstallMode, CanisterUpgradeModeArgs, + CycleObtainStrategy, ManageSystemInfoOperationInput, Metadata, RequestId, RequestKey, + RequestOperation, RequestStatus, SystemUpgradeTarget, TokenStandard, WasmModuleExtraChunks, }, repositories::{ - permission::PERMISSION_REPOSITORY, RequestRepository, REQUEST_REPOSITORY, - USER_GROUP_REPOSITORY, USER_REPOSITORY, + permission::PERMISSION_REPOSITORY, RequestRepository, ACCOUNT_REPOSITORY, ASSET_REPOSITORY, + REQUEST_REPOSITORY, USER_GROUP_REPOSITORY, USER_REPOSITORY, }, services::{ change_canister::{ChangeCanisterService, CHANGE_CANISTER_SERVICE}, @@ -37,16 +37,46 @@ use lazy_static::lazy_static; use orbit_essentials::api::ServiceResult; use orbit_essentials::repository::Repository; use station_api::{HealthStatus, SystemInit, SystemInstall, SystemUpgrade}; -use std::sync::Arc; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; use upgrader_api::UpgradeParams; use uuid::Uuid; +pub const INITIAL_ICP_ASSET_ID: [u8; 16] = [ + 0x78, 0x02, 0xcb, 0xab, 0x22, 0x1d, 0x4e, 0x49, 0xb7, 0x64, 0xa6, 0x95, 0xea, 0x6d, 0xef, 0x1a, +]; + lazy_static! { pub static ref SYSTEM_SERVICE: Arc = Arc::new(SystemService::new( Arc::clone(&REQUEST_REPOSITORY), Arc::clone(&REQUEST_SERVICE), Arc::clone(&CHANGE_CANISTER_SERVICE) )); + pub static ref INITIAL_ICP_ASSET: Asset = Asset { + id: INITIAL_ICP_ASSET_ID, + blockchain: Blockchain::InternetComputer, + decimals: 8, + name: "Internet Computer".to_string(), + symbol: "ICP".to_string(), + + standards: BTreeSet::from([TokenStandard::InternetComputerNative, TokenStandard::ICRC1,]), + metadata: Metadata::new(BTreeMap::from([ + ( + "ledger_canister_id".to_string(), + "ryjl3-tyaaa-aaaaa-aaaba-cai".to_string(), + ), + ( + "index_canister_id".to_string(), + "qhbym-qaaaa-aaaaa-aaafq-cai".to_string(), + ), + ])), + }; +} + +thread_local! { + pub static INITIALIZING: std::cell::RefCell = const { std::cell::RefCell::new(false) }; } #[derive(Default, Debug)] @@ -92,7 +122,13 @@ impl SystemService { let state = read_system_state(); match state { - SystemState::Initialized(_) => HealthStatus::Healthy, + SystemState::Initialized(_) => { + if INITIALIZING.with_borrow(|init| *init) { + HealthStatus::Uninitialized + } else { + HealthStatus::Healthy + } + } SystemState::Uninitialized => HealthStatus::Uninitialized, } } @@ -192,18 +228,29 @@ impl SystemService { ) -> Option { match strategy { CycleObtainStrategy::Disabled => None, - CycleObtainStrategy::MintFromNativeToken { account_id } => Some(ObtainCyclesOptions { - obtain_cycles: Arc::new(MintCycles { - ledger: Arc::new(IcLedgerCanister::new(MAINNET_LEDGER_CANISTER_ID)), - cmc: Arc::new(IcCyclesMintingCanister::new( - MAINNET_CYCLES_MINTING_CANISTER_ID, - )), - from_subaccount: Subaccount( - InternetComputer::subaccount_from_station_account_id(account_id), - ), - }), - top_up_self: true, - }), + CycleObtainStrategy::MintFromNativeToken { account_id } => { + if let Some(account) = ACCOUNT_REPOSITORY.get(&AccountKey { id: *account_id }) { + Some(ObtainCyclesOptions { + obtain_cycles: Arc::new(MintCycles { + ledger: Arc::new(IcLedgerCanister::new(MAINNET_LEDGER_CANISTER_ID)), + cmc: Arc::new(IcCyclesMintingCanister::new( + MAINNET_CYCLES_MINTING_CANISTER_ID, + )), + from_subaccount: Subaccount(InternetComputer::subaccount_from_seed( + &account.seed, + )), + }), + top_up_self: true, + }) + } else { + print(format!( + "Account with id `{}` not found, cannot create ObtainCyclesOptions", + Uuid::from_bytes(*account_id).hyphenated() + )); + + None + } + } } } #[cfg(target_arch = "wasm32")] @@ -257,6 +304,10 @@ impl SystemService { system_info.update_last_upgrade_timestamp(); write_system_info(system_info.to_owned()); + + INITIALIZING.with_borrow_mut(|initializing| { + *initializing = false; + }); } async fn install_canister_post_process_work( @@ -292,10 +343,17 @@ impl SystemService { let admin_count = init.admins.len() as u16; let quorum = calc_initial_quorum(admin_count, init.quorum); + // if provided, creates the initial assets + if let Some(assets) = init.assets.clone() { + print("Adding initial assets"); + install_canister_handlers::set_initial_assets(assets).await?; + } + // if provided, creates the initial accounts if let Some(accounts) = init.accounts { print("Adding initial accounts"); - install_canister_handlers::set_initial_accounts(accounts, quorum).await?; + install_canister_handlers::set_initial_accounts(accounts, &init.assets, quorum) + .await?; } if SYSTEM_SERVICE.is_healthy() { @@ -351,6 +409,7 @@ impl SystemService { USER_GROUP_REPOSITORY.build_cache(); USER_REPOSITORY.build_cache(); PERMISSION_REPOSITORY.build_cache(); + ASSET_REPOSITORY.build_cache(); } /// Initializes the canister with the given owners and settings. @@ -375,6 +434,9 @@ impl SystemService { // registers the admins of the canister init_canister_sync_handlers::set_admins(input.admins.clone())?; + // add initial assets + init_canister_sync_handlers::add_initial_assets(); + // sets the name of the canister system_info.set_name(input.name.clone()); @@ -499,17 +561,21 @@ impl SystemService { mod init_canister_sync_handlers { use crate::core::ic_cdk::{api::print, next_time}; - use crate::models::{AddUserOperationInput, UserStatus}; + use crate::models::{AddUserOperationInput, Asset, UserStatus}; + use crate::repositories::ASSET_REPOSITORY; use crate::services::USER_SERVICE; use crate::{ models::{UserGroup, ADMIN_GROUP_ID}, repositories::USER_GROUP_REPOSITORY, }; use orbit_essentials::api::ApiError; + use orbit_essentials::model::ModelKey; use orbit_essentials::repository::Repository; use station_api::AdminInitInput; use uuid::Uuid; + use super::INITIAL_ICP_ASSET; + pub fn add_admin_group() { // adds the admin group which is used as the default group for admins during the canister instantiation USER_GROUP_REPOSITORY.insert( @@ -522,6 +588,15 @@ mod init_canister_sync_handlers { ); } + pub fn add_initial_assets() { + let initial_assets: Vec = vec![INITIAL_ICP_ASSET.clone()]; + + for asset in initial_assets { + print(format!("Adding initial asset: {}", asset.name)); + ASSET_REPOSITORY.insert(asset.key(), asset); + } + } + /// Registers the newly added admins of the canister. pub fn set_admins(admins: Vec) -> Result<(), ApiError> { print(format!("Registering {} admin users", admins.len())); @@ -560,12 +635,13 @@ mod install_canister_handlers { use crate::models::permission::Allow; use crate::models::request_specifier::UserSpecifier; use crate::models::{ - AddAccountOperationInput, AddRequestPolicyOperationInput, CycleObtainStrategy, - EditPermissionOperationInput, RequestPolicyRule, ADMIN_GROUP_ID, + AddAccountOperationInput, AddAssetOperationInput, AddRequestPolicyOperationInput, + CycleObtainStrategy, EditPermissionOperationInput, RequestPolicyRule, ADMIN_GROUP_ID, }; + use crate::repositories::ASSET_REPOSITORY; use crate::services::permission::PERMISSION_SERVICE; - use crate::services::ACCOUNT_SERVICE; use crate::services::REQUEST_POLICY_SERVICE; + use crate::services::{ACCOUNT_SERVICE, ASSET_SERVICE}; use candid::{Encode, Principal}; use canfund::manager::options::{EstimatedRuntime, FundManagerOptions, FundStrategy}; use canfund::manager::RegisterOpts; @@ -573,9 +649,12 @@ mod install_canister_handlers { use ic_cdk::api::management_canister::main::{self as mgmt}; use ic_cdk::id; + use orbit_essentials::api::ApiError; + use orbit_essentials::repository::Repository; use orbit_essentials::types::UUID; - use station_api::{InitAccountInput, SystemInit}; + use station_api::{InitAccountInput, InitAssetInput, SystemInit}; use std::cell::RefCell; + use uuid::Uuid; use super::SYSTEM_SERVICE; @@ -618,6 +697,7 @@ mod install_canister_handlers { // Registers the initial accounts of the canister during the canister initialization. pub async fn set_initial_accounts( accounts: Vec, + initial_assets: &Option>, quorum: u16, ) -> Result<(), String> { let add_accounts = accounts @@ -625,10 +705,15 @@ mod install_canister_handlers { .map(|account| { let input = AddAccountOperationInput { name: account.name, - blockchain: BlockchainMapper::to_blockchain(account.blockchain.clone()) - .expect("Invalid blockchain"), - standard: BlockchainMapper::to_blockchain_standard(account.standard) - .expect("Invalid blockchain standard"), + assets: account + .assets + .into_iter() + .map(|asset| { + *HelperMapper::to_uuid(asset) + .expect("Invalid UUID") + .as_bytes() + }) + .collect(), metadata: account.metadata.into(), transfer_request_policy: Some(RequestPolicyRule::Quorum( UserSpecifier::Group(vec![*ADMIN_GROUP_ID]), @@ -652,7 +737,55 @@ mod install_canister_handlers { }) .collect::)>>(); - for (new_account, with_account_id) in add_accounts { + // + // In case there are assets existing in the Asset repository at the time of recovering the assets + // some of the assets might not be able to be recreated, in this case we try to find the same asset + // in the existing assets and replace the asset_id in the recreated account with the existing one. + // + for (mut new_account, with_account_id) in add_accounts { + if let Some(initial_assets) = initial_assets { + let mut new_account_assets = new_account.assets.clone(); + for asset_id in new_account.assets.iter() { + if ASSET_REPOSITORY.get(asset_id).is_none() { + // the asset could not be recreated, try to find the same asset in the existing assets + let asset_id_str = Uuid::from_bytes(*asset_id).hyphenated().to_string(); + let Some(original_asset_to_create) = initial_assets + .iter() + .find(|initial_asset| initial_asset.id == asset_id_str) + else { + // the asset does not exist and it could not be recreated, skip + continue; + }; + + if let Some(existing_asset_id) = ASSET_REPOSITORY.exists_unique( + &original_asset_to_create.blockchain, + &original_asset_to_create.symbol, + ) { + // replace the asset_id in the recreated account with the existing one + new_account_assets.retain(|id| asset_id != id); + new_account_assets.push(existing_asset_id); + + print(format!( + "Asset {} could not be recreated, replaced with existing asset {}", + asset_id_str, + Uuid::from_bytes(existing_asset_id).hyphenated() + )); + } else { + // the asset does not exist and it could not be recreated, skip + + print(format!( + "Asset {} could not be recreated and does not exist in the existing assets, skipping", + asset_id_str + )); + + continue; + } + } + } + + new_account.assets = new_account_assets; + } + ACCOUNT_SERVICE .create_account(new_account, with_account_id) .await @@ -661,6 +794,53 @@ mod install_canister_handlers { Ok(()) } + // Registers the initial accounts of the canister during the canister initialization. + pub async fn set_initial_assets(assets: Vec) -> Result<(), String> { + let add_assets = assets + .into_iter() + .map(|asset| { + let input = AddAssetOperationInput { + name: asset.name, + blockchain: BlockchainMapper::to_blockchain(asset.blockchain.clone()) + .expect("Invalid blockchain"), + standards: asset + .standards + .iter() + .map(|standard| { + BlockchainMapper::to_blockchain_standard(standard.clone()) + .expect("Invalid blockchain standard") + }) + .collect(), + decimals: asset.decimals, + symbol: asset.symbol, + metadata: asset.metadata.into(), + }; + + ( + input, + *HelperMapper::to_uuid(asset.id) + .expect("Invalid UUID") + .as_bytes(), + ) + }) + .collect::>(); + + for (new_asset, with_asset_id) in add_assets { + match ASSET_SERVICE.create(new_asset, Some(with_asset_id)) { + Err(ApiError { code, details, .. }) if &code == "ALREADY_EXISTS" => { + // asset already exists, can skip safely + print(format!( + "Asset already exists, skipping. Details: {:?}", + details.unwrap_or_default() + )); + } + Err(e) => Err(format!("Failed to add asset: {:?}", e))?, + Ok(_) => {} + } + } + + Ok(()) + } pub async fn init_upgrader( input: station_api::SystemUpgraderInput, @@ -790,6 +970,7 @@ mod tests { upgrader: station_api::SystemUpgraderInput::WasmModule(vec![]), fallback_controller: None, accounts: None, + assets: None, }) .await; diff --git a/core/station/impl/src/services/transfer.rs b/core/station/impl/src/services/transfer.rs index bf5896ce4..39d97b196 100644 --- a/core/station/impl/src/services/transfer.rs +++ b/core/station/impl/src/services/transfer.rs @@ -104,12 +104,15 @@ mod tests { use crate::{ core::{test_utils, validation::disable_mock_resource_validation}, models::{ - account_test_utils::mock_account, request_test_utils::mock_request, - transfer_test_utils::mock_transfer, user_test_utils::mock_user, Account, User, + account_test_utils::mock_account, asset_test_utils::mock_asset, permission::Allow, + request_test_utils::mock_request, transfer_test_utils::mock_transfer, + user_test_utils::mock_user, Account, Metadata, User, }, repositories::{ - ACCOUNT_REPOSITORY, REQUEST_REPOSITORY, TRANSFER_REPOSITORY, USER_REPOSITORY, + ACCOUNT_REPOSITORY, ASSET_REPOSITORY, REQUEST_REPOSITORY, TRANSFER_REPOSITORY, + USER_REPOSITORY, }, + services::ACCOUNT_SERVICE, }; use candid::Principal; @@ -121,7 +124,7 @@ mod tests { call_context: CallContext, } - fn setup() -> TestContext { + async fn setup() -> TestContext { test_utils::init_canister_system(); let call_context = CallContext::new(Principal::from_slice(&[9; 29])); @@ -130,9 +133,28 @@ mod tests { USER_REPOSITORY.insert(user.to_key(), user.clone()); + let asset = mock_asset(); + + ASSET_REPOSITORY.insert(asset.id, asset.clone()); + let account = mock_account(); - ACCOUNT_REPOSITORY.insert(account.to_key(), account.clone()); + ACCOUNT_SERVICE + .create_account( + crate::models::AddAccountOperationInput { + name: "foo".to_owned(), + assets: vec![asset.id], + metadata: Metadata::default(), + read_permission: Allow::default(), + configs_permission: Allow::default(), + transfer_permission: Allow::default(), + configs_request_policy: None, + transfer_request_policy: None, + }, + Some(account.id), + ) + .await + .expect("Failed to create account"); let mut request = mock_request(); request.id = [2; 16]; @@ -148,9 +170,9 @@ mod tests { } } - #[test] - fn add_transfer_successfully() { - let ctx = setup(); + #[tokio::test] + async fn add_transfer_successfully() { + let ctx = setup().await; disable_mock_resource_validation(); @@ -163,9 +185,9 @@ mod tests { assert!(result.is_ok()); } - #[test] - fn fail_add_transfer_missing_initiator_user() { - let ctx = setup(); + #[tokio::test] + async fn fail_add_transfer_missing_initiator_user() { + let ctx = setup().await; disable_mock_resource_validation(); @@ -185,9 +207,9 @@ mod tests { ); } - #[test] - fn fail_add_transfer_missing_from_account() { - let ctx = setup(); + #[tokio::test] + async fn fail_add_transfer_missing_from_account() { + let ctx = setup().await; disable_mock_resource_validation(); @@ -206,9 +228,9 @@ mod tests { ); } - #[test] - fn fail_add_transfer_missing_request_id() { - let ctx = setup(); + #[tokio::test] + async fn fail_add_transfer_missing_request_id() { + let ctx = setup().await; disable_mock_resource_validation(); @@ -226,9 +248,9 @@ mod tests { ); } - #[test] - fn get_transfer() { - let ctx = setup(); + #[tokio::test] + async fn get_transfer() { + let ctx = setup().await; let mut transfer = mock_transfer(); transfer.from_account = ctx.account.id; transfer.initiator_user = ctx.caller_user.id; @@ -240,9 +262,9 @@ mod tests { assert!(result.is_ok()); } - #[test] - fn fail_get_transfer_not_allowed() { - let ctx = setup(); + #[tokio::test] + async fn fail_get_transfer_not_allowed() { + let ctx = setup().await; let mut user = mock_user(); user.identities = vec![Principal::from_slice(&[10; 29])]; diff --git a/core/upgrader/api/spec.did b/core/upgrader/api/spec.did index d66a786b5..e8f087033 100644 --- a/core/upgrader/api/spec.did +++ b/core/upgrader/api/spec.did @@ -39,7 +39,18 @@ type TriggerUpgradeError = variant { // Metadata for an account in the station canister. type Metadata = record { key : text; value : text }; -// Backup of Account in the station canister. +// Backup of Asset in the station canister. +type Asset = record { + id : text; + name : text; + symbol : text; + decimals : nat32; + blockchain : text; + standards : vec text; + metadata : vec Metadata; +}; + +// Backup of a legacy Account in the station canister. type Account = record { id : text; decimals : nat32; @@ -51,6 +62,15 @@ type Account = record { symbol : text; }; +// Backup of a multi asset Account in the station canister. +type MultiAssetAccount = record { + id : text; + name : text; + seed : blob; + assets : vec text; + metadata : vec Metadata; +}; + // Backup of admin user in the station canister. type AdminUser = record { id : text; name : text; identities : vec principal }; @@ -92,12 +112,24 @@ type GetDisasterRecoveryAccountsResponse = record { accounts : vec Account; }; +// Response to a successful get_disaster_recovery_accounts_and_assets query. +type GetDisasterRecoveryAccountsAndAssetsResponse = record { + accounts : vec MultiAssetAccount; + assets : vec Asset; +}; + // Result of the get_disaster_recovery_accounts query. type GetDisasterRecoveryAccountsResult = variant { Ok : GetDisasterRecoveryAccountsResponse; Err : Error; }; +// Result of the get_disaster_recovery_accounts_and_assets query. +type GetDisasterRecoveryAccountsAndAssetsResult = variant { + Ok : GetDisasterRecoveryAccountsAndAssetsResponse; + Err : Error; +}; + // Response to a successful get_disaster_recovery_committee query. type GetDisasterRecoveryCommitteeResponse = record { committee : opt DisasterRecoveryCommittee; @@ -121,6 +153,13 @@ type SetDisasterRecoveryAccountsInput = record { accounts : vec Account; }; +// Set the disaster recovery accounts and assets. Called by the station canister +// when accounts are added. +type SetDisasterRecoveryAccountsAndAssetsInput = record { + accounts : vec MultiAssetAccount; + assets : vec Asset; +}; + // Request to trigger disaster recovery. Requests are stored in the Upgrader // canister, and when at least `quorum` of the committee members // agree on the exact module, args, and install mode, the request is processed. @@ -224,8 +263,12 @@ type RecoveryResult = variant { type GetDisasterRecoveryStateResponse = record { // The disaster recovery committee. committee : opt DisasterRecoveryCommittee; - // The backup of the station accounts. + // The backup of the legacy station accounts. accounts : vec Account; + // The backup of the station multi asset accounts. + multi_asset_accounts : vec MultiAssetAccount; + // The backup of the station assets. + assets : vec Asset; // The current list of recovery requests. recovery_requests : vec StationRecoveryRequest; // The current recovery status. @@ -245,10 +288,13 @@ service : (InitArg) -> { "trigger_upgrade" : (UpgradeParams) -> (TriggerUpgradeResponse); "set_disaster_recovery_committee" : (SetDisasterRecoveryCommitteeInput) -> (SetDisasterRecoveryResult); "set_disaster_recovery_accounts" : (SetDisasterRecoveryAccountsInput) -> (SetDisasterRecoveryResult); + "set_disaster_recovery_accounts_and_assets" : (SetDisasterRecoveryAccountsAndAssetsInput) -> (SetDisasterRecoveryResult); "is_committee_member" : () -> (IsCommitteeMemberResult) query; "get_disaster_recovery_accounts" : () -> (GetDisasterRecoveryAccountsResult) query; + "get_disaster_recovery_accounts_and_assets" : () -> (GetDisasterRecoveryAccountsAndAssetsResult) query; "get_disaster_recovery_committee" : () -> (GetDisasterRecoveryCommitteeResult) query; "get_disaster_recovery_state" : () -> (GetDisasterRecoveryStateResult) query; "request_disaster_recovery" : (RequestDisasterRecoveryInput) -> (RequestDisasterRecoveryResult); "get_logs" : (GetLogsInput) -> (GetLogsResult) query; + "deprecated_get_logs" : (GetLogsInput) -> (GetLogsResult) query; }; diff --git a/core/upgrader/api/src/lib.rs b/core/upgrader/api/src/lib.rs index 7874f3d2a..ef42fecb3 100644 --- a/core/upgrader/api/src/lib.rs +++ b/core/upgrader/api/src/lib.rs @@ -1,5 +1,6 @@ use candid::{CandidType, Deserialize, Principal}; use orbit_essentials::types::WasmModuleExtraChunks; +use station_api::AccountSeedDTO; use station_api::TimestampRfc3339; pub use station_api::{MetadataDTO, UuidDTO}; @@ -64,6 +65,43 @@ pub struct Account { pub metadata: Vec, } +#[derive(Clone, Debug, CandidType, Deserialize, PartialEq, Eq)] +pub struct Asset { + /// The asset id, which is a UUID. + pub id: UuidDTO, + /// The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) + pub name: String, + /// The asset symbol (e.g. `ICP`, `BTC`, `ETH`, etc.) + pub symbol: String, + /// The number of decimal places that the asset supports (e.g. `8` for `BTC`, `18` for `ETH`, etc.) + pub decimals: u32, + /// The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + pub blockchain: String, + // The asset standard that is supported (e.g. `erc20`, `native`, etc.), canonically + // represented as a lowercase string with spaces replaced with underscores. + pub standards: Vec, + /// The account metadata, which is a list of key-value pairs, + /// where the key is unique and the first entry in the tuple, + /// and the value is the second entry in the tuple. + pub metadata: Vec, +} + +#[derive(Clone, Debug, CandidType, Deserialize, PartialEq, Eq)] +pub struct MultiAssetAccount { + /// The account id, which is a UUID. + pub id: UuidDTO, + /// The seed for address generation. + pub seed: AccountSeedDTO, + /// The account name. + pub name: String, + /// The account assets. + pub assets: Vec, + /// The account metadata, which is a list of key-value pairs, + /// where the key is unique and the first entry in the tuple, + /// and the value is the second entry in the tuple. + pub metadata: Vec, +} + #[derive(Clone, Debug, CandidType)] pub enum DisasterRecoveryError { Unauthorized, @@ -79,6 +117,12 @@ pub struct GetDisasterRecoveryAccountsResponse { pub accounts: Vec, } +#[derive(Clone, Debug, CandidType, Deserialize)] +pub struct GetDisasterRecoveryAccountsAndAssetsResponse { + pub accounts: Vec, + pub assets: Vec, +} + #[derive(Clone, Debug, CandidType, Deserialize)] pub struct GetDisasterRecoveryCommitteeResponse { pub committee: Option, @@ -94,6 +138,12 @@ pub struct SetDisasterRecoveryAccountsInput { pub accounts: Vec, } +#[derive(Clone, Debug, CandidType, Deserialize)] +pub struct SetDisasterRecoveryAccountsAndAssetsInput { + pub accounts: Vec, + pub assets: Vec, +} + #[derive(Clone, Debug, CandidType, Deserialize)] pub enum InstallMode { /// Install the module. @@ -188,6 +238,9 @@ pub struct GetDisasterRecoveryStateResponse { pub committee: Option, pub accounts: Vec, + pub multi_asset_accounts: Vec, + pub assets: Vec, + pub recovery_requests: Vec, pub recovery_status: RecoveryStatus, pub last_recovery_result: Option, diff --git a/core/upgrader/impl/src/controllers/disaster_recovery.rs b/core/upgrader/impl/src/controllers/disaster_recovery.rs index 4ac7a18f1..7545c9a0a 100644 --- a/core/upgrader/impl/src/controllers/disaster_recovery.rs +++ b/core/upgrader/impl/src/controllers/disaster_recovery.rs @@ -31,6 +31,13 @@ fn set_disaster_recovery_accounts( CONTROLLER.set_disaster_recovery_accounts(input) } +#[update] +fn set_disaster_recovery_accounts_and_assets( + input: upgrader_api::SetDisasterRecoveryAccountsAndAssetsInput, +) -> ApiResult { + CONTROLLER.set_disaster_recovery_accounts_and_assets(input) +} + #[update] fn request_disaster_recovery(input: upgrader_api::RequestDisasterRecoveryInput) -> ApiResult { CONTROLLER.request_disaster_recovery(input) @@ -47,6 +54,12 @@ fn get_disaster_recovery_accounts() -> ApiResult ApiResult { + CONTROLLER.get_disaster_recovery_accounts_and_assets() +} + #[query] fn get_disaster_recovery_committee() -> ApiResult { @@ -70,24 +83,38 @@ impl DisasterRecoveryController { let caller = caller(); if !is_controller(&caller) { Err(UpgraderApiError::NotController)? - } else { - self.disaster_recovery_service - .set_committee(input.committee.into()) } + + self.disaster_recovery_service + .set_committee(input.committee.into()) } fn set_disaster_recovery_accounts( &self, - input: upgrader_api::SetDisasterRecoveryAccountsInput, ) -> ApiResult { let caller = caller(); if !is_controller(&caller) { Err(UpgraderApiError::NotController)? - } else { - self.disaster_recovery_service - .set_accounts(input.accounts.into_iter().map(Into::into).collect()) } + + self.disaster_recovery_service + .set_accounts(input.accounts.into_iter().map(Into::into).collect()) + } + + fn set_disaster_recovery_accounts_and_assets( + &self, + input: upgrader_api::SetDisasterRecoveryAccountsAndAssetsInput, + ) -> ApiResult { + let caller = caller(); + if !is_controller(&caller) { + Err(UpgraderApiError::NotController)? + } + + self.disaster_recovery_service.set_accounts_and_assets( + input.accounts.into_iter().map(Into::into).collect(), + input.assets.into_iter().map(Into::into).collect(), + ) } fn request_disaster_recovery( @@ -98,14 +125,13 @@ impl DisasterRecoveryController { let caller = caller(); if !self.disaster_recovery_service.is_committee_member(&caller) { Err(UpgraderApiError::Unauthorized)? - } else { - self.disaster_recovery_service - .request_recovery(caller, input); + } - self.disaster_recovery_service.check_requests(); + self.disaster_recovery_service + .request_recovery(caller, input); + self.disaster_recovery_service.check_requests(); - Ok(()) - } + Ok(()) } fn is_committee_member(&self) -> ApiResult { @@ -113,11 +139,11 @@ impl DisasterRecoveryController { if caller == Principal::anonymous() { Err(UpgraderApiError::Unauthorized)? - } else { - Ok(upgrader_api::IsCommitteeMemberResponse { - is_committee_member: self.disaster_recovery_service.is_committee_member(&caller), - }) } + + Ok(upgrader_api::IsCommitteeMemberResponse { + is_committee_member: self.disaster_recovery_service.is_committee_member(&caller), + }) } fn can_query_state(&self, caller: &Principal) -> bool { @@ -128,18 +154,43 @@ impl DisasterRecoveryController { &self, ) -> ApiResult { let caller = caller(); + if !self.can_query_state(&caller) { Err(UpgraderApiError::Unauthorized)? - } else { - Ok(upgrader_api::GetDisasterRecoveryAccountsResponse { - accounts: self - .disaster_recovery_service - .get_accounts() - .into_iter() - .map(Into::into) - .collect(), - }) } + + Ok(upgrader_api::GetDisasterRecoveryAccountsResponse { + accounts: self + .disaster_recovery_service + .get_accounts() + .into_iter() + .map(Into::into) + .collect(), + }) + } + + fn get_disaster_recovery_accounts_and_assets( + &self, + ) -> ApiResult { + let caller = caller(); + if !is_controller(&caller) { + Err(UpgraderApiError::NotController)? + } + + Ok(upgrader_api::GetDisasterRecoveryAccountsAndAssetsResponse { + accounts: self + .disaster_recovery_service + .get_multi_asset_accounts() + .into_iter() + .map(Into::into) + .collect(), + assets: self + .disaster_recovery_service + .get_assets() + .into_iter() + .map(Into::into) + .collect(), + }) } fn get_disaster_recovery_committee( @@ -148,14 +199,14 @@ impl DisasterRecoveryController { let caller = caller(); if !self.can_query_state(&caller) { Err(UpgraderApiError::Unauthorized)? - } else { - Ok(upgrader_api::GetDisasterRecoveryCommitteeResponse { - committee: self - .disaster_recovery_service - .get_committee() - .map(Into::into), - }) } + + Ok(upgrader_api::GetDisasterRecoveryCommitteeResponse { + committee: self + .disaster_recovery_service + .get_committee() + .map(Into::into), + }) } fn get_disaster_recovery_state( @@ -164,9 +215,9 @@ impl DisasterRecoveryController { let caller = caller(); if !self.can_query_state(&caller) { Err(UpgraderApiError::Unauthorized)? - } else { - Ok(self.disaster_recovery_service.get_state().into()) } + + Ok(self.disaster_recovery_service.get_state().into()) } } diff --git a/core/upgrader/impl/src/controllers/logs.rs b/core/upgrader/impl/src/controllers/logs.rs index 6e55bc133..962f01c2a 100644 --- a/core/upgrader/impl/src/controllers/logs.rs +++ b/core/upgrader/impl/src/controllers/logs.rs @@ -28,6 +28,13 @@ fn get_logs(input: upgrader_api::GetLogsInput) -> ApiResult ApiResult { + CONTROLLER.deprecated_get_logs(input) +} + pub struct LogsController { disaster_recover_service: Arc, logger_service: Arc, @@ -59,4 +66,31 @@ impl LogsController { Err(UpgraderApiError::Unauthorized.into()) } } + + // Supports fetching the logs from the deprecated log storage. + pub fn deprecated_get_logs( + &self, + input: upgrader_api::GetLogsInput, + ) -> ApiResult { + let caller = caller(); + + if is_controller(&caller) || self.disaster_recover_service.is_committee_member(&caller) { + let GetLogsResult { + logs, + next_offset, + total, + } = self.logger_service.deprecated_get_logs( + input.pagination.as_ref().and_then(|p| p.offset), + input.pagination.as_ref().and_then(|p| p.limit), + ); + + Ok(upgrader_api::GetLogsResponse { + logs: logs.into_iter().map(|l| l.into()).collect(), + total, + next_offset, + }) + } else { + Err(UpgraderApiError::Unauthorized.into()) + } + } } diff --git a/core/upgrader/impl/src/errors/mod.rs b/core/upgrader/impl/src/errors/mod.rs index bfcfbb40c..101129711 100644 --- a/core/upgrader/impl/src/errors/mod.rs +++ b/core/upgrader/impl/src/errors/mod.rs @@ -4,6 +4,7 @@ pub enum UpgraderApiError { NotController, Unauthorized, DisasterRecoveryInProgress, + EmptyCommittee, } impl From for ApiError { @@ -24,6 +25,11 @@ impl From for ApiError { message: Some("Disaster recovery is in progress.".to_owned()), details: None, }, + UpgraderApiError::EmptyCommittee => ApiError { + code: "EMPTY_COMMITTEE".to_owned(), + message: Some("Committee cannot be empty.".to_owned()), + details: None, + }, } } } diff --git a/core/upgrader/impl/src/lib.rs b/core/upgrader/impl/src/lib.rs index b6c7379d5..4f3ea2a15 100644 --- a/core/upgrader/impl/src/lib.rs +++ b/core/upgrader/impl/src/lib.rs @@ -33,8 +33,9 @@ type LocalRef = &'static LocalKey>; const MEMORY_ID_TARGET_CANISTER_ID: u8 = 0; const MEMORY_ID_DISASTER_RECOVERY: u8 = 1; -const MEMORY_ID_LOG_INDEX: u8 = 2; -const MEMORY_ID_LOG_DATA: u8 = 3; +const DEPRECATED_MEMORY_ID_LOG_INDEX: u8 = 2; +const DEPRECATED_MEMORY_ID_LOG_DATA: u8 = 3; +const MEMORY_ID_LOGS: u8 = 4; thread_local! { static MEMORY_MANAGER: RefCell> = diff --git a/core/upgrader/impl/src/model/disaster_recovery.rs b/core/upgrader/impl/src/model/disaster_recovery.rs index efab159e6..63cb96f42 100644 --- a/core/upgrader/impl/src/model/disaster_recovery.rs +++ b/core/upgrader/impl/src/model/disaster_recovery.rs @@ -246,6 +246,62 @@ impl From for upgrader_api::AdminUser { } } +#[storable] +#[derive(Clone, Debug)] +pub struct Asset { + /// The asset id, which is a UUID. + pub id: UUID, + /// The asset name (e.g. `Internet Computer`, `Bitcoin`, `Ethereum`, etc.) + pub name: String, + /// The asset symbol (e.g. `ICP`, `BTC`, `ETH`, etc.) + pub symbol: String, + /// The number of decimal places that the asset supports (e.g. `8` for `BTC`, `18` for `ETH`, etc.) + pub decimals: u32, + /// The blockchain identifier (e.g., `ethereum`, `bitcoin`, `icp`, etc.) + pub blockchain: String, + // The asset standard that is supported (e.g. `erc20`, `native`, etc.), canonically + // represented as a lowercase string with spaces replaced with underscores. + pub standards: Vec, + /// The account metadata, which is a list of key-value pairs, + /// where the key is unique and the first entry in the tuple, + /// and the value is the second entry in the tuple. + pub metadata: Vec, +} + +impl From for Asset { + fn from(value: upgrader_api::Asset) -> Self { + Asset { + id: *HelperMapper::to_uuid(value.id) + .expect("Invalid asset ID") + .as_bytes(), + name: value.name, + symbol: value.symbol, + decimals: value.decimals, + blockchain: value.blockchain, + standards: value.standards, + metadata: value.metadata.into_iter().map(Metadata::from).collect(), + } + } +} + +impl From for upgrader_api::Asset { + fn from(value: Asset) -> Self { + upgrader_api::Asset { + id: Uuid::from_bytes(value.id).hyphenated().to_string(), + name: value.name, + symbol: value.symbol, + decimals: value.decimals, + blockchain: value.blockchain, + standards: value.standards, + metadata: value + .metadata + .into_iter() + .map(upgrader_api::MetadataDTO::from) + .collect(), + } + } +} + #[storable] #[derive(Clone, Debug)] pub struct Account { @@ -269,6 +325,24 @@ pub struct Account { pub metadata: Vec, } +type AccountSeed = [u8; 16]; +#[storable] +#[derive(Clone, Debug)] +pub struct MultiAssetAccount { + /// The account id, which is a UUID. + pub id: UUID, + /// The blockchain type (e.g. `icp`, `eth`, `btc`) + pub name: String, + /// The address generation seed. + pub seed: AccountSeed, + /// Assets + pub assets: Vec, + /// The account metadata, which is a list of key-value pairs, + /// where the key is unique and the first entry in the tuple, + /// and the value is the second entry in the tuple. + pub metadata: Vec, +} + impl From for Account { fn from(value: upgrader_api::Account) -> Self { Account { @@ -305,10 +379,58 @@ impl From for upgrader_api::Account { } } +impl From for MultiAssetAccount { + fn from(value: upgrader_api::MultiAssetAccount) -> Self { + MultiAssetAccount { + id: *HelperMapper::to_uuid(value.id) + .expect("Invalid account ID") + .as_bytes(), + assets: value + .assets + .into_iter() + .map(|asset_id| { + *HelperMapper::to_uuid(asset_id) + .expect("Invalid asset ID") + .as_bytes() + }) + .collect(), + seed: value.seed, + name: value.name, + metadata: value.metadata.into_iter().map(Metadata::from).collect(), + } + } +} + +impl From for upgrader_api::MultiAssetAccount { + fn from(value: MultiAssetAccount) -> Self { + upgrader_api::MultiAssetAccount { + id: Uuid::from_bytes(value.id).hyphenated().to_string(), + name: value.name, + seed: value.seed, + assets: value + .assets + .into_iter() + .map(|asset_id| Uuid::from_bytes(asset_id).hyphenated().to_string()) + .collect(), + metadata: value + .metadata + .into_iter() + .map(upgrader_api::MetadataDTO::from) + .collect(), + } + } +} + #[storable] #[derive(Clone, Debug)] pub struct DisasterRecovery { pub accounts: Vec, + + #[serde(default)] + pub multi_asset_accounts: Vec, + #[serde(default)] + pub assets: Vec, + pub committee: Option, pub recovery_requests: Vec, @@ -320,6 +442,8 @@ impl Default for DisasterRecovery { fn default() -> Self { DisasterRecovery { accounts: vec![], + multi_asset_accounts: vec![], + assets: vec![], committee: None, recovery_requests: vec![], recovery_status: RecoveryStatus::Idle, @@ -336,6 +460,18 @@ impl From for upgrader_api::GetDisasterRecoveryStateResponse { .into_iter() .map(upgrader_api::Account::from) .collect(), + + multi_asset_accounts: value + .multi_asset_accounts + .into_iter() + .map(upgrader_api::MultiAssetAccount::from) + .collect(), + assets: value + .assets + .into_iter() + .map(upgrader_api::Asset::from) + .collect(), + committee: value .committee .map(upgrader_api::DisasterRecoveryCommittee::from), @@ -354,6 +490,8 @@ impl From for upgrader_api::GetDisasterRecoveryStateResponse { pub mod tests { use candid::Principal; + use crate::model::{Asset, MultiAssetAccount}; + use super::{Account, AdminUser, DisasterRecoveryCommittee}; pub fn mock_committee_member() -> Principal { @@ -411,4 +549,46 @@ pub mod tests { }, ] } + + pub fn mock_multi_asset_accounts() -> Vec { + vec![ + MultiAssetAccount { + id: [1; 16], + assets: vec![[1; 16], [2; 16]], + seed: [0; 16], + name: "Main Account".to_owned(), + metadata: vec![], + }, + MultiAssetAccount { + id: [2; 16], + assets: vec![[1; 16]], + seed: [0; 16], + name: "Secondary Account".to_owned(), + metadata: vec![], + }, + ] + } + + pub fn mock_assets() -> Vec { + vec![ + Asset { + id: [1; 16], + name: "Internet Computer".to_owned(), + symbol: "ICP".to_owned(), + decimals: 8, + blockchain: "icp".to_owned(), + standards: vec!["icp_native".to_owned()], + metadata: vec![], + }, + Asset { + id: [2; 16], + name: "Ethereum".to_owned(), + symbol: "ETH".to_owned(), + decimals: 18, + blockchain: "eth".to_owned(), + standards: vec!["erc20".to_owned()], + metadata: vec![], + }, + ] + } } diff --git a/core/upgrader/impl/src/model/logging.rs b/core/upgrader/impl/src/model/logging.rs index 617df02ac..6ce78bbb5 100644 --- a/core/upgrader/impl/src/model/logging.rs +++ b/core/upgrader/impl/src/model/logging.rs @@ -1,8 +1,10 @@ -use crate::upgrader_ic_cdk::api::time; +use crate::upgrader_ic_cdk::next_time; use orbit_essentials::{storable, types::Timestamp, utils::timestamp_to_rfc3339}; use serde::Serialize; -use super::{Account, AdminUser, DisasterRecoveryCommittee, RecoveryResult}; +use super::{ + Account, AdminUser, Asset, DisasterRecoveryCommittee, MultiAssetAccount, RecoveryResult, +}; #[derive(Serialize)] pub enum UpgradeResultLog { @@ -20,6 +22,12 @@ pub struct SetAccountsLog { pub accounts: Vec, } +#[derive(Serialize)] +pub struct SetAccountsAndAssetsLog { + pub multi_asset_accounts: Vec, + pub assets: Vec, +} + #[derive(Serialize)] pub struct RequestDisasterRecoveryLog { pub user: AdminUser, @@ -48,6 +56,7 @@ pub struct DisasterRecoveryInProgressLog { pub enum LogEntryType { SetCommittee(SetCommitteeLog), SetAccounts(SetAccountsLog), + SetAccountsAndAssets(SetAccountsAndAssetsLog), RequestDisasterRecovery(RequestDisasterRecoveryLog), DisasterRecoveryStart(DisasterRecoveryStartLog), DisasterRecoveryResult(DisasterRecoveryResultLog), @@ -80,6 +89,7 @@ impl LogEntryType { LogEntryType::DisasterRecoveryInProgressExpired(_) => { "disaster_recovery_in_progress_expired".to_owned() } + LogEntryType::SetAccountsAndAssets(_) => "set_accounts_and_assets".to_owned(), } } @@ -96,7 +106,7 @@ impl LogEntryType { data.committee.quorum ), LogEntryType::SetAccounts(data) => { - format!("Set {} disaster recovery account(s)", data.accounts.len()) + format!("Set {} disaster recovery account(s)", data.accounts.len(),) } LogEntryType::RequestDisasterRecovery(data) => format!( "{} requested disaster recovery with wasm hash {} and arg hash {}", @@ -132,6 +142,13 @@ impl LogEntryType { data.operation ) } + LogEntryType::SetAccountsAndAssets(data) => { + format!( + "Set {} multi-asset account(s) and {} asset(s)", + data.multi_asset_accounts.len(), + data.assets.len() + ) + } } } @@ -145,6 +162,7 @@ impl LogEntryType { LogEntryType::UpgradeResult(data) => serde_json::to_string(data), LogEntryType::DisasterRecoveryInProgress(data) => serde_json::to_string(data), LogEntryType::DisasterRecoveryInProgressExpired(data) => serde_json::to_string(data), + LogEntryType::SetAccountsAndAssets(data) => serde_json::to_string(data), } .map_err(|err| format!("Failed to serialize log entry: {}", err)) } @@ -153,7 +171,7 @@ impl LogEntryType { impl LogEntry { pub fn try_from_entry_type(entry_type: LogEntryType) -> Result { Ok(LogEntry { - time: time(), + time: next_time(), entry_type: entry_type.to_type_string(), message: entry_type.to_message(), data_json: entry_type.to_json_string()?, diff --git a/core/upgrader/impl/src/services/disaster_recovery.rs b/core/upgrader/impl/src/services/disaster_recovery.rs index 66a610ba3..44d5ef46d 100644 --- a/core/upgrader/impl/src/services/disaster_recovery.rs +++ b/core/upgrader/impl/src/services/disaster_recovery.rs @@ -3,8 +3,9 @@ use std::{cell::RefCell, collections::HashMap, sync::Arc}; use crate::{ errors::UpgraderApiError, model::{ - DisasterRecoveryInProgressLog, DisasterRecoveryResultLog, DisasterRecoveryStartLog, - LogEntryType, RequestDisasterRecoveryLog, SetAccountsLog, SetCommitteeLog, + Asset, DisasterRecoveryInProgressLog, DisasterRecoveryResultLog, DisasterRecoveryStartLog, + LogEntryType, MultiAssetAccount, RequestDisasterRecoveryLog, SetAccountsAndAssetsLog, + SetAccountsLog, SetCommitteeLog, }, services::LOGGER_SERVICE, upgrader_ic_cdk::{api::time, spawn}, @@ -98,24 +99,37 @@ pub struct DisasterRecoveryService { } impl DisasterRecoveryService { - pub fn set_committee(&self, committee: DisasterRecoveryCommittee) -> ServiceResult { - let mut value = self.storage.get(); - + fn ensure_not_in_progress( + logger: &Arc, + value: &mut DisasterRecovery, + operation: &str, + ) -> ServiceResult { if let RecoveryStatus::InProgress { since } = &value.recovery_status { let log = DisasterRecoveryInProgressLog { - operation: "set_committee".to_owned(), + operation: operation.to_owned(), }; if since + DISASTER_RECOVERY_IN_PROGESS_EXPIRATION_NS > time() { - self.logger - .log(LogEntryType::DisasterRecoveryInProgress(log)); + logger.log(LogEntryType::DisasterRecoveryInProgress(log)); return Err(UpgraderApiError::DisasterRecoveryInProgress.into()); } - self.logger - .log(LogEntryType::DisasterRecoveryInProgressExpired(log)); + logger.log(LogEntryType::DisasterRecoveryInProgressExpired(log)); value.recovery_status = RecoveryStatus::Idle; } + Ok(()) + } + + pub fn set_committee(&self, committee: DisasterRecoveryCommittee) -> ServiceResult { + let mut value = self.storage.get(); + + Self::ensure_not_in_progress(&self.logger, &mut value, "set_committee")?; + + // Ensure committee is not empty due to some error + if committee.users.is_empty() { + return Err(UpgraderApiError::EmptyCommittee.into()); + } + value.committee = Some(committee.clone()); self.storage.set(value); @@ -129,22 +143,10 @@ impl DisasterRecoveryService { pub fn set_accounts(&self, accounts: Vec) -> ServiceResult { let mut value = self.storage.get(); - if let RecoveryStatus::InProgress { since } = &value.recovery_status { - let log = DisasterRecoveryInProgressLog { - operation: "set_accounts".to_owned(), - }; - if since + DISASTER_RECOVERY_IN_PROGESS_EXPIRATION_NS > time() { - self.logger - .log(LogEntryType::DisasterRecoveryInProgress(log)); - return Err(UpgraderApiError::DisasterRecoveryInProgress.into()); - } - - self.logger - .log(LogEntryType::DisasterRecoveryInProgressExpired(log)); - value.recovery_status = RecoveryStatus::Idle; - } + Self::ensure_not_in_progress(&self.logger, &mut value, "set_accounts")?; value.accounts = accounts.clone(); + self.storage.set(value); self.logger @@ -153,10 +155,42 @@ impl DisasterRecoveryService { Ok(()) } + pub fn set_accounts_and_assets( + &self, + multi_asset_accounts: Vec, + assets: Vec, + ) -> ServiceResult { + let mut value = self.storage.get(); + + Self::ensure_not_in_progress(&self.logger, &mut value, "set_accounts_and_assets")?; + + value.multi_asset_accounts = multi_asset_accounts.clone(); + value.assets = assets.clone(); + + self.storage.set(value); + + self.logger.log(LogEntryType::SetAccountsAndAssets( + SetAccountsAndAssetsLog { + multi_asset_accounts, + assets, + }, + )); + + Ok(()) + } + pub fn get_accounts(&self) -> Vec { self.storage.get().accounts } + pub fn get_multi_asset_accounts(&self) -> Vec { + self.storage.get().multi_asset_accounts + } + + pub fn get_assets(&self) -> Vec { + self.storage.get().assets + } + pub fn get_committee(&self) -> Option { self.storage.get().committee } @@ -244,18 +278,8 @@ impl DisasterRecoveryService { }, )); - if let RecoveryStatus::InProgress { since } = &value.recovery_status { - let log = DisasterRecoveryInProgressLog { - operation: "do_recovery".to_owned(), - }; - - if since + DISASTER_RECOVERY_IN_PROGESS_EXPIRATION_NS > time() { - logger.log(LogEntryType::DisasterRecoveryInProgress(log)); - return; - } - - logger.log(LogEntryType::DisasterRecoveryInProgressExpired(log)); - value.recovery_status = RecoveryStatus::Idle; + if Self::ensure_not_in_progress(&logger, &mut value, "do_recovery").is_err() { + return; } let Some(station_canister_id) = @@ -384,7 +408,7 @@ mod tests { use crate::{ model::{ - tests::{mock_accounts, mock_committee}, + tests::{mock_accounts, mock_assets, mock_committee, mock_multi_asset_accounts}, InstallMode, RecoveryEvaluationResult, RecoveryResult, RecoveryStatus, StationRecoveryRequest, }, @@ -748,8 +772,20 @@ mod tests { }; storage.set(value); + let error = DISASTER_RECOVERY_SERVICE + .set_accounts_and_assets(mock_multi_asset_accounts(), mock_assets()) + .expect_err("Setting accounts and assets during recovery should fail"); + + assert_eq!(error.code, "DISASTER_RECOVERY_IN_PROGRESS".to_string(),); + let error = DISASTER_RECOVERY_SERVICE .set_accounts(mock_accounts()) + .expect_err("Setting accounts during recovery should fail"); + + assert_eq!(error.code, "DISASTER_RECOVERY_IN_PROGRESS".to_string(),); + + let error = DISASTER_RECOVERY_SERVICE + .set_committee(mock_committee()) .expect_err("Setting committee during recovery should fail"); assert_eq!(error.code, "DISASTER_RECOVERY_IN_PROGRESS".to_string(),); diff --git a/core/upgrader/impl/src/services/logger.rs b/core/upgrader/impl/src/services/logger.rs index a32fe0419..0ec46e613 100644 --- a/core/upgrader/impl/src/services/logger.rs +++ b/core/upgrader/impl/src/services/logger.rs @@ -1,25 +1,32 @@ use std::{cell::RefCell, sync::Arc}; -use ic_stable_structures::{memory_manager::MemoryId, Log}; +use ic_stable_structures::{memory_manager::MemoryId, BTreeMap, Log}; use lazy_static::lazy_static; +use orbit_essentials::types::Timestamp; use crate::{ model::{LogEntry, LogEntryType}, - Memory, MEMORY_ID_LOG_DATA, MEMORY_ID_LOG_INDEX, MEMORY_MANAGER, + Memory, DEPRECATED_MEMORY_ID_LOG_DATA, DEPRECATED_MEMORY_ID_LOG_INDEX, MEMORY_ID_LOGS, + MEMORY_MANAGER, }; pub const MAX_GET_LOGS_LIMIT: u64 = 100; pub const DEFAULT_GET_LOGS_LIMIT: u64 = 10; +pub const MAX_LOG_ENTRIES: u64 = 25000; thread_local! { - - static STORAGE: RefCell> = RefCell::new( - Log::init( - MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(MEMORY_ID_LOG_INDEX))), - MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(MEMORY_ID_LOG_DATA))), - ).expect("Failed to initialize log storage") - ); - + static DEPRECATED_STORAGE: RefCell> = RefCell::new( + Log::init( + MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(DEPRECATED_MEMORY_ID_LOG_INDEX))), + MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(DEPRECATED_MEMORY_ID_LOG_DATA))), + ).expect("Failed to initialize deprecated log storage") + ); + + static STORAGE: RefCell> = RefCell::new( + BTreeMap::init( + MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(MEMORY_ID_LOGS))), + ) + ); } lazy_static! { @@ -40,12 +47,12 @@ impl LoggerService { /// Tries to log an entry to the storage. pub fn try_log(&self, entry_type: LogEntryType) -> Result<(), String> { let entry = LogEntry::try_from_entry_type(entry_type)?; - STORAGE.with(|storage| { - storage - .borrow_mut() - .append(&entry) - .map_err(|err| format!("Failed to log entry: {:?}", err)) - })?; + STORAGE.with_borrow_mut(|storage| { + if storage.len() >= MAX_LOG_ENTRIES { + let _ = storage.pop_first(); + } + storage.insert(entry.time, entry); + }); Ok(()) } @@ -71,6 +78,47 @@ impl LoggerService { }; } + let offset = offset.unwrap_or(0); + let limit = limit + .unwrap_or(DEFAULT_GET_LOGS_LIMIT) + .min(MAX_GET_LOGS_LIMIT); + + let logs = borrowed + .iter() + .rev() + .skip(offset as usize) + .take(limit as usize) + .map(|(_, v)| v) + .collect::>(); + + let next_offset = if total > offset + limit { + Some(offset + limit) + } else { + None + }; + GetLogsResult { + logs, + total, + next_offset, + } + }) + } + + /// Returns logs from the deprecated storage starting from the end of the log. + pub fn deprecated_get_logs(&self, offset: Option, limit: Option) -> GetLogsResult { + DEPRECATED_STORAGE.with(|storage| { + let borrowed = storage.borrow(); + + let total = borrowed.len(); + + if total == 0 { + return GetLogsResult { + logs: vec![], + total, + next_offset: None, + }; + } + let offset = offset.unwrap_or(0); let limit = limit .unwrap_or(DEFAULT_GET_LOGS_LIMIT) @@ -102,8 +150,8 @@ impl LoggerService { mod tests { use crate::model::{ - tests::{mock_accounts, mock_committee}, - DisasterRecoveryResultLog, RecoveryResult, SetAccountsLog, SetCommitteeLog, + tests::{mock_assets, mock_committee, mock_multi_asset_accounts}, + DisasterRecoveryResultLog, RecoveryResult, SetAccountsAndAssetsLog, SetCommitteeLog, UpgradeResultLog, }; @@ -121,15 +169,21 @@ mod tests { result: RecoveryResult::Success, }, )); - logger_service.log(LogEntryType::SetAccounts(SetAccountsLog { - accounts: mock_accounts(), - })); + logger_service.log(LogEntryType::SetAccountsAndAssets( + SetAccountsAndAssetsLog { + multi_asset_accounts: mock_multi_asset_accounts(), + assets: mock_assets(), + }, + )); let result = logger_service.get_logs(None, None); - println!("{:?}", result); + assert_eq!(result.logs.len(), 4); assert_eq!(result.total, 4); assert_eq!(result.logs[3].entry_type, "set_committee".to_owned()); - assert_eq!(result.logs[0].entry_type, "set_accounts".to_owned()); + assert_eq!( + result.logs[0].entry_type, + "set_accounts_and_assets".to_owned() + ); let result = logger_service.get_logs(Some(1), Some(2)); assert_eq!(result.logs.len(), 2); @@ -147,4 +201,43 @@ mod tests { assert_eq!(result.next_offset, None); assert_eq!(result.logs[0].entry_type, "set_committee".to_owned()); } + + #[test] + fn test_log_trimming() { + for _ in 0..MAX_LOG_ENTRIES { + LOGGER_SERVICE.log(LogEntryType::SetCommittee(SetCommitteeLog { + committee: mock_committee(), + })); + } + + let result = LOGGER_SERVICE.get_logs(None, None); + assert_eq!(result.total, MAX_LOG_ENTRIES); + + let latest_log_time = result.logs.last().unwrap().time; + + LOGGER_SERVICE.log(LogEntryType::SetCommittee(SetCommitteeLog { + committee: mock_committee(), + })); + + let result = LOGGER_SERVICE.get_logs(None, None); + + assert_eq!(result.total, MAX_LOG_ENTRIES); + assert_ne!(result.logs.last().unwrap().time, latest_log_time); + } + + #[test] + fn test_deprecated_storage() { + let logger_service = LoggerService::default(); + logger_service.log(LogEntryType::SetCommittee(SetCommitteeLog { + committee: mock_committee(), + })); + + // new logs should be in the new storage + let result = logger_service.get_logs(None, None); + assert_eq!(result.total, 1); + + // deprecated logs should not get new logs + let result = logger_service.deprecated_get_logs(None, None); + assert_eq!(result.total, 0); + } } diff --git a/dfx.json b/dfx.json index 97c5ff986..d8b9b663f 100644 --- a/dfx.json +++ b/dfx.json @@ -9,6 +9,10 @@ "id": { "ic": "ryjl3-tyaaa-aaaaa-aaaba-cai" } + }, + "declarations": { + "output": "apps/wallet/src/generated/icp_ledger", + "node_compatibility": true } }, "icp_index": { @@ -61,9 +65,29 @@ }, "app_wallet": { "type": "assets", - "source": ["apps/wallet/dist/"], + "source": [ + "apps/wallet/dist/" + ], "build": "pnpm --filter 'wallet-dapp' build" }, + "icrc1_index_canister": { + "type": "custom", + "candid": "https://raw.githubusercontent.com/dfinity/ic/d87954601e4b22972899e9957e800406a0a6b929/rs/rosetta-api/icrc1/index-ng/index-ng.did", + "wasm": "https://download.dfinity.systems/ic/d87954601e4b22972899e9957e800406a0a6b929/canisters/ic-icrc1-index-ng.wasm.gz", + "declarations": { + "output": "apps/wallet/src/generated/icrc1_index", + "node_compatibility": true + } + }, + "icrc1_ledger_canister": { + "type": "custom", + "candid": "https://raw.githubusercontent.com/dfinity/ic/d87954601e4b22972899e9957e800406a0a6b929/rs/rosetta-api/icrc1/ledger/ledger.did", + "wasm": "https://download.dfinity.systems/ic/d87954601e4b22972899e9957e800406a0a6b929/canisters/ic-icrc1-ledger.wasm.gz", + "declarations": { + "output": "apps/wallet/src/generated/icrc1_ledger", + "node_compatibility": true + } + }, "wasm_chunk_store": { "type": "assets", "source": [], @@ -78,28 +102,36 @@ }, "networks": { "production": { - "providers": ["https://icp0.io"], + "providers": [ + "https://icp0.io" + ], "type": "persistent", "replica": { "subnet_type": "application" } }, "staging": { - "providers": ["https://icp0.io"], + "providers": [ + "https://icp0.io" + ], "type": "persistent", "replica": { "subnet_type": "application" } }, "playground": { - "providers": ["https://icp0.io"], + "providers": [ + "https://icp0.io" + ], "type": "persistent", "replica": { "subnet_type": "application" } }, "testing": { - "providers": ["https://icp0.io"], + "providers": [ + "https://icp0.io" + ], "type": "persistent", "replica": { "subnet_type": "application" @@ -115,4 +147,4 @@ }, "dfx": "0.23.0", "version": 1 -} +} \ No newline at end of file diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 2a252ed74..f66245d13 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -131,21 +131,29 @@ Request Policy Approval is the process of approving a request. Users can add the Permissions are rules that define the functionality that a user can access in a station canister. Permissions are defined by the authorized station users and can be customized to fit the needs of different use cases. Permissions can be granted to individual users, groups of users or any (un)authenticated user and can be revoked at any time. +### Asset + +An Orbit Asset holds metadata about an asset on the blockchain. Besides typical properties like Name and Symbol, it also stores which blockchain the asset is on, what token standards it supports, the contract address(es), etc. Assets can be added/changed/removed through requests. The native ICP asset is added by default to new Orbit stations. + ### Account -An account is a record in the station canister that represents a user's ownership of a specific asset. Accounts can hold different types of assets, such as tokens, NFTs, or other fungible or non-fungible assets. Accounts can be created, updated, and archived by the station users through requests. +An account is a record in the station canister that represents a user's ownership of specific assets. Accounts can hold multiple types of assets, such as tokens, NFTs, or other fungible or non-fungible assets. Accounts can be created, updated, and archived by the station users through requests. #### Account Name An account name is a human-readable name that represents the account in the station canister. Account names can be customized by privileged users and are unique within the station canister. +#### Account Asset + +An account can hold multiple types of assets, on any supported blockchains, and any supported standards. Assets can be added and removed from accounts. Removing an asset does not result in losing funds, readding the asset restores access. + #### Account Address -An account address is a unique identifier that represents the account address in relation to the asset it holds. +An account address is a unique identifier that represents the account address in relation to the asset it holds. An account can have many addresses derived from the account seed, as assets support different token standards and address formats. #### Account Balance -An account balance is the amount of a specific asset that an account holds. Account balances are updated when assets are deposited or withdrawn from the account. +An account asset's balance is the amount of a specific asset that an account holds. Account balances are updated when assets are deposited or withdrawn from the account. ### Address Book diff --git a/libs/orbit-essentials/src/utils/lock.rs b/libs/orbit-essentials/src/utils/lock.rs index fe7c8ec3e..48b916775 100644 --- a/libs/orbit-essentials/src/utils/lock.rs +++ b/libs/orbit-essentials/src/utils/lock.rs @@ -1,19 +1,22 @@ use std::cell::RefCell; use std::cmp::Ord; -use std::collections::BTreeSet; +use std::collections::BTreeMap; use std::rc::Rc; -// The following code implementing canister locks is adapted from +use crate::cdk::api::time; +use std::fmt::Debug; + +// The following code implementing canister locks with optional expiration is adapted from // https://internetcomputer.org/docs/current/developer-docs/security/rust-canister-development-security-best-practices#recommendation-10 pub struct State { - pending_requests: BTreeSet, + pending_requests: BTreeMap>, } impl Default for State { fn default() -> Self { Self { - pending_requests: BTreeSet::new(), + pending_requests: BTreeMap::new(), } } } @@ -23,15 +26,27 @@ pub struct CallerGuard { lock: T, } -impl CallerGuard { - pub fn new(state: Rc>>, lock: T) -> Option { +impl CallerGuard { + pub fn new(state: Rc>>, lock: T, expires_at_ns: Option) -> Option { { let pending_requests = &mut state.borrow_mut().pending_requests; - if pending_requests.contains(&lock) { - return None; + if let Some(existing_request) = pending_requests.get(&lock) { + if let Some(expires_at_ns) = existing_request { + if expires_at_ns > &time() { + // Lock is already held by another caller and has not expired. + return None; + } else { + // Lock has expired, fall through to update the lock. + crate::cdk::api::print(format!("Lock has expired for {:?}", lock)); + } + } else { + // Lock is held indefinitely. + return None; + } } - pending_requests.insert(lock.clone()); + pending_requests.insert(lock.clone(), expires_at_ns); } + Some(Self { state, lock }) } } diff --git a/orbit b/orbit index 71b9829cc..f4b08cf6b 100755 --- a/orbit +++ b/orbit @@ -16,6 +16,8 @@ CANISTER_ID_ICP_LEDGER="ryjl3-tyaaa-aaaaa-aaaba-cai" CANISTER_ID_INTERNET_IDENTITY="rdmx6-jaaaa-aaaaa-aaadq-cai" CANISTER_ID_UI="werw6-ayaaa-aaaaa-774aa-cai" CANISTER_ID_WALLET="wkt3w-3iaaa-aaaaa-774ba-cai" +CANISTER_ID_TEST_ICRC1_LEDGER="bw4dl-smaaa-aaaaa-qaacq-cai" +CANISTER_ID_TEST_ICRC1_INDEX="br5f7-7uaaa-aaaaa-qaaca-cai" # Default identity store path DFX_DEFAULT_IDENTITY_STORE_PATH=${DFX_DEFAULT_IDENTITY_STORE_PATH:-"$HOME/.config/dfx/identity"} @@ -51,6 +53,7 @@ Options: --init-app-wallet fresh installs the Orbit Wallet application --candid-generate generates the code for the candid specifications that the Orbit applications are using --approve-waiting-list approves the given principal to the waiting list + --deploy-icrc1-token deploys an ICRC1 token canister for local development EOF } @@ -253,6 +256,66 @@ function approve_waiting_list() { dfx canister call control_panel update_waiting_list "record { users = vec { principal \"$principal\" }; new_status = variant {Approved} }" } +function deploy_icrc1_token() { + uninstall_test_icrc1_canisters + install_test_icrc1_canisters +} + +function uninstall_test_icrc1_canisters() { + # Uninstall the ICRC1 Ledger canister + dfx canister delete icrc1_ledger_canister -y >/dev/null 2>&1 || true + dfx canister delete icrc1_index_canister -y >/dev/null 2>&1 || true +} + +function install_test_icrc1_canisters() { + if [ "$MINTER_IDENTITY_NAME" == "$WHOAMI" ]; then + echo "You can't run this script as the minter identity. Please run it as a different identity." + exit 1 + fi + + if ! dfx identity list | grep -q $MINTER_IDENTITY_NAME; then + dfx identity new $MINTER_IDENTITY_NAME --storage-mode plaintext + fi + + dfx deploy --specified-id $CANISTER_ID_TEST_ICRC1_LEDGER icrc1_ledger_canister --argument " + (variant { + Init = record { + minting_account = record { + owner = principal \"$(dfx identity get-principal --identity $MINTER_IDENTITY_NAME)\"; + }; + initial_balances = vec { + record { + record { + owner = principal \"$(dfx identity get-principal)\"; + }; + 1_000_000_000_000 : nat; + }; + }; + token_symbol = \"TEST\"; + token_name = \"Test ICRC1 Token\"; + + metadata = vec {}; + + transfer_fee = 20 : nat; + + archive_options = record { + num_blocks_to_archive = 100 : nat64; + trigger_threshold = 100 : nat64; + controller_id = principal \"$CANISTER_ID_TEST_ICRC1_LEDGER\"; + }; + } + }) +" + + dfx deploy --specified-id $CANISTER_ID_TEST_ICRC1_INDEX icrc1_index_canister --argument " + (opt variant { + Init = record { + ledger_id = principal \"$CANISTER_ID_TEST_ICRC1_LEDGER\" + } + }) +" +} + ############################################# # SCRIPT OPTIONS # ############################################# @@ -281,6 +344,11 @@ while [[ $# -gt 0 ]]; do shift # Remove the principal ID from the arguments echo ;; + --deploy-icrc1-token) + shift + exec_function deploy_icrc1_token + echo + ;; --init) shift exec_function setup_devenv diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 83ca3e26c..4fe019342 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -74,9 +74,15 @@ importers: '@dfinity/identity': specifier: 1.4.0 version: 1.4.0(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0)(@peculiar/webcrypto@1.4.3) + '@dfinity/ledger-icrc': + specifier: 2.3.3 + version: 2.3.3(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0)(@dfinity/utils@2.3.1(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0)) '@dfinity/principal': specifier: 1.4.0 version: 1.4.0 + '@dfinity/utils': + specifier: 2.3.1 + version: 2.3.1(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0) '@mdi/font': specifier: 7.4.47 version: 7.4.47 @@ -277,16 +283,16 @@ packages: resolution: {integrity: sha512-2ofRCjnnA9y+wk8b9IAREroeUP02KHp431N2mhKniy2yKIDKpbrHv9eXwm8cBeWQYcJmzv5qKCu65P47eCF7CQ==} engines: {node: '>=6.9.0'} - '@babel/helper-string-parser@7.25.7': - resolution: {integrity: sha512-CbkjYdsJNHFk8uqpEkpCvRs3YRp9tY6FmFY7wLMSYuGYkrdUi7r2lc4/wqsvlHoMznX3WJ9IP8giGPq68T/Y6g==} + '@babel/helper-string-parser@7.25.9': + resolution: {integrity: sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==} engines: {node: '>=6.9.0'} '@babel/helper-validator-identifier@7.24.5': resolution: {integrity: sha512-3q93SSKX2TWCG30M2G2kwaKeTYgEUp5Snjuj8qm729SObL6nbtUldAi37qbxkD5gg3xnBio+f9nqpSepGZMvxA==} engines: {node: '>=6.9.0'} - '@babel/helper-validator-identifier@7.25.7': - resolution: {integrity: sha512-AM6TzwYqGChO45oiuPqwL2t20/HdMC1rTPAesnBCgPCSF1x3oN9MVUwQV2iyz4xqWrctwK5RNC8LV22kaQCNYg==} + '@babel/helper-validator-identifier@7.25.9': + resolution: {integrity: sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==} engines: {node: '>=6.9.0'} '@babel/helper-validator-option@7.23.5': @@ -310,8 +316,8 @@ packages: engines: {node: '>=6.0.0'} hasBin: true - '@babel/parser@7.25.7': - resolution: {integrity: sha512-aZn7ETtQsjjGG5HruveUK06cU3Hljuhd9Iojm4M8WWv3wLE6OkE5PWbDUkItmMgegmccaITudyuW5RPYrYlgWw==} + '@babel/parser@7.25.9': + resolution: {integrity: sha512-aI3jjAAO1fh7vY/pBGsn1i9LDbRP43+asrRlkPuTXW5yHXtd1NgTEMudbBoDDxrf1daEEfPJqR+JBMakzrR4Dg==} engines: {node: '>=6.0.0'} hasBin: true @@ -801,8 +807,8 @@ packages: resolution: {integrity: sha512-6mQNsaLeXTw0nxYUYu+NSa4Hx4BlF1x1x8/PMFbiR+GBSr+2DkECc69b8hgy2frEodNcvPffeH8YfWd3LI6jhQ==} engines: {node: '>=6.9.0'} - '@babel/types@7.25.7': - resolution: {integrity: sha512-vwIVdXG+j+FOpkwqHRcBgHLYNL7XMkufrlaFvL9o6Ai9sJn9+PdyIL5qa0XzTZw084c+u9LOls53eoZWP/W5WQ==} + '@babel/types@7.25.9': + resolution: {integrity: sha512-OwS2CM5KocvQ/k7dFJa8i5bNGJP0hXWfVCfDkqRFP1IreH1JDC7wG6eCYCi0+McbfT8OR/kNqsI0UU0xP9H6PQ==} engines: {node: '>=6.9.0'} '@bcoe/v8-coverage@0.2.3': @@ -841,9 +847,24 @@ packages: '@dfinity/principal': ^1.4.0 '@peculiar/webcrypto': ^1.4.0 + '@dfinity/ledger-icrc@2.3.3': + resolution: {integrity: sha512-ASF9A/FcyHlEsFVENEZ1/f/PFcdvtEg75zD70zL/n7FUSN+3I8c82tbt5TunraRCGBQjDgBigUoRY2+k5J18rQ==} + peerDependencies: + '@dfinity/agent': ^1.3.0 + '@dfinity/candid': ^1.3.0 + '@dfinity/principal': ^1.3.0 + '@dfinity/utils': ^2.3.1 + '@dfinity/principal@1.4.0': resolution: {integrity: sha512-SuTBVlc71ub89ji0WN5/T100zUG2uIMn5x4+We4vS4nJ0R3/Xt89XJsHepjd5SQTSQPOvP7eQ+S8cQKWRz/RkA==} + '@dfinity/utils@2.3.1': + resolution: {integrity: sha512-FvMBwlKBJGJhugGRn13U0Jvfldu01P2QZXDqogkWTHnQs+IJ8N1sVLQ8DQaT+bnOaT5Ii8kEes0ecaMaeTdHgw==} + peerDependencies: + '@dfinity/agent': ^1.3.0 + '@dfinity/candid': ^1.3.0 + '@dfinity/principal': ^1.3.0 + '@emnapi/core@1.3.0': resolution: {integrity: sha512-9hRqVlhwqBqCoToZ3hFcNVqL+uyHV06Y47ax4UB8L6XgVRqYz7MFnfessojo6+5TK89pKwJnpophwjTMOeKI9Q==} @@ -2619,7 +2640,6 @@ packages: glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Glob versions prior to v9 are no longer supported globals@11.12.0: resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==} @@ -2713,7 +2733,6 @@ packages: inflight@1.0.6: resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} - deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} @@ -2927,8 +2946,8 @@ packages: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} - magic-string@0.30.11: - resolution: {integrity: sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==} + magic-string@0.30.12: + resolution: {integrity: sha512-Ea8I3sQMVXr8JhN4z+H/d8zwo+tYDgHE9+5G4Wnrwhs0gaK9fXTKx0Tw5Xwsd/bCPTTZNRAdpyzvoeORe9LYpw==} magic-string@0.30.8: resolution: {integrity: sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ==} @@ -3158,8 +3177,8 @@ packages: picocolors@1.0.0: resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==} - picocolors@1.1.0: - resolution: {integrity: sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==} + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} picomatch@2.3.1: resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} @@ -4070,11 +4089,11 @@ snapshots: '@babel/helper-string-parser@7.24.1': {} - '@babel/helper-string-parser@7.25.7': {} + '@babel/helper-string-parser@7.25.9': {} '@babel/helper-validator-identifier@7.24.5': {} - '@babel/helper-validator-identifier@7.25.7': {} + '@babel/helper-validator-identifier@7.25.9': {} '@babel/helper-validator-option@7.23.5': {} @@ -4103,9 +4122,9 @@ snapshots: dependencies: '@babel/types': 7.24.5 - '@babel/parser@7.25.7': + '@babel/parser@7.25.9': dependencies: - '@babel/types': 7.25.7 + '@babel/types': 7.25.9 '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.24.5(@babel/core@7.24.5)': dependencies: @@ -4695,11 +4714,10 @@ snapshots: '@babel/helper-validator-identifier': 7.24.5 to-fast-properties: 2.0.0 - '@babel/types@7.25.7': + '@babel/types@7.25.9': dependencies: - '@babel/helper-string-parser': 7.25.7 - '@babel/helper-validator-identifier': 7.25.7 - to-fast-properties: 2.0.0 + '@babel/helper-string-parser': 7.25.9 + '@babel/helper-validator-identifier': 7.25.9 '@bcoe/v8-coverage@0.2.3': {} @@ -4740,10 +4758,23 @@ snapshots: '@peculiar/webcrypto': 1.4.3 borc: 2.1.2 + '@dfinity/ledger-icrc@2.3.3(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0)(@dfinity/utils@2.3.1(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))': + dependencies: + '@dfinity/agent': 1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0) + '@dfinity/candid': 1.4.0(@dfinity/principal@1.4.0) + '@dfinity/principal': 1.4.0 + '@dfinity/utils': 2.3.1(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0) + '@dfinity/principal@1.4.0': dependencies: '@noble/hashes': 1.4.0 + '@dfinity/utils@2.3.1(@dfinity/agent@1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0))(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0)': + dependencies: + '@dfinity/agent': 1.4.0(@dfinity/candid@1.4.0(@dfinity/principal@1.4.0))(@dfinity/principal@1.4.0) + '@dfinity/candid': 1.4.0(@dfinity/principal@1.4.0) + '@dfinity/principal': 1.4.0 + '@emnapi/core@1.3.0': dependencies: '@emnapi/wasi-threads': 1.0.1 @@ -5772,7 +5803,7 @@ snapshots: '@vue/compiler-core@3.5.11': dependencies: - '@babel/parser': 7.25.7 + '@babel/parser': 7.25.9 '@vue/shared': 3.5.11 entities: 4.5.0 estree-walker: 2.0.2 @@ -5790,13 +5821,13 @@ snapshots: '@vue/compiler-sfc@3.5.11': dependencies: - '@babel/parser': 7.25.7 + '@babel/parser': 7.25.9 '@vue/compiler-core': 3.5.11 '@vue/compiler-dom': 3.5.11 '@vue/compiler-ssr': 3.5.11 '@vue/shared': 3.5.11 estree-walker: 2.0.2 - magic-string: 0.30.11 + magic-string: 0.30.12 postcss: 8.4.47 source-map-js: 1.2.0 @@ -6918,7 +6949,7 @@ snapshots: dependencies: yallist: 4.0.0 - magic-string@0.30.11: + magic-string@0.30.12: dependencies: '@jridgewell/sourcemap-codec': 1.5.0 @@ -7178,7 +7209,7 @@ snapshots: picocolors@1.0.0: {} - picocolors@1.1.0: {} + picocolors@1.1.1: {} picomatch@2.3.1: {} @@ -7225,7 +7256,7 @@ snapshots: postcss@8.4.47: dependencies: nanoid: 3.3.7 - picocolors: 1.1.0 + picocolors: 1.1.1 source-map-js: 1.2.1 prelude-ls@1.2.1: {} diff --git a/scripts/benchmark-canister.sh b/scripts/benchmark-canister.sh index 87626bdf3..5781fa05c 100755 --- a/scripts/benchmark-canister.sh +++ b/scripts/benchmark-canister.sh @@ -25,7 +25,7 @@ print_message "Benchmarking canister at $CANISTER_PATH" # Install canbench if not already installed if ! cargo install --list | grep -q canbench; then print_message "Installing canbench..." - cargo install canbench --version 0.1.4 + cargo install canbench --version 0.1.8 fi # Changes to the canister path @@ -42,8 +42,8 @@ canbench --less-verbose >"$CANBENCH_TMP_OUTPUT" if grep -q "(regress\|(improved by \|(new)" "$CANBENCH_TMP_OUTPUT"; then # Check if running in GitHub Actions and print the CANBENCH_TMP_OUTPUT file if so if [ "${GITHUB_ACTIONS:-}" = "true" ]; then - print_message "Review the benchmark results below:" - cat "$CANBENCH_TMP_OUTPUT" + print_message "Review the benchmark results below:" + cat "$CANBENCH_TMP_OUTPUT" fi print_message "Benchmarking completed. diff --git a/scripts/run-integration-tests.sh b/scripts/run-integration-tests.sh index 5a15ab1a9..9a5533914 100755 --- a/scripts/run-integration-tests.sh +++ b/scripts/run-integration-tests.sh @@ -42,6 +42,7 @@ if [ $DOWNLOAD_NNS_CANISTERS == "true" ]; then ./scripts/download-nns-canister-wasm.sh icp_ledger ledger-canister ./scripts/download-nns-canister-wasm.sh icp_index ic-icp-index-canister ./scripts/download-nns-canister-wasm.sh cmc cycles-minting-canister + ./scripts/download-nns-canister-wasm.sh icrc1_ledger ic-icrc1-ledger fi if [ $DOWNLOAD_ASSET_CANISTER == "true" ]; then diff --git a/tests/integration/Cargo.toml b/tests/integration/Cargo.toml index 1f6e1901d..af00c73f0 100644 --- a/tests/integration/Cargo.toml +++ b/tests/integration/Cargo.toml @@ -13,6 +13,7 @@ hex = { workspace = true } orbit-essentials = { path = '../../libs/orbit-essentials', version = '0.0.2-alpha.6' } ic-certified-assets = { workspace = true } ic-ledger-types = { workspace = true } +icrc-ledger-types = { workspace = true } itertools = { workspace = true } lazy_static = { workspace = true } num-bigint = { workspace = true } diff --git a/tests/integration/assets/station-memory-v1.bin b/tests/integration/assets/station-memory-v1.bin new file mode 100644 index 000000000..c35b27d39 Binary files /dev/null and b/tests/integration/assets/station-memory-v1.bin differ diff --git a/tests/integration/src/account_tests.rs b/tests/integration/src/account_tests.rs new file mode 100644 index 000000000..56c8b592e --- /dev/null +++ b/tests/integration/src/account_tests.rs @@ -0,0 +1,203 @@ +use std::time::Duration; + +use crate::interfaces::mint_icp; +use crate::setup::{setup_new_env, WALLET_ADMIN_USER}; +use crate::utils::{create_account, expect_await_call_result, get_icp_asset}; +use crate::TestEnv; +use candid::Encode; +use ic_ledger_types::AccountIdentifier; +use orbit_essentials::api::ApiResult; +use pocket_ic::update_candid_as; +use station_api::{ + AddAccountOperationInput, AllowDTO, FetchAccountBalancesInput, FetchAccountBalancesResponse, + MeResponse, RequestPolicyRuleDTO, +}; + +#[test] +fn test_fetch_balances() { + let TestEnv { + env, + canister_ids, + // controller, + minter, + .. + } = setup_new_env(); + + // register user + let res: (ApiResult,) = + update_candid_as(&env, canister_ids.station, WALLET_ADMIN_USER, "me", ()).unwrap(); + let user_dto = res.0.unwrap().me; + + let icp_asset = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + + let permission = AllowDTO { + auth_scope: station_api::AuthScopeDTO::Restricted, + user_groups: vec![], + users: vec![user_dto.id.clone()], + }; + + let account = create_account( + &env, + canister_ids.station, + user_dto.identities[0], + AddAccountOperationInput { + name: "test account".to_owned(), + assets: vec![icp_asset.id.clone()], + metadata: vec![], + read_permission: permission.clone(), + configs_permission: permission.clone(), + transfer_permission: permission.clone(), + configs_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + transfer_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + }, + ); + + let icp_account_identifier = AccountIdentifier::from_hex( + &account + .addresses + .iter() + .find(|a| a.format == "icp_account_identifier") + .expect("cannot get ICP account identifier") + .address, + ) + .expect("cannot parse ICP account identifier"); + + mint_icp(&env, minter, &icp_account_identifier, 10 * 100_000_000) + .expect("failed to mint ICP to account"); + + let messages_ids = [ + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + ]; + + let results = messages_ids + .into_iter() + .map(|message_id| { + expect_await_call_result::<(ApiResult,)>( + env.await_call(message_id).expect("failed to await call"), + ) + .0 + .expect("failed to get result") + }) + .collect::>(); + + results.iter().any(|result| { + result.balances[0] + .as_ref() + .map_or(false, |account_balance| { + account_balance.query_state == "fresh" + }) + }); + results.iter().any(|result| result.balances[0].is_none()); + + let messages_ids = [ + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + ]; + + let results = messages_ids + .into_iter() + .map(|message_id| { + expect_await_call_result::<(ApiResult,)>( + env.await_call(message_id).expect("failed to await call"), + ) + .0 + .expect("failed to get result") + }) + .collect::>(); + + results.iter().all(|result| { + result.balances[0] + .as_ref() + .map_or(false, |account_balance| { + account_balance.query_state == "fresh" + }) + }); + + env.advance_time(Duration::from_secs(10)); + + let messages_ids = [ + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + env.submit_call( + canister_ids.station, + user_dto.identities[0], + "fetch_account_balances", + Encode!(&FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }) + .unwrap(), + ) + .expect("failed to submit call"), + ]; + + let results = messages_ids + .into_iter() + .map(|message_id| { + expect_await_call_result::<(ApiResult,)>( + env.await_call(message_id).expect("failed to await call"), + ) + .0 + .expect("failed to get result") + }) + .collect::>(); + + results.iter().any(|result| { + result.balances[0] + .as_ref() + .map_or(false, |account_balance| { + account_balance.query_state == "fresh" + }) + }); + results.iter().any(|result| { + result.balances[0] + .as_ref() + .map_or(false, |account_balance| { + account_balance.query_state == "stale_refreshing" + }) + }); +} diff --git a/tests/integration/src/address_book_tests.rs b/tests/integration/src/address_book_tests.rs index c678e1458..3a28a0541 100644 --- a/tests/integration/src/address_book_tests.rs +++ b/tests/integration/src/address_book_tests.rs @@ -1,6 +1,8 @@ use crate::interfaces::{default_account, get_icp_balance, send_icp_to_account, ICP, ICP_FEE}; use crate::setup::{setup_new_env, WALLET_ADMIN_USER}; -use crate::utils::{execute_request, get_user, user_test_id}; +use crate::utils::{ + execute_request, get_icp_account_identifier, get_icp_asset, get_user, user_test_id, +}; use crate::TestEnv; use ic_ledger_types::AccountIdentifier; use pocket_ic::update_candid_as; @@ -24,8 +26,9 @@ fn address_book_entry_lifecycle() { RequestOperationInput::AddAddressBookEntry(AddAddressBookEntryOperationInput { address_owner: "John Doe".to_string(), address: "0x1234".to_string(), + address_format: "icp_account_identifier".to_string(), blockchain: "icp".to_string(), - labels: vec!["native".to_string()], + labels: vec!["icp_native".to_string()], metadata: vec![MetadataDTO { key: "kyc".to_string(), value: "false".to_string(), @@ -47,7 +50,7 @@ fn address_book_entry_lifecycle() { assert_eq!(address_book_entry.address_owner, "John Doe".to_string()); assert_eq!(address_book_entry.address, "0x1234".to_string()); assert_eq!(address_book_entry.blockchain, "icp".to_string()); - assert_eq!(address_book_entry.labels, vec!["native".to_string()]); + assert_eq!(address_book_entry.labels, vec!["icp_native".to_string()]); assert_eq!( address_book_entry.metadata, vec![MetadataDTO { @@ -60,9 +63,11 @@ fn address_book_entry_lifecycle() { let add_address_book_entry = RequestOperationInput::AddAddressBookEntry(AddAddressBookEntryOperationInput { address_owner: "Max Mustermann".to_string(), + address_format: "icp_account_identifier".to_string(), + address: "0x1234".to_string(), blockchain: "icp".to_string(), - labels: vec!["native".to_string()], + labels: vec!["icp_native".to_string()], metadata: vec![MetadataDTO { key: "kyc".to_string(), value: "true".to_string(), @@ -80,9 +85,10 @@ fn address_book_entry_lifecycle() { let add_address_book_entry = RequestOperationInput::AddAddressBookEntry(AddAddressBookEntryOperationInput { address_owner: "Max Mustermann".to_string(), + address_format: "icp_account_identifier".to_string(), address: "0x5678".to_string(), blockchain: "icp".to_string(), - labels: vec!["native".to_string()], + labels: vec!["icp_native".to_string()], metadata: vec![MetadataDTO { key: "kyc".to_string(), value: "true".to_string(), @@ -107,7 +113,10 @@ fn address_book_entry_lifecycle() { ); assert_eq!(next_address_book_entry.address, "0x5678".to_string()); assert_eq!(next_address_book_entry.blockchain, "icp".to_string()); - assert_eq!(next_address_book_entry.labels, vec!["native".to_string()]); + assert_eq!( + next_address_book_entry.labels, + vec!["icp_native".to_string()] + ); assert_eq!( next_address_book_entry.metadata, vec![MetadataDTO { @@ -123,6 +132,7 @@ fn address_book_entry_lifecycle() { addresses: None, ids: None, paginate: None, + address_formats: None, }; let res: (Result,) = update_candid_as( &env, @@ -196,6 +206,7 @@ fn address_book_entry_lifecycle() { addresses: None, ids: None, paginate: None, + address_formats: None, }; let res: (Result,) = update_candid_as( &env, @@ -230,9 +241,10 @@ fn check_address_book_for_transfer() { let add_address_book_entry = RequestOperationInput::AddAddressBookEntry(AddAddressBookEntryOperationInput { address_owner: "John Doe".to_string(), + address_format: "icp_account_identifier".to_string(), address: john_doe_account.clone(), blockchain: "icp".to_string(), - labels: vec!["native".to_string()], + labels: vec!["icp_native".to_string()], metadata: vec![MetadataDTO { key: "kyc".to_string(), value: "false".to_string(), @@ -255,11 +267,12 @@ fn check_address_book_for_transfer() { // get admin user let admin_user = get_user(&env, WALLET_ADMIN_USER, canister_ids.station); + let icp = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + // create account for admin user let add_account = RequestOperationInput::AddAccount(AddAccountOperationInput { name: "admin".to_string(), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp.id.clone()], read_permission: AllowDTO { auth_scope: station_api::AuthScopeDTO::Restricted, user_groups: vec![], @@ -289,8 +302,10 @@ fn check_address_book_for_transfer() { _ => panic!("unexpected request operation"), }; + let icp_address = get_icp_account_identifier(&admin_account.addresses).expect("no icp address"); + // send ICP to admin user's station account - let admin_account_address = AccountIdentifier::from_hex(&admin_account.address).unwrap(); + let admin_account_address = AccountIdentifier::from_hex(&icp_address).unwrap(); send_icp_to_account( &env, controller, @@ -298,6 +313,7 @@ fn check_address_book_for_transfer() { ICP + ICP_FEE, 0, None, + None, ) .unwrap(); @@ -305,6 +321,8 @@ fn check_address_book_for_transfer() { // and check that transfer request gets rejected let transfer = RequestOperationInput::Transfer(TransferOperationInput { from_account_id: admin_account.id, + from_asset_id: icp.id, + with_standard: "icp_native".to_string(), to: john_doe_account, amount: ICP.into(), fee: None, diff --git a/tests/integration/src/asset_tests.rs b/tests/integration/src/asset_tests.rs new file mode 100644 index 000000000..5b0fdf491 --- /dev/null +++ b/tests/integration/src/asset_tests.rs @@ -0,0 +1,123 @@ +use candid::Principal; + +use crate::{ + setup::{setup_new_env, WALLET_ADMIN_USER}, + test_data::{ + asset::{ + add_asset, add_asset_with_input, edit_asset_name, get_asset, list_assets, remove_asset, + }, + user::add_user, + }, + TestEnv, +}; + +#[test] +fn asset_lifecycle_test() { + let TestEnv { + env, canister_ids, .. + } = setup_new_env(); + + // create asset + let asset = add_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + + // edit asset + edit_asset_name( + &env, + canister_ids.station, + WALLET_ADMIN_USER, + asset.id.clone(), + "test".to_string(), + ); + + // remove asset + remove_asset(&env, canister_ids.station, WALLET_ADMIN_USER, asset.id); +} + +#[test] +#[should_panic] +fn asset_uniqeness_test() { + // assets with the same symbol and blockchain are not allowed + + let TestEnv { + env, canister_ids, .. + } = setup_new_env(); + + add_asset_with_input( + &env, + canister_ids.station, + WALLET_ADMIN_USER, + station_api::AddAssetOperationInput { + name: "asset".to_string(), + blockchain: "icp".to_string(), + standards: vec!["icp_native".to_string()], + metadata: Vec::new(), + symbol: "SYM".to_string(), + decimals: 8, + }, + ); + + add_asset_with_input( + &env, + canister_ids.station, + WALLET_ADMIN_USER, + station_api::AddAssetOperationInput { + name: "asset".to_string(), + blockchain: "icp".to_string(), + standards: vec!["icp_native".to_string()], + metadata: Vec::new(), + symbol: "SYM".to_string(), + decimals: 8, + }, + ); +} + +#[test] +fn asset_permission_test() { + // unauthorized users cant interact with assets + let TestEnv { + env, canister_ids, .. + } = setup_new_env(); + + let asset = add_asset_with_input( + &env, + canister_ids.station, + WALLET_ADMIN_USER, + station_api::AddAssetOperationInput { + name: "asset".to_string(), + blockchain: "icp".to_string(), + standards: vec!["icp_native".to_string()], + metadata: Vec::new(), + symbol: "SYM".to_string(), + decimals: 8, + }, + ); + + let user = add_user(&env, canister_ids.station, WALLET_ADMIN_USER, vec![]); + + list_assets(&env, canister_ids.station, user.identities[0]) + .expect("Station user should be able to list assets") + .0 + .expect("Station user should be able to list assets"); + + list_assets(&env, canister_ids.station, Principal::anonymous()) + .expect_err("Unauthenticated user should not be able to list assets"); + + get_asset( + &env, + canister_ids.station, + Principal::anonymous(), + asset.id.clone(), + ) + .expect_err("Unauthenticated user should not be able to get asset"); + + list_assets(&env, canister_ids.station, Principal::from_slice(&[0; 29])) + .expect_err("Unauthorized user should not be able to list assets"); + + get_asset( + &env, + canister_ids.station, + Principal::from_slice(&[0; 29]), + asset.id, + ) + .expect_err("Unauthorized user should not be able to get asset"); +} diff --git a/tests/integration/src/cycles_monitor_tests.rs b/tests/integration/src/cycles_monitor_tests.rs index b93679b02..9bc8645fb 100644 --- a/tests/integration/src/cycles_monitor_tests.rs +++ b/tests/integration/src/cycles_monitor_tests.rs @@ -4,7 +4,8 @@ use crate::setup::{ }; use crate::utils::{ advance_time_to_burn_cycles, controller_test_id, create_icp_account, - get_core_canister_health_status, get_system_info, get_user, user_test_id, NNS_ROOT_CANISTER_ID, + get_core_canister_health_status, get_icp_account_identifier, get_system_info, get_user, + user_test_id, NNS_ROOT_CANISTER_ID, }; use crate::TestEnv; use control_panel_api::{ @@ -232,9 +233,12 @@ fn can_mint_cycles_to_top_up_self() { let user = get_user(&env, user_id, canister_ids.station); let account = create_icp_account(&env, canister_ids.station, user.id); - let account_id = AccountIdentifier::from_hex(&account.address).unwrap(); + let account_id = AccountIdentifier::from_hex( + &get_icp_account_identifier(&account.addresses).expect("no icp address found"), + ) + .unwrap(); - send_icp_to_account(&env, controller, account_id, 100 * ICP, 0, None).unwrap(); + send_icp_to_account(&env, controller, account_id, 100 * ICP, 0, None, None).unwrap(); let pre_account_balance = get_icp_account_balance(&env, account_id); let pre_cycle_balance = env.cycle_balance(canister_ids.station); assert_eq!(pre_account_balance, 100 * ICP); diff --git a/tests/integration/src/disaster_recovery_tests.rs b/tests/integration/src/disaster_recovery_tests.rs index d8db6d22c..88c7e11d7 100644 --- a/tests/integration/src/disaster_recovery_tests.rs +++ b/tests/integration/src/disaster_recovery_tests.rs @@ -4,25 +4,29 @@ use crate::setup::{ use crate::utils::{ add_user, advance_time_to_burn_cycles, await_station_healthy, execute_request, get_account_read_permission, get_account_transfer_permission, get_account_update_permission, - get_core_canister_health_status, get_system_info, get_upgrader_disaster_recovery, - get_upgrader_logs, get_user, set_disaster_recovery, upload_canister_chunks_to_asset_canister, - user_test_id, NNS_ROOT_CANISTER_ID, + get_core_canister_health_status, get_icp_asset, get_system_info, + get_upgrader_disaster_recovery, get_upgrader_logs, get_user, set_disaster_recovery, + upload_canister_chunks_to_asset_canister, user_test_id, NNS_ROOT_CANISTER_ID, }; use crate::TestEnv; -use candid::{Encode, Principal}; +use candid::{CandidType, Encode, Principal}; use orbit_essentials::api::ApiResult; use orbit_essentials::utils::sha256_hash; use pocket_ic::{query_candid_as, update_candid_as, PocketIc}; +use serde::Deserialize; use station_api::{ - AddAccountOperationInput, AllowDTO, DisasterRecoveryCommitteeDTO, HealthStatus, + AccountDTO, AddAccountOperationInput, AllowDTO, DisasterRecoveryCommitteeDTO, HealthStatus, ListAccountsResponse, RequestOperationDTO, RequestOperationInput, RequestPolicyRuleDTO, SetDisasterRecoveryOperationInput, SystemInit, SystemInstall, SystemUpgrade, }; use std::collections::BTreeMap; +use std::str::FromStr; use upgrader_api::{ - Account, AdminUser, DisasterRecoveryCommittee, GetDisasterRecoveryAccountsResponse, - GetDisasterRecoveryCommitteeResponse, SetDisasterRecoveryAccountsInput, - SetDisasterRecoveryCommitteeInput, + Account, AdminUser, Asset, DisasterRecoveryCommittee, + GetDisasterRecoveryAccountsAndAssetsResponse, GetDisasterRecoveryAccountsResponse, + GetDisasterRecoveryCommitteeResponse, MultiAssetAccount, RecoveryResult, RecoveryStatus, + SetDisasterRecoveryAccountsAndAssetsInput, SetDisasterRecoveryAccountsInput, + SetDisasterRecoveryCommitteeInput, StationRecoveryRequest, }; use uuid::Uuid; @@ -150,29 +154,34 @@ fn successful_disaster_recovery_sync() { assert_eq!(admins.users[0].name, "user_1"); assert_eq!(admins.users[1].name, "user_2"); - let args = SetDisasterRecoveryAccountsInput { + let icp_asset_id = Uuid::from_bytes([0; 16]).hyphenated().to_string(); + + let args = SetDisasterRecoveryAccountsAndAssetsInput { accounts: vec![ - Account { + MultiAssetAccount { id: Uuid::from_bytes([0; 16]).hyphenated().to_string(), - blockchain: "icp".to_owned(), - address: "abc".to_owned(), - standard: "native".to_owned(), - symbol: "ICP".to_owned(), - decimals: 8, name: "Main Account".to_owned(), metadata: vec![], + assets: vec![icp_asset_id.clone()], + seed: [0; 16], }, - Account { + MultiAssetAccount { id: Uuid::from_bytes([1; 16]).hyphenated().to_string(), - blockchain: "icp".to_owned(), - address: "def".to_owned(), - standard: "native".to_owned(), - symbol: "ICP".to_owned(), - decimals: 8, name: "Another Account".to_owned(), metadata: vec![], + assets: vec![icp_asset_id.clone()], + seed: [1; 16], }, ], + assets: vec![Asset { + blockchain: "icp".to_owned(), + id: Uuid::from_bytes([0; 16]).hyphenated().to_string(), + name: "Internet Computer".to_owned(), + symbol: "ICP".to_owned(), + decimals: 8, + metadata: vec![], + standards: vec!["icp_native".to_owned()], + }], }; // non-controller can't set disaster recovery accounts @@ -180,7 +189,7 @@ fn successful_disaster_recovery_sync() { &env, upgrader_id, Principal::from_slice(&[1]), - "set_disaster_recovery_accounts", + "set_disaster_recovery_accounts_and_assets", (args.clone(),), ) .expect("Failed update call to set disaster recovery accounts"); @@ -194,17 +203,17 @@ fn successful_disaster_recovery_sync() { &env, upgrader_id, canister_ids.station, - "set_disaster_recovery_accounts", + "set_disaster_recovery_accounts_and_assets", (args,), ) .expect("Failed update call to set disaster recovery accounts"); res.0.expect("Failed to set disaster recovery accounts"); - let res: (ApiResult,) = query_candid_as( + let res: (ApiResult,) = query_candid_as( &env, upgrader_id, canister_ids.station, - "get_disaster_recovery_accounts", + "get_disaster_recovery_accounts_and_assets", ((),), ) .expect("Failed query call to get disaster recovery accounts"); @@ -258,11 +267,12 @@ fn auto_syncs_on_account_creation() { assert!(state.accounts.is_empty()); + let icp_asset = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + // create account for admin user let add_account = RequestOperationInput::AddAccount(AddAccountOperationInput { name: "admin".to_string(), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp_asset.id], read_permission: AllowDTO { auth_scope: station_api::AuthScopeDTO::Restricted, user_groups: vec![], @@ -288,8 +298,8 @@ fn auto_syncs_on_account_creation() { let state = get_upgrader_disaster_recovery(&env, &upgrader_id, &canister_ids.station); - assert_eq!(state.accounts.len(), 1); - assert_eq!(state.accounts[0].name, "admin"); + assert_eq!(state.multi_asset_accounts.len(), 1); + assert_eq!(state.multi_asset_accounts[0].name, "admin"); } /* @@ -472,13 +482,14 @@ fn test_disaster_recovery_flow_recreates_same_accounts() { let upgrader_id = system_info.upgrader_id; let admin_user = get_user(&env, WALLET_ADMIN_USER, canister_ids.station); + let icp_asset = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + // 2. create 3 accounts with the same admin user and no approval required let mut initial_accounts = BTreeMap::new(); for account_nr in 0..3 { let create_account_args = AddAccountOperationInput { name: format!("account-{}", account_nr), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp_asset.id.clone()], read_permission: AllowDTO { auth_scope: station_api::AuthScopeDTO::Restricted, user_groups: vec![], @@ -515,25 +526,37 @@ fn test_disaster_recovery_flow_recreates_same_accounts() { .account .expect("Unexpected new account not available"); - initial_accounts.insert( - newly_added_account.id, - (newly_added_account.name, newly_added_account.address), - ); + initial_accounts.insert(newly_added_account.id.clone(), newly_added_account); } else { panic!("Unexpected request operation found"); } } + let init_assets_input = station_api::InitAssetInput { + id: icp_asset.id.clone(), + name: icp_asset.name.clone(), + symbol: icp_asset.symbol.clone(), + decimals: icp_asset.decimals, + blockchain: icp_asset.blockchain.clone(), + standards: icp_asset.standards.clone(), + metadata: vec![], + }; + // 3. perform a reinstall disaster recovery request let init_accounts_input = initial_accounts .iter() - .map(|(id, (name, _))| station_api::InitAccountInput { - id: Some(id.to_string()), - name: name.to_string(), - blockchain: "icp".to_string(), - standard: "native".to_string(), - metadata: vec![], - }) + .map( + |(id, AccountDTO { name, .. })| station_api::InitAccountInput { + id: Some(id.clone()), + name: name.to_string(), + metadata: vec![], + assets: vec![icp_asset.id.clone()], + seed: Uuid::from_str(id.as_str()) + .expect("Failed to parse uuid") + .as_bytes() + .to_owned(), + }, + ) .collect(); let (base_chunk, module_extra_chunks) = @@ -566,6 +589,7 @@ fn test_disaster_recovery_flow_recreates_same_accounts() { fallback_controller: None, upgrader: station_api::SystemUpgraderInput::Id(upgrader_id), accounts: Some(init_accounts_input), + assets: Some(vec![init_assets_input]), })) .unwrap(), install_mode: upgrader_api::InstallMode::Reinstall, @@ -636,14 +660,19 @@ fn test_disaster_recovery_flow_recreates_same_accounts() { assert_eq!(admin_user.groups.len(), 1); let admin_user_group = admin_user.groups.first().expect("No user group found"); - for (id, (name, address)) in initial_accounts { + for (id, initial_account) in initial_accounts { let account = existing_accounts .iter() .find(|a| a.id == id) .expect("Unexpected account not found"); - assert_eq!(account.name, name); - assert_eq!(account.address, address); + assert_eq!(account.name, initial_account.name); + + for account_address in initial_account.addresses.iter() { + assert!(account.addresses.iter().any(|recovered_account_address| { + recovered_account_address.address == account_address.address + })); + } account.metadata.iter().for_each(|m| { assert_eq!(m.key, "key"); @@ -734,6 +763,7 @@ fn test_disaster_recovery_flow_reuses_same_upgrader() { fallback_controller: Some(fallback_controller), upgrader: station_api::SystemUpgraderInput::Id(upgrader_id), accounts: None, + assets: None, })) .unwrap(), install_mode: upgrader_api::InstallMode::Reinstall, @@ -972,6 +1002,7 @@ fn test_disaster_recovery_failing() { name: "Station".to_string(), admins: vec![], accounts: None, + assets: None, }); // install with intentionally bad arg to fail @@ -997,3 +1028,90 @@ fn test_disaster_recovery_failing() { await_disaster_recovery_failure(&env, canister_ids.station, upgrader_id); } + +#[test] +fn test_disaster_recovery_supports_legacy_format() { + let TestEnv { + env, canister_ids, .. + } = setup_new_env(); + + let system_info = get_system_info(&env, WALLET_ADMIN_USER, canister_ids.station); + let upgrader_id = system_info.upgrader_id; + + let args = SetDisasterRecoveryAccountsInput { + accounts: vec![ + Account { + id: Uuid::from_bytes([0; 16]).hyphenated().to_string(), + name: "Main Account".to_owned(), + metadata: vec![], + blockchain: "icp".to_owned(), + address: "1".to_owned(), + standard: "icp_native".to_owned(), + symbol: "ICP1".to_owned(), + decimals: 8, + }, + Account { + id: Uuid::from_bytes([1; 16]).hyphenated().to_string(), + name: "Another Account".to_owned(), + metadata: vec![], + blockchain: "icp".to_owned(), + address: "2".to_owned(), + standard: "icp_native".to_owned(), + symbol: "ICP2".to_owned(), + decimals: 8, + }, + ], + }; + + let res: (ApiResult,) = update_candid_as( + &env, + upgrader_id, + canister_ids.station, + "set_disaster_recovery_accounts", + (args,), + ) + .expect("Failed update call to set disaster recovery accounts"); + res.0.expect("Failed to set disaster recovery accounts"); + + let res: (ApiResult,) = query_candid_as( + &env, + upgrader_id, + canister_ids.station, + "get_disaster_recovery_accounts", + ((),), + ) + .expect("Failed query call to get disaster recovery accounts"); + + let res = res.0.expect("Failed to get disaster recovery accounts"); + + assert!(res.accounts.len() == 2); + assert_eq!(res.accounts[0].name, "Main Account"); + assert_eq!(res.accounts[0].address, "1"); + + assert_eq!(res.accounts[1].name, "Another Account"); + assert_eq!(res.accounts[1].address, "2"); + + // old response format should deserialize correctly + #[derive(Clone, Debug, CandidType, Deserialize)] + pub struct GetDisasterRecoveryStateResponse { + pub committee: Option, + pub accounts: Vec, + + pub recovery_requests: Vec, + pub recovery_status: RecoveryStatus, + pub last_recovery_result: Option, + } + + let res: (ApiResult,) = query_candid_as( + &env, + upgrader_id, + canister_ids.station, + "get_disaster_recovery_state", + ((),), + ) + .expect("Failed query call to get disaster recovery accounts"); + + let res = res.0.expect("Failed to get disaster recovery accounts"); + + assert!(res.accounts.len() == 2); +} diff --git a/tests/integration/src/interfaces.rs b/tests/integration/src/interfaces.rs index 3c2aea9a9..a2b5bd2e2 100644 --- a/tests/integration/src/interfaces.rs +++ b/tests/integration/src/interfaces.rs @@ -1,11 +1,13 @@ -use candid::{CandidType, Principal}; +use candid::{CandidType, Encode, Principal}; use ic_ledger_types::{ AccountBalanceArgs, AccountIdentifier, Memo, Subaccount, Tokens, TransferArgs, TransferError, DEFAULT_SUBACCOUNT, }; -use pocket_ic::{update_candid_as, PocketIc}; +use pocket_ic::{query_candid_as, update_candid_as, PocketIc}; use std::collections::{HashMap, HashSet}; +use crate::setup::{create_canister_with_cycles, get_canister_wasm}; + #[derive(CandidType)] pub enum NnsLedgerCanisterPayload { Init(NnsLedgerCanisterInitPayload), @@ -71,12 +73,13 @@ pub fn send_icp_to_account( e8s: u64, memo: u64, from_subaccount: Option, + fee: Option, ) -> Result { let ledger_canister_id = Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai").unwrap(); let transfer_args = TransferArgs { memo: Memo(memo), amount: Tokens::from_e8s(e8s), - fee: Tokens::from_e8s(10_000), + fee: Tokens::from_e8s(fee.unwrap_or(10_000)), from_subaccount, to: beneficiary_account, created_at_time: None, @@ -100,5 +103,126 @@ pub fn send_icp( memo: u64, ) -> Result { let to = AccountIdentifier::new(&beneficiary_id, &DEFAULT_SUBACCOUNT); - send_icp_to_account(env, sender_id, to, e8s, memo, None) + send_icp_to_account(env, sender_id, to, e8s, memo, None, None) +} + +pub fn mint_icp( + env: &PocketIc, + minter_id: Principal, + to: &AccountIdentifier, + e8s: u64, +) -> Result { + send_icp_to_account(env, minter_id, *to, e8s, 0, None, Some(0)) +} + +#[derive(CandidType)] +pub struct Icrc1LedgerInitArgs { + pub minting_account: icrc_ledger_types::icrc1::account::Account, + pub fee_collector_account: Option, + pub initial_balances: Vec<(icrc_ledger_types::icrc1::account::Account, candid::Nat)>, + pub transfer_fee: candid::Nat, + pub decimals: Option, + pub token_name: String, + pub token_symbol: String, + pub metadata: Vec<( + String, + icrc_ledger_types::icrc::generic_metadata_value::MetadataValue, + )>, + pub archive_options: ArchiveOptions, + pub max_memo_length: Option, + pub feature_flags: Option, + pub maximum_number_of_accounts: Option, + pub accounts_overflow_trim_quantity: Option, +} + +#[derive(CandidType)] +pub struct ArchiveOptions { + pub trigger_threshold: usize, + pub num_blocks_to_archive: usize, + pub node_max_memory_size_bytes: Option, + pub max_message_size_bytes: Option, + pub controller_id: Principal, + pub more_controller_ids: Option>, + pub cycles_for_archive_creation: Option, + pub max_transactions_per_response: Option, +} + +#[derive(CandidType)] +pub struct FeatureFlags { + pub icrc2: bool, +} + +#[derive(CandidType)] +pub enum Icrc1LedgerArgument { + Init(Icrc1LedgerInitArgs), +} + +pub fn deploy_icrc1_token( + env: &mut PocketIc, + controller: Principal, + init: Icrc1LedgerInitArgs, +) -> Principal { + let wasm_module = get_canister_wasm("icrc1_ledger").to_vec(); + + let canister_id = create_canister_with_cycles(env, controller, 1_000_000_000_000); + + env.install_canister( + canister_id, + wasm_module, + Encode!(&Icrc1LedgerArgument::Init(init)).unwrap(), + Some(controller), + ); + + canister_id +} + +pub fn mint_icrc1_tokens( + env: &PocketIc, + ledger_id: Principal, + minter: Principal, + to: icrc_ledger_types::icrc1::account::Account, + amount: u64, +) -> Result< + icrc_ledger_types::icrc1::transfer::BlockIndex, + icrc_ledger_types::icrc1::transfer::TransferError, +> { + let res: ( + Result< + icrc_ledger_types::icrc1::transfer::BlockIndex, + icrc_ledger_types::icrc1::transfer::TransferError, + >, + ) = update_candid_as( + env, + ledger_id, + minter, + "icrc1_transfer", + (icrc_ledger_types::icrc1::transfer::TransferArg { + from_subaccount: None, + to, + fee: None, + created_at_time: None, + memo: None, + amount: amount.into(), + },), + ) + .expect("Failed to make update call"); + + res.0 +} + +pub fn get_icrc1_balance_of( + env: &PocketIc, + ledger_id: Principal, + account: icrc_ledger_types::icrc1::account::Account, +) -> candid::Nat { + let res: (candid::Nat,) = query_candid_as( + env, + ledger_id, + Principal::anonymous(), + "icrc1_balance_of", + (account,), + ) + .expect("Failed to make query call"); + + res.0 } diff --git a/tests/integration/src/lib.rs b/tests/integration/src/lib.rs index b91099213..3f25d735a 100644 --- a/tests/integration/src/lib.rs +++ b/tests/integration/src/lib.rs @@ -3,7 +3,9 @@ use candid::Principal; use pocket_ic::PocketIc; +mod account_tests; mod address_book_tests; +mod asset_tests; mod control_panel_tests; mod cycles_monitor_tests; mod dfx_orbit; diff --git a/tests/integration/src/migration_tests.rs b/tests/integration/src/migration_tests.rs index d8e28054f..e51fa12e0 100644 --- a/tests/integration/src/migration_tests.rs +++ b/tests/integration/src/migration_tests.rs @@ -1,4 +1,5 @@ use crate::setup::{get_canister_wasm, setup_new_env, WALLET_ADMIN_USER}; +use crate::test_data::asset::list_assets; use crate::test_data::{set_test_data_id, StationDataGenerator}; use crate::utils::{compress_to_gzip, create_file, read_file, NNS_ROOT_CANISTER_ID}; use crate::TestEnv; @@ -6,11 +7,14 @@ use candid::{Encode, Principal}; use orbit_essentials::api::ApiResult; use pocket_ic::{update_candid_as, PocketIc}; -const CURRENT_BASELINE_NR_OF_REQUEST_POLICIES: usize = 18; // can be found in the station core/init.rs -const CURRENT_BASELINE_NR_PERMISSIONS: usize = 35; // can be found in the station core/init.rs +const CURRENT_BASELINE_NR_OF_REQUEST_POLICIES: usize = 21; // can be found in the station core/init.rs +const CURRENT_BASELINE_NR_PERMISSIONS: usize = 40; // can be found in the station core/init.rs const PREVIOUS_BASELINE_NR_OF_REQUEST_POLICIES: usize = 18; // baseline in the previous memory version core/init.rs -const PREVIOUS_BASELINE_NR_PERMISSIONS: usize = 34; // baseline in the previous memory version core/init.rs +const PREVIOUS_BASELINE_NR_PERMISSIONS: usize = 35; // baseline in the previous memory version core/init.rs + +const POLICIES_ADDED_AT_MIGRATION: usize = 3; +const PERMISSIONS_ADDED_AT_MIGRATION: usize = 5; const USER_GROUPS_NR: usize = 10; const USER_NR: usize = 10; @@ -122,7 +126,7 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { let station_wasm = get_canister_wasm("station").to_vec(); let wasm_memory = - read_file("station-memory-v0.bin").expect("Unexpected missing older wasm memory"); + read_file("station-memory-v1.bin").expect("Unexpected missing older wasm memory"); env.stop_canister(canister_ids.station, Some(NNS_ROOT_CANISTER_ID)) .expect("unexpected failure stopping canister"); @@ -130,6 +134,7 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { // This is needed to avoid `install_code` rate limit error env.tick(); env.tick(); + env.tick(); // Set the stable memory of the canister to the previous version of the canister env.set_stable_memory( @@ -181,15 +186,21 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { &env, canister_ids.station, WALLET_ADMIN_USER, - EXPECTED_ADDITIONAL_REQUEST_POLICIES_NR + PREVIOUS_BASELINE_NR_OF_REQUEST_POLICIES, + EXPECTED_ADDITIONAL_REQUEST_POLICIES_NR + + PREVIOUS_BASELINE_NR_OF_REQUEST_POLICIES + + POLICIES_ADDED_AT_MIGRATION, ); assert_can_list_permissions( &env, canister_ids.station, WALLET_ADMIN_USER, - EXPECTED_ADDITIONAL_PERMISSIONS_NR + PREVIOUS_BASELINE_NR_PERMISSIONS, + EXPECTED_ADDITIONAL_PERMISSIONS_NR + + PREVIOUS_BASELINE_NR_PERMISSIONS + + PERMISSIONS_ADDED_AT_MIGRATION, ); + assert_has_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + // Makes sure that the next test data id number is pointing at a value that was // not already used in the previous version set_test_data_id(9_999); @@ -204,6 +215,7 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { .with_user_groups(new_records) .with_accounts(new_records) .with_address_book_entries(new_records) + .with_assets(new_records) .with_request_policy_updates(new_records) .with_station_updates(0) .with_upgrader_updates(0) @@ -250,6 +262,7 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { // for accounts there are transfer policies and configuration policies EXPECTED_ADDITIONAL_REQUEST_POLICIES_NR + PREVIOUS_BASELINE_NR_OF_REQUEST_POLICIES + + POLICIES_ADDED_AT_MIGRATION + new_records + (new_records * 2), ); @@ -258,7 +271,18 @@ fn test_canister_migration_path_with_previous_wasm_memory_version() { canister_ids.station, WALLET_ADMIN_USER, // for accounts there are view, transfer and configuration permissions - EXPECTED_ADDITIONAL_PERMISSIONS_NR + PREVIOUS_BASELINE_NR_PERMISSIONS + (new_records * 3), + EXPECTED_ADDITIONAL_PERMISSIONS_NR + + PREVIOUS_BASELINE_NR_PERMISSIONS + + PERMISSIONS_ADDED_AT_MIGRATION + + (new_records * 3), + ); + + assert_can_list_assets( + &env, + canister_ids.station, + WALLET_ADMIN_USER, + // there should be one asset here already: ICP + new_records + 1, ); } @@ -364,6 +388,7 @@ fn assert_can_list_address_book_entries( blockchain: None, labels: None, addresses: None, + address_formats: None, ids: None, paginate: Some(station_api::PaginationInput { offset: Some(0), @@ -426,7 +451,7 @@ fn assert_can_list_request_policies( requester, "list_request_policies", (station_api::ListRequestPoliciesInput { - limit: Some(25), + limit: Some(1000), offset: Some(0), },), ) @@ -462,3 +487,46 @@ fn assert_can_list_permissions( assert_eq!(res.total as usize, expected); } + +fn assert_can_list_assets( + env: &PocketIc, + station_id: Principal, + requester: Principal, + expected: usize, +) { + let res: (ApiResult,) = update_candid_as( + env, + station_id, + requester, + "list_assets", + (station_api::ListAssetsInput { + paginate: Some(station_api::PaginationInput { + offset: Some(0), + limit: Some(25), + }), + },), + ) + .unwrap(); + + let res = res.0.unwrap(); + + assert_eq!(res.total as usize, expected); +} + +fn assert_has_icp_asset(env: &PocketIc, station_id: Principal, requester: Principal) { + let assets = list_assets(env, station_id, requester) + .expect("Failed to query list assets") + .0 + .expect("Failed to list assets"); + + assert!(assets.assets.len() == 1); + assert_eq!(assets.assets[0].symbol, "ICP"); + assert_eq!(assets.assets[0].name, "Internet Computer"); + assert_eq!(&assets.assets[0].blockchain, "icp"); + assert!( + assets.assets[0] + .standards + .contains(&"icp_native".to_string()) + && assets.assets[0].standards.contains(&"icrc1".to_string()) + ); +} diff --git a/tests/integration/src/setup.rs b/tests/integration/src/setup.rs index 020d30679..0b01c2008 100644 --- a/tests/integration/src/setup.rs +++ b/tests/integration/src/setup.rs @@ -282,6 +282,7 @@ fn install_canisters( identity: WALLET_ADMIN_USER, name: "station-admin".to_string(), }], + assets: None, quorum: Some(1), upgrader: station_api::SystemUpgraderInput::WasmModule(upgrader_wasm), fallback_controller: config.fallback_controller, diff --git a/tests/integration/src/test_data.rs b/tests/integration/src/test_data.rs index bbb989e96..70ee9f338 100644 --- a/tests/integration/src/test_data.rs +++ b/tests/integration/src/test_data.rs @@ -9,6 +9,7 @@ use crate::utils::bump_time_to_avoid_ratelimit; pub mod account; pub mod address_book; +pub mod asset; pub mod permission; pub mod request_policy; pub mod system_upgrade; @@ -55,6 +56,7 @@ pub struct StationDataGenerator<'a> { station_updates: usize, permission_updates: usize, request_policy_updates: usize, + assets: usize, } impl<'a> StationDataGenerator<'a> { @@ -77,6 +79,7 @@ impl<'a> StationDataGenerator<'a> { max_user_groups_per_user: 5, has_generated: false, count_requests: 0, + assets: Self::DEFAULT_ENTRIES, } } @@ -124,6 +127,11 @@ impl<'a> StationDataGenerator<'a> { self } + pub fn with_assets(mut self, assets: usize) -> Self { + self.assets = assets; + self + } + pub fn with_edit_operations(mut self) -> Self { self.perform_edit_operations = true; self @@ -211,6 +219,15 @@ impl<'a> StationDataGenerator<'a> { format!("{}_edited", account.name), ); self.increment_request_count(); + + account::edit_account_assets( + self.env, + self.station_canister_id, + self.requester, + account.id.clone(), + station_api::ChangeAssets::ReplaceWith { assets: vec![] }, + ); + self.increment_request_count(); } } @@ -235,6 +252,23 @@ impl<'a> StationDataGenerator<'a> { } } + // Add the assets + for _ in 0..self.assets { + let asset = asset::add_asset(self.env, self.station_canister_id, self.requester); + self.increment_request_count(); + + if self.perform_edit_operations { + asset::edit_asset_name( + self.env, + self.station_canister_id, + self.requester, + asset.id.clone(), + format!("{}_edited", asset.name), + ); + self.increment_request_count(); + } + } + // Edit the permissions for _ in 0..self.permission_updates { permission::edit_permission( diff --git a/tests/integration/src/test_data/account.rs b/tests/integration/src/test_data/account.rs index a6f7b9f19..02c01c17d 100644 --- a/tests/integration/src/test_data/account.rs +++ b/tests/integration/src/test_data/account.rs @@ -1,13 +1,16 @@ use super::next_unique_id; -use crate::utils::{submit_request, wait_for_request}; +use crate::utils::{get_icp_asset, submit_request, wait_for_request}; use candid::Principal; use pocket_ic::PocketIc; +use station_api::ChangeAssets; pub fn add_account( env: &PocketIc, station_canister_id: Principal, requester: Principal, ) -> station_api::AccountDTO { + let icp_asset = get_icp_asset(env, station_canister_id, requester); + let next_id = next_unique_id(); let add_account_request = submit_request( env, @@ -15,8 +18,7 @@ pub fn add_account( station_canister_id, station_api::RequestOperationInput::AddAccount(station_api::AddAccountOperationInput { name: format!("account-{}", next_id), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp_asset.id], metadata: Vec::new(), configs_permission: station_api::AllowDTO { auth_scope: station_api::AuthScopeDTO::Authenticated, @@ -66,6 +68,34 @@ pub fn edit_account_name( station_api::RequestOperationInput::EditAccount(station_api::EditAccountOperationInput { account_id, name: Some(name), + change_assets: None, + configs_permission: None, + read_permission: None, + transfer_permission: None, + configs_request_policy: None, + transfer_request_policy: None, + }), + ); + + wait_for_request(env, requester, station_canister_id, edit_account_request) + .expect("Failed to edit account"); +} + +pub fn edit_account_assets( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + account_id: station_api::UuidDTO, + change_assets: ChangeAssets, +) { + let edit_account_request = submit_request( + env, + requester, + station_canister_id, + station_api::RequestOperationInput::EditAccount(station_api::EditAccountOperationInput { + account_id, + name: None, + change_assets: Some(change_assets), configs_permission: None, read_permission: None, transfer_permission: None, diff --git a/tests/integration/src/test_data/address_book.rs b/tests/integration/src/test_data/address_book.rs index 951ae716d..c19d41307 100644 --- a/tests/integration/src/test_data/address_book.rs +++ b/tests/integration/src/test_data/address_book.rs @@ -17,7 +17,8 @@ pub fn add_address_book_entry( station_api::RequestOperationInput::AddAddressBookEntry( station_api::AddAddressBookEntryOperationInput { blockchain: "icp".to_string(), - labels: vec!["native".to_string()], + address_format: "icp_account_identifier".to_string(), + labels: vec!["icp_native".to_string()], address_owner: format!("user-{}", next_id), metadata: Vec::new(), address: format!("{}{}", "0x", sha256_hex(&next_id.to_le_bytes())), diff --git a/tests/integration/src/test_data/asset.rs b/tests/integration/src/test_data/asset.rs new file mode 100644 index 000000000..66f74d997 --- /dev/null +++ b/tests/integration/src/test_data/asset.rs @@ -0,0 +1,123 @@ +use super::next_unique_id; +use crate::utils::{submit_request, wait_for_request}; +use candid::Principal; +use orbit_essentials::api::ApiResult; +use pocket_ic::{query_candid_as, CallError, PocketIc}; +use station_api::{GetAssetInput, GetAssetResponse, ListAssetsInput, ListAssetsResponse}; + +pub fn add_asset_with_input( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + input: station_api::AddAssetOperationInput, +) -> station_api::AssetDTO { + let add_asset_request = submit_request( + env, + requester, + station_canister_id, + station_api::RequestOperationInput::AddAsset(input), + ); + + let request = wait_for_request(env, requester, station_canister_id, add_asset_request) + .expect("Failed to add asset"); + + match request.operation { + station_api::RequestOperationDTO::AddAsset(add_asset) => add_asset.asset.unwrap(), + _ => panic!("invalid request operation"), + } +} + +pub fn add_asset( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, +) -> station_api::AssetDTO { + let next_id = next_unique_id(); + + add_asset_with_input( + env, + station_canister_id, + requester, + station_api::AddAssetOperationInput { + name: format!("asset-{}", next_id), + blockchain: "icp".to_string(), + standards: vec!["icp_native".to_string()], + metadata: Vec::new(), + symbol: format!("SYM{}", next_id), + decimals: 8, + }, + ) +} + +pub fn edit_asset_name( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + asset_id: station_api::UuidDTO, + name: String, +) { + let edit_asset_request = submit_request( + env, + requester, + station_canister_id, + station_api::RequestOperationInput::EditAsset(station_api::EditAssetOperationInput { + asset_id, + name: Some(name), + blockchain: None, + standards: None, + symbol: None, + change_metadata: None, + }), + ); + + wait_for_request(env, requester, station_canister_id, edit_asset_request) + .expect("Failed to edit asset name"); +} + +pub fn remove_asset( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + asset_id: station_api::UuidDTO, +) { + let remove_asset_request = submit_request( + env, + requester, + station_canister_id, + station_api::RequestOperationInput::RemoveAsset(station_api::RemoveAssetOperationInput { + asset_id, + }), + ); + + wait_for_request(env, requester, station_canister_id, remove_asset_request) + .expect("Failed to remove asset"); +} + +pub fn list_assets( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, +) -> Result<(ApiResult,), CallError> { + query_candid_as::<(ListAssetsInput,), (ApiResult,)>( + env, + station_canister_id, + requester, + "list_assets", + (ListAssetsInput { paginate: None },), + ) +} + +pub fn get_asset( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + asset_id: station_api::UuidDTO, +) -> Result<(ApiResult,), CallError> { + query_candid_as::<(GetAssetInput,), (ApiResult,)>( + env, + station_canister_id, + requester, + "get_asset", + (GetAssetInput { asset_id },), + ) +} diff --git a/tests/integration/src/transfer_tests.rs b/tests/integration/src/transfer_tests.rs index ede83a832..cf8e349fb 100644 --- a/tests/integration/src/transfer_tests.rs +++ b/tests/integration/src/transfer_tests.rs @@ -1,19 +1,28 @@ use crate::interfaces::{ - default_account, get_icp_balance, send_icp, send_icp_to_account, ICP, ICP_FEE, + default_account, deploy_icrc1_token, get_icp_balance, get_icrc1_balance_of, mint_icp, + mint_icrc1_tokens, send_icp, send_icp_to_account, ArchiveOptions, Icrc1LedgerInitArgs, ICP, + ICP_FEE, }; use crate::setup::{setup_new_env, WALLET_ADMIN_USER}; -use crate::utils::user_test_id; +use crate::test_data::asset::add_asset_with_input; +use crate::utils::{ + create_account, create_transfer, fetch_account_balances, get_icp_account_identifier, + get_icp_asset, user_test_id, +}; use crate::TestEnv; +use candid::Principal; use ic_ledger_types::AccountIdentifier; use orbit_essentials::api::ApiResult; use pocket_ic::{query_candid_as, update_candid_as}; use station_api::{ - AddAccountOperationInput, AllowDTO, ApiErrorDTO, CreateRequestInput, CreateRequestResponse, - GetRequestInput, GetRequestResponse, GetTransfersInput, GetTransfersResponse, - ListAccountTransfersInput, ListAccountTransfersResponse, MeResponse, QuorumPercentageDTO, - RequestExecutionScheduleDTO, RequestOperationDTO, RequestOperationInput, RequestPolicyRuleDTO, - RequestStatusDTO, TransferOperationInput, UserSpecifierDTO, + AddAccountOperationInput, AddAssetOperationInput, AllowDTO, ApiErrorDTO, CreateRequestInput, + CreateRequestResponse, GetRequestInput, GetRequestResponse, GetTransfersInput, + GetTransfersResponse, ListAccountTransfersInput, ListAccountTransfersResponse, MeResponse, + MetadataDTO, QuorumPercentageDTO, RequestExecutionScheduleDTO, RequestOperationDTO, + RequestOperationInput, RequestPolicyRuleDTO, RequestStatusDTO, TransferOperationInput, + UserSpecifierDTO, }; +use std::str::FromStr; use std::time::Duration; #[test] @@ -32,11 +41,12 @@ fn make_transfer_successful() { update_candid_as(&env, canister_ids.station, WALLET_ADMIN_USER, "me", ()).unwrap(); let user_dto = res.0.unwrap().me; + let icp_asset = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + // create account let create_account_args = AddAccountOperationInput { name: "test".to_string(), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp_asset.id.clone()], read_permission: AllowDTO { auth_scope: station_api::AuthScopeDTO::Restricted, user_groups: vec![], @@ -135,7 +145,10 @@ fn make_transfer_successful() { assert_eq!(user_balance, ICP + 2 * ICP_FEE); // send ICP to orbit station account - let account_address = AccountIdentifier::from_hex(&account_dto.address).unwrap(); + let account_address = AccountIdentifier::from_hex( + &get_icp_account_identifier(&account_dto.addresses).expect("no icp address found"), + ) + .unwrap(); send_icp_to_account( &env, WALLET_ADMIN_USER, @@ -143,6 +156,7 @@ fn make_transfer_successful() { ICP + ICP_FEE, 0, None, + None, ) .unwrap(); @@ -157,6 +171,8 @@ fn make_transfer_successful() { // make transfer request to beneficiary let transfer = TransferOperationInput { from_account_id: account_dto.id.clone(), + from_asset_id: icp_asset.id.clone(), + with_standard: "icp_native".to_string(), to: default_account(beneficiary_id), amount: ICP.into(), fee: None, @@ -188,6 +204,10 @@ fn make_transfer_successful() { env.tick(); env.tick(); env.tick(); + env.advance_time(Duration::from_secs(5)); + env.tick(); + env.tick(); + env.tick(); // check transfer request status let get_request_args = GetRequestInput { @@ -275,3 +295,310 @@ fn make_transfer_successful() { assert!(all_have_transaction_hash); } + +#[test] +fn make_icrc1_transfer() { + let TestEnv { + mut env, + canister_ids, + // controller, + .. + } = setup_new_env(); + + let beneficiary_id = user_test_id(1); + + // register user + let res: (ApiResult,) = + update_candid_as(&env, canister_ids.station, WALLET_ADMIN_USER, "me", ()).unwrap(); + let user_dto = res.0.unwrap().me; + + let ledger_controller = Principal::from_slice(&[99; 29]); + + let token_ledger_canister_id = deploy_icrc1_token( + &mut env, + ledger_controller, + Icrc1LedgerInitArgs { + minting_account: icrc_ledger_types::icrc1::account::Account { + owner: ledger_controller, + subaccount: None, + }, + fee_collector_account: None, + initial_balances: vec![], + transfer_fee: 50u64.into(), + decimals: Some(12), + token_name: "TEST_ICRC1".to_owned(), + token_symbol: "TST".to_owned(), + metadata: vec![], + archive_options: ArchiveOptions { + trigger_threshold: 1000, + num_blocks_to_archive: 1000, + node_max_memory_size_bytes: None, + max_message_size_bytes: None, + controller_id: ledger_controller, + more_controller_ids: None, + cycles_for_archive_creation: None, + max_transactions_per_response: None, + }, + max_memo_length: None, + feature_flags: None, + maximum_number_of_accounts: None, + accounts_overflow_trim_quantity: None, + }, + ); + + let asset = add_asset_with_input( + &env, + canister_ids.station, + user_dto.identities[0], + AddAssetOperationInput { + name: "Test ICRC1 Token".to_owned(), + blockchain: "icp".to_owned(), + standards: vec!["icrc1".to_owned()], + symbol: "TEST".to_owned(), + decimals: 4, + metadata: vec![ + MetadataDTO { + key: "ledger_canister_id".to_owned(), + value: Principal::to_text(&token_ledger_canister_id), + }, + MetadataDTO { + key: "index_canister_id".to_owned(), + value: Principal::to_text(&token_ledger_canister_id), + }, + ], + }, + ); + + let permission = AllowDTO { + auth_scope: station_api::AuthScopeDTO::Restricted, + user_groups: vec![], + users: vec![user_dto.id.clone()], + }; + + let account = create_account( + &env, + canister_ids.station, + user_dto.identities[0], + AddAccountOperationInput { + name: "test account".to_owned(), + assets: vec![asset.id.clone()], + metadata: vec![], + read_permission: permission.clone(), + configs_permission: permission.clone(), + transfer_permission: permission.clone(), + configs_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + transfer_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + }, + ); + + let station_account_icrc1_account = + icrc_ledger_types::icrc1::account::Account::from_str(&account.addresses[0].address) + .expect("invalid account address"); + + mint_icrc1_tokens( + &env, + token_ledger_canister_id, + ledger_controller, + station_account_icrc1_account, + 1_000_000, + ) + .expect("failed to mint icrc1 tokens"); + + let to_address = icrc_ledger_types::icrc1::account::Account { + owner: beneficiary_id, + subaccount: None, + } + .to_string(); + + create_transfer( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::TransferOperationInput { + from_account_id: account.id.clone(), + from_asset_id: asset.id.clone(), + with_standard: "icrc1".to_owned(), + to: to_address.clone(), + amount: candid::Nat::from(100u128), + fee: Some(50u64.into()), + metadata: vec![], + network: None, + }, + ); + + let balance = get_icrc1_balance_of( + &env, + token_ledger_canister_id, + icrc_ledger_types::icrc1::account::Account { + owner: beneficiary_id, + subaccount: None, + }, + ); + + assert_eq!(balance, candid::Nat::from(100u128)); + + let account_balances = fetch_account_balances( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }, + ); + + assert_eq!( + account_balances.balances[0] + .as_ref() + .expect("should have balance") + .balance, + candid::Nat::from(999_850u128) + ); + + // test transfering without specifying fee + let transfer_without_fee = create_transfer( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::TransferOperationInput { + from_account_id: account.id.clone(), + from_asset_id: asset.id.clone(), + with_standard: "icrc1".to_owned(), + to: to_address, + amount: candid::Nat::from(500u128), + fee: None, + metadata: vec![], + network: None, + }, + ); + + // the station queries the ledger canister to get the fee + assert_eq!(transfer_without_fee.fee, candid::Nat::from(50u64)); +} + +#[test] +fn make_icrc1_icp_transfer() { + let TestEnv { + env, + canister_ids, + // controller, + minter, + .. + } = setup_new_env(); + + // register user + let res: (ApiResult,) = + update_candid_as(&env, canister_ids.station, WALLET_ADMIN_USER, "me", ()).unwrap(); + let user_dto = res.0.unwrap().me; + + let icp_asset = get_icp_asset(&env, canister_ids.station, WALLET_ADMIN_USER); + + let permission = AllowDTO { + auth_scope: station_api::AuthScopeDTO::Restricted, + user_groups: vec![], + users: vec![user_dto.id.clone()], + }; + + let account = create_account( + &env, + canister_ids.station, + user_dto.identities[0], + AddAccountOperationInput { + name: "test account".to_owned(), + assets: vec![icp_asset.id.clone()], + metadata: vec![], + read_permission: permission.clone(), + configs_permission: permission.clone(), + transfer_permission: permission.clone(), + configs_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + transfer_request_policy: Some(RequestPolicyRuleDTO::AutoApproved), + }, + ); + + assert_eq!(account.addresses.len(), 2); + + let icp_account_identifier = AccountIdentifier::from_hex( + &account + .addresses + .iter() + .find(|a| a.format == "icp_account_identifier") + .expect("cannot get ICP account identifier") + .address, + ) + .expect("cannot parse ICP account identifier"); + + let icp_icrc1_account = icrc_ledger_types::icrc1::account::Account::from_str( + &account + .addresses + .iter() + .find(|a| a.format == "icrc1_account") + .expect("cannot get ICRC1 account") + .address, + ) + .expect("invalid account address"); + + mint_icp(&env, minter, &icp_account_identifier, 10 * 100_000_000) + .expect("failed to mint ICP to account"); + + mint_icrc1_tokens( + &env, + Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai").unwrap(), + minter, + icp_icrc1_account, + 20 * 100_000_000, + ) + .expect("failed to mint ICP to ICRC1 account"); + + let account_balances = fetch_account_balances( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }, + ); + assert_eq!(account_balances.balances.len(), 1); + assert_eq!( + account_balances.balances[0] + .as_ref() + .expect("should have balance") + .balance, + candid::Nat::from(30 * 100_000_000u64) + ); + + create_transfer( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::TransferOperationInput { + from_account_id: account.id.clone(), + from_asset_id: icp_asset.id.clone(), + with_standard: "icrc1".to_owned(), + to: icrc_ledger_types::icrc1::account::Account { + owner: user_dto.identities[0], + subaccount: None, + } + .to_string(), + amount: candid::Nat::from(25 * 100_000_000u64), + fee: None, + metadata: vec![], + network: None, + }, + ); + + let account_balances = fetch_account_balances( + &env, + canister_ids.station, + user_dto.identities[0], + station_api::FetchAccountBalancesInput { + account_ids: vec![account.id.clone()], + }, + ); + assert_eq!(account_balances.balances.len(), 1); + assert_eq!( + account_balances.balances[0] + .as_ref() + .expect("should have balance") + .balance, + candid::Nat::from(5 * 100_000_000u64 - 10_000) + ); +} diff --git a/tests/integration/src/utils.rs b/tests/integration/src/utils.rs index 4ca8ef1c9..6029a06e0 100644 --- a/tests/integration/src/utils.rs +++ b/tests/integration/src/utils.rs @@ -1,5 +1,8 @@ use crate::setup::{create_canister, get_canister_wasm, WALLET_ADMIN_USER}; -use candid::{CandidType, Encode, Principal}; +use crate::test_data::asset::list_assets; +use candid::utils::ArgumentDecoder; +use candid::Principal; +use candid::{decode_args, CandidType, Encode}; use control_panel_api::UploadCanisterModulesInput; use flate2::{write::GzEncoder, Compression}; use ic_certified_assets::types::{ @@ -15,12 +18,14 @@ use sha2::Digest; use sha2::Sha256; use station_api::{ AccountDTO, AddAccountOperationInput, AddUserOperationInput, AllowDTO, ApiErrorDTO, - CreateRequestInput, CreateRequestResponse, GetPermissionResponse, GetRequestInput, - GetRequestResponse, HealthStatus, MeResponse, QuorumPercentageDTO, RequestApprovalStatusDTO, - RequestDTO, RequestExecutionScheduleDTO, RequestOperationDTO, RequestOperationInput, - RequestPolicyRuleDTO, RequestStatusDTO, ResourceIdDTO, SetDisasterRecoveryOperationDTO, - SetDisasterRecoveryOperationInput, SubmitRequestApprovalInput, SubmitRequestApprovalResponse, - SystemInfoDTO, SystemInfoResponse, UserDTO, UserSpecifierDTO, UserStatusDTO, UuidDTO, + CreateRequestInput, CreateRequestResponse, FetchAccountBalancesInput, + FetchAccountBalancesResponse, GetPermissionResponse, GetRequestInput, GetRequestResponse, + GetTransfersInput, GetTransfersResponse, HealthStatus, MeResponse, QuorumPercentageDTO, + RequestApprovalStatusDTO, RequestDTO, RequestExecutionScheduleDTO, RequestOperationDTO, + RequestOperationInput, RequestPolicyRuleDTO, RequestStatusDTO, ResourceIdDTO, + SetDisasterRecoveryOperationDTO, SetDisasterRecoveryOperationInput, SubmitRequestApprovalInput, + SubmitRequestApprovalResponse, SystemInfoDTO, SystemInfoResponse, UserDTO, UserSpecifierDTO, + UserStatusDTO, UuidDTO, }; use std::io::Write; use std::path::PathBuf; @@ -227,6 +232,16 @@ pub fn wait_for_request_with_extra_ticks( request: RequestDTO, extra_ticks: u64, ) -> Result> { + // wait for the request to be approved + env.advance_time(Duration::from_secs(2)); + env.tick(); + // wait for the request to be processing + env.advance_time(Duration::from_secs(2)); + env.tick(); + // wait in case the request calls out to other canisters + env.advance_time(Duration::from_secs(2)); + env.tick(); + for _ in 0..extra_ticks { // timer's period for processing requests is 5 seconds env.advance_time(Duration::from_secs(5)); @@ -577,11 +592,12 @@ pub fn get_account_transfer_permission( } pub fn create_icp_account(env: &PocketIc, station_id: Principal, user_id: UuidDTO) -> AccountDTO { + let icp = get_icp_asset(env, station_id, WALLET_ADMIN_USER); + // create account let create_account_args = AddAccountOperationInput { name: "test".to_string(), - blockchain: "icp".to_string(), - standard: "native".to_string(), + assets: vec![icp.id.clone()], read_permission: AllowDTO { auth_scope: station_api::AuthScopeDTO::Restricted, user_groups: vec![], @@ -611,8 +627,18 @@ pub fn create_icp_account(env: &PocketIc, station_id: Principal, user_id: UuidDT )), metadata: vec![], }; + + create_account(env, station_id, WALLET_ADMIN_USER, create_account_args) +} + +pub fn create_account( + env: &PocketIc, + station_id: Principal, + requester: Principal, + input: AddAccountOperationInput, +) -> AccountDTO { let add_account_request = CreateRequestInput { - operation: RequestOperationInput::AddAccount(create_account_args), + operation: RequestOperationInput::AddAccount(input), title: None, summary: None, execution_plan: Some(RequestExecutionScheduleDTO::Immediate), @@ -621,7 +647,7 @@ pub fn create_icp_account(env: &PocketIc, station_id: Principal, user_id: UuidDT let res: (ApiResult,) = update_candid_as( env, station_id, - WALLET_ADMIN_USER, + requester, "create_request", (add_account_request,), ) @@ -651,7 +677,7 @@ pub fn create_icp_account(env: &PocketIc, station_id: Principal, user_id: UuidDT let res: (ApiResult,) = update_candid_as( env, station_id, - WALLET_ADMIN_USER, + requester, "get_request", (get_request_args,), ) @@ -677,6 +703,138 @@ pub fn create_icp_account(env: &PocketIc, station_id: Principal, user_id: UuidDT } } +pub fn create_transfer( + env: &PocketIc, + station_id: Principal, + requester: Principal, + input: station_api::TransferOperationInput, +) -> station_api::TransferDTO { + // make transfer request to beneficiary + + let transfer_request = CreateRequestInput { + operation: RequestOperationInput::Transfer(input), + title: None, + summary: None, + expiration_dt: None, + execution_plan: Some(RequestExecutionScheduleDTO::Immediate), + }; + let res: (Result,) = update_candid_as( + env, + station_id, + requester, + "create_request", + (transfer_request,), + ) + .unwrap(); + let request_dto = res.0.unwrap().request; + + // wait for the request to be approved (timer's period is 5 seconds) + env.advance_time(Duration::from_secs(5)); + env.tick(); + // wait for the request to be processing (timer's period is 5 seconds) and first is set to processing + env.advance_time(Duration::from_secs(5)); + env.tick(); + env.tick(); + env.tick(); + env.advance_time(Duration::from_secs(5)); + env.tick(); + env.tick(); + env.tick(); + + // check transfer request status + let get_request_args = GetRequestInput { + request_id: request_dto.id.clone(), + with_full_info: Some(false), + }; + let res: (Result,) = update_candid_as( + env, + station_id, + requester, + "get_request", + (get_request_args,), + ) + .unwrap(); + let new_request_dto = res.0.unwrap().request; + match new_request_dto.status { + RequestStatusDTO::Completed { .. } => {} + _ => { + panic!( + "request must be completed by now but instead is {:?}", + new_request_dto.status + ); + } + }; + + // request has the transfer id filled out + let transfer_id = match new_request_dto.operation { + RequestOperationDTO::Transfer(transfer) => transfer + .transfer_id + .expect("transfer id must be set for completed transfer"), + _ => { + panic!("request must be Transfer"); + } + }; + + // fetch the transfer and check if its request id matches the request id that created it + let res: (Result,) = query_candid_as( + env, + station_id, + requester, + "get_transfers", + (GetTransfersInput { + transfer_ids: vec![transfer_id], + },), + ) + .expect("Failed to send query call"); + + res.0 + .expect("Failed to get transfers") + .transfers + .first() + .expect("no transfer in result") + .clone() +} + +pub fn fetch_account_balances( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, + input: FetchAccountBalancesInput, +) -> station_api::FetchAccountBalancesResponse { + update_candid_as::<(FetchAccountBalancesInput,), (ApiResult,)>( + env, + station_canister_id, + requester, + "fetch_account_balances", + (input,), + ) + .expect("Failed to send query call") + .0 + .expect("Failed to get account balances") +} + +pub fn get_icp_asset( + env: &PocketIc, + station_canister_id: Principal, + requester: Principal, +) -> station_api::AssetDTO { + list_assets(env, station_canister_id, requester) + .expect("Failed to query list_assets") + .0 + .expect("Failed to list assets") + .assets + .into_iter() + .find(|asset| asset.symbol == "ICP") + .expect("Failed to find ICP asset") +} + +pub fn get_icp_account_identifier(addresses: &[station_api::AccountAddressDTO]) -> Option { + addresses + .iter() + .find(|a| a.format == "icp_account_identifier") + .map(|a| a.address.clone()) +} + /// Compresses the given data to a gzip format. pub fn compress_to_gzip(data: &[u8]) -> Vec { let mut encoder = GzEncoder::new(Vec::new(), Compression::best()); @@ -742,6 +900,7 @@ pub fn upload_canister_modules(env: &PocketIc, control_panel_id: Principal, cont res.0.unwrap(); // upload station + let station_wasm = get_canister_wasm("station"); let (base_chunk, module_extra_chunks) = upload_canister_chunks_to_asset_canister(env, station_wasm, 500_000); @@ -936,3 +1095,16 @@ pub(crate) fn add_external_canister_call_any_method_permission_and_approval( ) .expect("Failed to add approval policy to call external canister"); } + +pub fn expect_await_call_result(result: WasmResult) -> T +where + T: for<'a> ArgumentDecoder<'a>, +{ + match result { + WasmResult::Reply(vec) => { + let result: T = decode_args(&vec).expect("Failed to decode result"); + result + } + WasmResult::Reject(error) => panic!("Unexpected reject: {error}"), + } +} diff --git a/tools/dfx-orbit/src/me.rs b/tools/dfx-orbit/src/me.rs index d2dc35d85..97db0e04f 100644 --- a/tools/dfx-orbit/src/me.rs +++ b/tools/dfx-orbit/src/me.rs @@ -84,5 +84,7 @@ fn display_privilege(privilege: &UserPrivilege) -> &'static str { UserPrivilege::CreateExternalCanister => "CreateExternalCanister", UserPrivilege::ListExternalCanisters => "ListExternalCanisters", UserPrivilege::CallAnyExternalCanister => "CallAnyExternalCanister", + UserPrivilege::AddAsset => "AddAsset", + UserPrivilege::ListAssets => "ListAssets", } } diff --git a/tools/dfx-orbit/src/review/display.rs b/tools/dfx-orbit/src/review/display.rs index b0a1648d2..1c3d4a0ba 100644 --- a/tools/dfx-orbit/src/review/display.rs +++ b/tools/dfx-orbit/src/review/display.rs @@ -241,6 +241,9 @@ pub(super) fn display_request_operation(op: &RequestOperationDTO) -> &'static st RequestOperationDTO::EditRequestPolicy(_) => "EditRequestPolicy", RequestOperationDTO::RemoveRequestPolicy(_) => "RemoveRequestPolicy", RequestOperationDTO::ManageSystemInfo(_) => "ManageSystemInfo", + RequestOperationDTO::AddAsset(_) => "AddAsset", + RequestOperationDTO::EditAsset(_) => "EditAsset", + RequestOperationDTO::RemoveAsset(_) => "RemoveAsset", } }