From ba3745c7be2bf1674a10b8ddb1e68d0c563748cf Mon Sep 17 00:00:00 2001 From: ardier16 Date: Wed, 20 Mar 2024 17:28:28 +0200 Subject: [PATCH] Update snap structure --- packages/snap/.npmignore | 21 + packages/snap/abis/LightweightStateV2.json | 564 --------- packages/snap/abis/StateV2.json | 945 --------------- packages/snap/package.json | 11 +- packages/snap/snap.manifest.json | 2 +- packages/snap/src/auth-zkp.ts | 127 -- packages/snap/src/config.ts | 70 +- packages/snap/src/const/global-const.ts | 16 - packages/snap/src/const/index.ts | 1 - packages/snap/src/enums/credential-enums.ts | 3 - packages/snap/src/enums/index.ts | 4 +- packages/snap/src/enums/proof-enums.ts | 25 - .../enums/{storage-enums.ts => storage.ts} | 1 + packages/snap/src/helpers/common-helpers.ts | 59 - packages/snap/src/helpers/error-helper.ts | 10 - packages/snap/src/helpers/identity-helpers.ts | 46 - packages/snap/src/helpers/index.ts | 10 +- .../snap/src/helpers/json-query-helpers.ts | 136 --- packages/snap/src/helpers/model-helpers.ts | 83 -- packages/snap/src/helpers/proof-helpers.ts | 593 --------- packages/snap/src/helpers/state-v2-helpers.ts | 211 ---- packages/snap/src/{rpc => helpers}/store.ts | 20 +- packages/snap/src/identity.ts | 139 --- packages/snap/src/index.ts | 460 +------ packages/snap/src/polyfill.ts | 2 +- packages/snap/src/rpc/index.ts | 1 - .../src/types/contracts/LightweightStateV2.ts | 966 --------------- packages/snap/src/types/contracts/StateV2.ts | 1073 ----------------- packages/snap/src/types/contracts/common.ts | 44 - .../factories/LightweightStateV2__factory.ts | 588 --------- .../contracts/factories/StateV2__factory.ts | 966 --------------- .../src/types/contracts/factories/index.ts | 5 - packages/snap/src/types/contracts/index.ts | 8 - packages/snap/src/types/credential-types.ts | 64 - packages/snap/src/types/global-types.ts | 17 - packages/snap/src/types/index.ts | 6 +- packages/snap/src/types/proof-types.ts | 100 -- packages/snap/src/types/state-types.ts | 47 - packages/snap/src/types/storage.ts | 14 + packages/snap/src/typia-generated/is-param.ts | 6 +- packages/snap/src/typia-templates/is-param.ts | 5 +- packages/snap/src/zkp-gen.ts | 555 --------- .../zkp/handlers/CheckCredentialExistence.ts | 62 + .../zkp/handlers/CheckStateContractSync.ts | 15 + .../snap/src/zkp/handlers/CreateIdentity.ts | 94 ++ packages/snap/src/zkp/handlers/CreateProof.ts | 210 ++++ .../snap/src/zkp/handlers/ExportIdentity.ts | 36 + .../snap/src/zkp/handlers/GetCredentials.ts | 22 + packages/snap/src/zkp/handlers/GetIdentity.ts | 22 + .../src/zkp/handlers/RemoveCredentials.ts | 76 ++ .../snap/src/zkp/handlers/SaveCredentials.ts | 97 ++ packages/snap/src/zkp/handlers/index.ts | 9 + .../src/{ => zkp}/helpers/ceramic-helpers.ts | 6 +- .../snap/src/zkp/helpers/common-helpers.ts | 30 + .../{ => zkp}/helpers/credential-helpers.ts | 138 +-- .../src/{ => zkp}/helpers/file-helpers.ts | 13 - .../snap/src/zkp/helpers/identity-helpers.ts | 10 + packages/snap/src/zkp/helpers/index.ts | 5 + packages/snap/src/zkp/index.ts | 1 + .../snap/src/{ => zkp}/types/graphql/index.ts | 0 packages/snap/src/zkp/types/index.ts | 1 + yarn.lock | 11 +- 62 files changed, 856 insertions(+), 8026 deletions(-) delete mode 100644 packages/snap/abis/LightweightStateV2.json delete mode 100644 packages/snap/abis/StateV2.json delete mode 100644 packages/snap/src/auth-zkp.ts delete mode 100644 packages/snap/src/const/global-const.ts delete mode 100644 packages/snap/src/const/index.ts delete mode 100644 packages/snap/src/enums/credential-enums.ts delete mode 100644 packages/snap/src/enums/proof-enums.ts rename packages/snap/src/enums/{storage-enums.ts => storage.ts} (80%) delete mode 100644 packages/snap/src/helpers/common-helpers.ts delete mode 100644 packages/snap/src/helpers/error-helper.ts delete mode 100644 packages/snap/src/helpers/identity-helpers.ts delete mode 100644 packages/snap/src/helpers/json-query-helpers.ts delete mode 100644 packages/snap/src/helpers/model-helpers.ts delete mode 100644 packages/snap/src/helpers/proof-helpers.ts delete mode 100644 packages/snap/src/helpers/state-v2-helpers.ts rename packages/snap/src/{rpc => helpers}/store.ts (68%) delete mode 100644 packages/snap/src/identity.ts delete mode 100644 packages/snap/src/rpc/index.ts delete mode 100644 packages/snap/src/types/contracts/LightweightStateV2.ts delete mode 100644 packages/snap/src/types/contracts/StateV2.ts delete mode 100644 packages/snap/src/types/contracts/common.ts delete mode 100644 packages/snap/src/types/contracts/factories/LightweightStateV2__factory.ts delete mode 100644 packages/snap/src/types/contracts/factories/StateV2__factory.ts delete mode 100644 packages/snap/src/types/contracts/factories/index.ts delete mode 100644 packages/snap/src/types/contracts/index.ts delete mode 100644 packages/snap/src/types/credential-types.ts delete mode 100644 packages/snap/src/types/proof-types.ts delete mode 100644 packages/snap/src/types/state-types.ts create mode 100644 packages/snap/src/types/storage.ts delete mode 100644 packages/snap/src/zkp-gen.ts create mode 100644 packages/snap/src/zkp/handlers/CheckCredentialExistence.ts create mode 100644 packages/snap/src/zkp/handlers/CheckStateContractSync.ts create mode 100644 packages/snap/src/zkp/handlers/CreateIdentity.ts create mode 100644 packages/snap/src/zkp/handlers/CreateProof.ts create mode 100644 packages/snap/src/zkp/handlers/ExportIdentity.ts create mode 100644 packages/snap/src/zkp/handlers/GetCredentials.ts create mode 100644 packages/snap/src/zkp/handlers/GetIdentity.ts create mode 100644 packages/snap/src/zkp/handlers/RemoveCredentials.ts create mode 100644 packages/snap/src/zkp/handlers/SaveCredentials.ts create mode 100644 packages/snap/src/zkp/handlers/index.ts rename packages/snap/src/{ => zkp}/helpers/ceramic-helpers.ts (93%) create mode 100644 packages/snap/src/zkp/helpers/common-helpers.ts rename packages/snap/src/{ => zkp}/helpers/credential-helpers.ts (81%) rename packages/snap/src/{ => zkp}/helpers/file-helpers.ts (52%) create mode 100644 packages/snap/src/zkp/helpers/identity-helpers.ts create mode 100644 packages/snap/src/zkp/helpers/index.ts create mode 100644 packages/snap/src/zkp/index.ts rename packages/snap/src/{ => zkp}/types/graphql/index.ts (100%) create mode 100644 packages/snap/src/zkp/types/index.ts diff --git a/packages/snap/.npmignore b/packages/snap/.npmignore index e69de29b..d328f57f 100644 --- a/packages/snap/.npmignore +++ b/packages/snap/.npmignore @@ -0,0 +1,21 @@ +assets/circuits/credentialAtomicQueryMTPV2/circuit.wasm +assets/circuits/credentialAtomicQueryMTPV2/circuit_final.zkey +assets/circuits/credentialAtomicQueryMTPV2/verification_key.json +assets/circuits/credentialAtomicQuerySigV2/circuit.wasm +assets/circuits/credentialAtomicQuerySigV2/circuit_final.zkey +assets/circuits/credentialAtomicQuerySigV2/verification_key.json +assets/circuits/credentialAtomicQuerySigV2OnChain/circuit.wasm +assets/circuits/credentialAtomicQuerySigV2OnChain/circuit_final.zkey +assets/circuits/credentialAtomicQuerySigV2OnChain/verification_key.json +ceramic +src +.eslintcache +.eslintrc.js +.npmignore +build.js +ceramic-prepare-vc.mjs +codegen.ts +package.json +post-process.js +snap.config.ts +tsconfig.json diff --git a/packages/snap/abis/LightweightStateV2.json b/packages/snap/abis/LightweightStateV2.json deleted file mode 100644 index 53337123..00000000 --- a/packages/snap/abis/LightweightStateV2.json +++ /dev/null @@ -1,564 +0,0 @@ -[ - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "previousAdmin", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "newAdmin", - "type": "address" - } - ], - "name": "AdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "beacon", - "type": "address" - } - ], - "name": "BeaconUpgraded", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint8", - "name": "version", - "type": "uint8" - } - ], - "name": "Initialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "newGistRoot", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "bytes32", - "name": "newIdentitesStatesRoot", - "type": "bytes32" - } - ], - "name": "SignedStateTransited", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "implementation", - "type": "address" - } - ], - "name": "Upgraded", - "type": "event" - }, - { - "inputs": [], - "name": "P", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "signer_", - "type": "address" - }, - { - "internalType": "address", - "name": "sourceStateContract_", - "type": "address" - }, - { - "internalType": "string", - "name": "sourceChainName_", - "type": "string" - }, - { - "internalType": "string", - "name": "chainName_", - "type": "string" - } - ], - "name": "__LightweightStateV2_init", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "signer_", - "type": "address" - }, - { - "internalType": "string", - "name": "chainName_", - "type": "string" - } - ], - "name": "__Signers_init", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "chainName", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "newSignerPubKey_", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "signature_", - "type": "bytes" - } - ], - "name": "changeSigner", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newSourceStateContract_", - "type": "address" - }, - { - "internalType": "bytes", - "name": "signature_", - "type": "bytes" - } - ], - "name": "changeSourceStateContract", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "methodId_", - "type": "uint8" - }, - { - "internalType": "address", - "name": "contractAddress_", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "signHash_", - "type": "bytes32" - }, - { - "internalType": "bytes", - "name": "signature_", - "type": "bytes" - } - ], - "name": "checkSignatureAndIncrementNonce", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "getCurrentGISTRootInfo", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - } - ], - "internalType": "struct ILightweightStateV2.GistRootData", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getGISTRoot", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "root_", - "type": "uint256" - } - ], - "name": "getGISTRootInfo", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - } - ], - "internalType": "struct ILightweightStateV2.GistRootData", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "root_", - "type": "bytes32" - } - ], - "name": "getIdentitiesStatesRootData", - "outputs": [ - { - "components": [ - { - "internalType": "bytes32", - "name": "root", - "type": "bytes32" - }, - { - "internalType": "uint256", - "name": "setTimestamp", - "type": "uint256" - } - ], - "internalType": "struct ILightweightStateV2.IdentitiesStatesRootData", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "methodId_", - "type": "uint8" - }, - { - "internalType": "address", - "name": "contractAddress_", - "type": "address" - } - ], - "name": "getSigComponents", - "outputs": [ - { - "internalType": "string", - "name": "chainName_", - "type": "string" - }, - { - "internalType": "uint256", - "name": "nonce_", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "identitiesStatesRoot", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "root_", - "type": "bytes32" - } - ], - "name": "isIdentitiesStatesRootExists", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - }, - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "name": "nonces", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "proxiableUUID", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "newIdentitiesStatesRoot_", - "type": "bytes32" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - } - ], - "internalType": "struct ILightweightStateV2.GistRootData", - "name": "gistData_", - "type": "tuple" - }, - { - "internalType": "bytes", - "name": "proof_", - "type": "bytes" - } - ], - "name": "signedTransitState", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "signer", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "sourceChainName", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "sourceStateContract", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newImplementation", - "type": "address" - } - ], - "name": "upgradeTo", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newImplementation", - "type": "address" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "name": "upgradeToAndCall", - "outputs": [], - "stateMutability": "payable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newImplementation_", - "type": "address" - }, - { - "internalType": "bytes", - "name": "signature_", - "type": "bytes" - } - ], - "name": "upgradeToWithSig", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "methodId_", - "type": "uint8" - }, - { - "internalType": "address", - "name": "contractAddress_", - "type": "address" - }, - { - "internalType": "address", - "name": "newAddress_", - "type": "address" - }, - { - "internalType": "bytes", - "name": "signature_", - "type": "bytes" - } - ], - "name": "validateChangeAddressSignature", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/packages/snap/abis/StateV2.json b/packages/snap/abis/StateV2.json deleted file mode 100644 index 275db6bb..00000000 --- a/packages/snap/abis/StateV2.json +++ /dev/null @@ -1,945 +0,0 @@ -[ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint8", - "name": "version", - "type": "uint8" - } - ], - "name": "Initialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferStarted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "inputs": [], - "name": "VERSION", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "acceptOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - } - ], - "name": "getGISTProof", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "existence", - "type": "bool" - }, - { - "internalType": "uint256[64]", - "name": "siblings", - "type": "uint256[64]" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "auxExistence", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "auxIndex", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "auxValue", - "type": "uint256" - } - ], - "internalType": "struct IState.GistProof", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "blockNumber", - "type": "uint256" - } - ], - "name": "getGISTProofByBlock", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "existence", - "type": "bool" - }, - { - "internalType": "uint256[64]", - "name": "siblings", - "type": "uint256[64]" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "auxExistence", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "auxIndex", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "auxValue", - "type": "uint256" - } - ], - "internalType": "struct IState.GistProof", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - } - ], - "name": "getGISTProofByRoot", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "existence", - "type": "bool" - }, - { - "internalType": "uint256[64]", - "name": "siblings", - "type": "uint256[64]" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "auxExistence", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "auxIndex", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "auxValue", - "type": "uint256" - } - ], - "internalType": "struct IState.GistProof", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "timestamp", - "type": "uint256" - } - ], - "name": "getGISTProofByTime", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "existence", - "type": "bool" - }, - { - "internalType": "uint256[64]", - "name": "siblings", - "type": "uint256[64]" - }, - { - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "auxExistence", - "type": "bool" - }, - { - "internalType": "uint256", - "name": "auxIndex", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "auxValue", - "type": "uint256" - } - ], - "internalType": "struct IState.GistProof", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getGISTRoot", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "start", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "length", - "type": "uint256" - } - ], - "name": "getGISTRootHistory", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByRoot", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.GistRootInfo[]", - "name": "", - "type": "tuple[]" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getGISTRootHistoryLength", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - } - ], - "name": "getGISTRootInfo", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByRoot", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.GistRootInfo", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "blockNumber", - "type": "uint256" - } - ], - "name": "getGISTRootInfoByBlock", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByRoot", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.GistRootInfo", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "timestamp", - "type": "uint256" - } - ], - "name": "getGISTRootInfoByTime", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "root", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByRoot", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.GistRootInfo", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - } - ], - "name": "getStateInfoById", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "state", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByState", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.StateInfo", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "state", - "type": "uint256" - } - ], - "name": "getStateInfoByIdAndState", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "state", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByState", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.StateInfo", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "startIndex", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "length", - "type": "uint256" - } - ], - "name": "getStateInfoHistoryById", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "state", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedByState", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtTimestamp", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "createdAtBlock", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "replacedAtBlock", - "type": "uint256" - } - ], - "internalType": "struct IState.StateInfo[]", - "name": "", - "type": "tuple[]" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - } - ], - "name": "getStateInfoHistoryLengthById", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getVerifier", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - } - ], - "name": "idExists", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "contract IStateTransitionVerifier", - "name": "verifierContractAddr", - "type": "address" - } - ], - "name": "initialize", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "pendingOwner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newVerifierAddr", - "type": "address" - } - ], - "name": "setVerifier", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "state", - "type": "uint256" - } - ], - "name": "stateExists", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "oldState", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "newState", - "type": "uint256" - }, - { - "internalType": "bool", - "name": "isOldStateGenesis", - "type": "bool" - }, - { - "internalType": "uint256[2]", - "name": "a", - "type": "uint256[2]" - }, - { - "internalType": "uint256[2][2]", - "name": "b", - "type": "uint256[2][2]" - }, - { - "internalType": "uint256[2]", - "name": "c", - "type": "uint256[2]" - } - ], - "name": "transitState", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/packages/snap/package.json b/packages/snap/package.json index c9e91f13..63f7f2f8 100644 --- a/packages/snap/package.json +++ b/packages/snap/package.json @@ -7,14 +7,6 @@ "url": "https://github.com/rarimo/rarime.git" }, "license": "(MIT-0 OR Apache-2.0)", - "files": [ - "dist/", - "images/", - "assets/circuits/auth", - "assets/circuits/credentialAtomicQueryMTPV2OnChain", - "snap.manifest.json", - "README.md" - ], "scripts": { "build": "yarn clean && node build.js && yarn build:post && yarn bundle:eval && yarn bundle:manifest", "build:clean": "yarn clean && yarn build", @@ -54,6 +46,7 @@ "@metamask/snaps-sdk": "^2.0.0", "@metamask/snaps-utils": "^6.0.0", "@rarimo/rarime-connector": "workspace:^", + "@rarimo/zkp-iden3": "workspace:^", "buffer": "6.0.3", "dids": "4.0.4", "ethers": "5.7.2", @@ -77,7 +70,6 @@ "@lavamoat/allow-scripts": "2.0.3", "@metamask/auto-changelog": "^3.4.4", "@metamask/snaps-cli": "^5.0.0", - "@typechain/ethers-v5": "11.1.1", "@types/intl": "1.2.0", "@types/lodash": "^4.14.202", "@types/uuid": "9.0.2", @@ -86,7 +78,6 @@ "nodemon": "2.0.20", "npm-commands": "^1.2.1", "rimraf": "3.0.2", - "typechain": "8.3.1", "typescript": "4.7.4" }, "packageManager": "yarn@3.2.1", diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index 33a87e5b..4397fc19 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/rarimo/rarime.git" }, "source": { - "shasum": "VsbqJ49GpnFK4HlpC6cpBsL/fS+W6w9C27wrH2tQv4E=", + "shasum": "MghGYJgzXVJ+OdrFj238GNbtfkh7svKE+NFqnjl3rW4=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/snap/src/auth-zkp.ts b/packages/snap/src/auth-zkp.ts deleted file mode 100644 index 08d72596..00000000 --- a/packages/snap/src/auth-zkp.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { fromBigEndian } from '@iden3/js-iden3-core'; -import { proving, Token } from '@iden3/js-jwz'; -import * as uuid from 'uuid'; - -import { config } from './config'; -import { defaultMTLevels, defaultMTLevelsOnChain } from './const'; -import { - getGISTProof, - getNodeAuxValue, - getProviderChainInfo, - getRarimoEvmRpcUrl, - getRarimoStateContractAddress, - getFileBytes, - prepareSiblingsStr, - toGISTProof, -} from './helpers'; -import type { Identity } from './identity'; -import type { W3CCredential, SaveCredentialsRequestParams } from './types'; - -export class AuthZkp { - identity: Identity = {} as Identity; - - offer: SaveCredentialsRequestParams = {} as SaveCredentialsRequestParams; - - verifiableCredentials: W3CCredential[] = []; - - constructor(identity: Identity, offer: SaveCredentialsRequestParams) { - this.identity = identity; - this.offer = offer; - } - - async getVerifiableCredentials(): Promise { - const credentials: W3CCredential[] = []; - - for (let index = 0; index < this.offer.body.Credentials.length; index++) { - const guid = uuid.v4(); - - const claimDetails = { - id: this.offer?.id ?? guid, - typ: this.offer?.typ || 'application/iden3-zkp-json', - type: 'https://iden3-communication.io/credentials/1.0/fetch-request', - threadID: this.offer?.threadID ?? guid, - body: { - id: this.offer?.body.Credentials[index].id, - }, - from: this.offer.to, - to: this.offer.from, - }; - - const token2 = new Token( - proving.provingMethodGroth16AuthV2Instance, - JSON.stringify(claimDetails), - this.#prepareInputs.bind(this), - ); - - const [wasm, provingKey] = await Promise.all([ - getFileBytes(config.CIRCUIT_AUTH_WASM_URL), - getFileBytes(config.CIRCUIT_AUTH_FINAL_KEY_URL), - ]); - - const jwzTokenRaw = await token2.prove(provingKey, wasm); - - const resp = await fetch(this.offer.body.url, { - method: 'post', - body: jwzTokenRaw, - }); - - if (resp.status !== 200) { - throw new Error( - `could not fetch W3C credential, ${this.offer?.body.Credentials[index].id}`, - ); - } - const data = await resp.json(); - - credentials.push(data.body.credential); - } - this.verifiableCredentials = credentials; - - return credentials; - } - - async #prepareInputs(messageHash: Uint8Array): Promise { - const messageHashBigInt = fromBigEndian(messageHash); - - const providerChainInfo = await getProviderChainInfo(); - - const signature = this.identity.privateKey.signPoseidon(messageHashBigInt); - const gistInfo = await getGISTProof({ - rpcUrl: getRarimoEvmRpcUrl(providerChainInfo.id), - contractAddress: getRarimoStateContractAddress(providerChainInfo.id), - userId: this.identity.identityIdBigIntString, - }); - - const gistProof = toGISTProof(gistInfo); - const globalNodeAux = getNodeAuxValue(gistProof.proof); - const nodeAuxAuth = getNodeAuxValue(this.identity.authClaimNonRevProof); - - const preparedInputs = { - authClaim: this.identity.coreAuthClaim.marshalJson(), - authClaimIncMtp: this.identity.authClaimIncProofSiblings, - authClaimNonRevMtp: prepareSiblingsStr( - this.identity.authClaimNonRevProof, - defaultMTLevels, - ), - authClaimNonRevMtpAuxHi: nodeAuxAuth.key.string(), - authClaimNonRevMtpAuxHv: nodeAuxAuth.value.string(), - authClaimNonRevMtpNoAux: nodeAuxAuth.noAux, - challenge: messageHashBigInt.toString(), - challengeSignatureR8x: signature.R8[0].toString(), - challengeSignatureR8y: signature.R8[1].toString(), - challengeSignatureS: signature.S.toString(), - claimsTreeRoot: this.identity.treeState.claimsRoot, - genesisID: this.identity.identityIdBigIntString, - revTreeRoot: this.identity.treeState.revocationRoot, - rootsTreeRoot: this.identity.treeState.rootOfRoots, - state: this.identity.treeState.state, - profileNonce: '0', - gistRoot: gistProof.root.string(), - gistMtp: prepareSiblingsStr(gistProof.proof, defaultMTLevelsOnChain), - gistMtpAuxHi: globalNodeAux?.key.string(), - gistMtpAuxHv: globalNodeAux?.value.string(), - gistMtpNoAux: globalNodeAux.noAux, - }; - - return new TextEncoder().encode(JSON.stringify(preparedInputs)); - } -} diff --git a/packages/snap/src/config.ts b/packages/snap/src/config.ts index 7310bb9a..e06bb4a0 100644 --- a/packages/snap/src/config.ts +++ b/packages/snap/src/config.ts @@ -1,4 +1,4 @@ -import type { ChainInfo } from './types'; +import type { ChainZkpInfo } from '@rarimo/rarime-connector'; export const config = { AUTH_BJJ_CREDENTIAL_HASH: 'cca3371a6cb1b715004407e325bd993c', @@ -50,41 +50,71 @@ enum CHAINS { Goerly = 5, } -export const SUPPORTED_CHAINS: Record = { +export const SUPPORTED_CHAINS: Record = { [CHAINS.Polygon]: { - id: CHAINS.Polygon, - rpcUrl: 'https://polygon-rpc.com', - stateContractAddress: '0xf9bA419ad9c82451d31d89917db61253a1e46B3C', + targetChainId: CHAINS.Polygon, + targetRpcUrl: 'https://polygon-rpc.com', + targetStateContractAddress: '0xf9bA419ad9c82451d31d89917db61253a1e46B3C', + + rarimoApiUrl: config.RARIMO_CORE_URL.mainnet, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.mainnet, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.mainnet, + rarimoNetworkType: 'mainnet', }, [CHAINS.EthereumMainet]: { - id: CHAINS.EthereumMainet, - rpcUrl: 'https://eth.llamarpc.com', - stateContractAddress: '0xB11D49e873A1B4a8c54520A9b6a3c8E017AfE7BB', + targetChainId: CHAINS.EthereumMainet, + targetRpcUrl: 'https://eth.llamarpc.com', + targetStateContractAddress: '0xB11D49e873A1B4a8c54520A9b6a3c8E017AfE7BB', + + rarimoApiUrl: config.RARIMO_CORE_URL.mainnet, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.mainnet, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.mainnet, + rarimoNetworkType: 'mainnet', }, [CHAINS.Bsc]: { - id: CHAINS.Bsc, - rpcUrl: 'https://bsc-dataseed.binance.org', - stateContractAddress: '0xF3e2491627b9eF3816A4143010B39B2B67F33E55', + targetChainId: CHAINS.Bsc, + targetRpcUrl: 'https://bsc-dataseed.binance.org', + targetStateContractAddress: '0xF3e2491627b9eF3816A4143010B39B2B67F33E55', + + rarimoApiUrl: config.RARIMO_CORE_URL.mainnet, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.mainnet, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.mainnet, + rarimoNetworkType: 'mainnet', }, [CHAINS.Avalance]: { - id: CHAINS.Avalance, - rpcUrl: 'https://avax.meowrpc.com', - stateContractAddress: '0xF3e2491627b9eF3816A4143010B39B2B67F33E55', + targetChainId: CHAINS.Avalance, + targetRpcUrl: 'https://avax.meowrpc.com', + targetStateContractAddress: '0xF3e2491627b9eF3816A4143010B39B2B67F33E55', + + rarimoApiUrl: config.RARIMO_CORE_URL.mainnet, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.mainnet, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.mainnet, + rarimoNetworkType: 'mainnet', }, [CHAINS.Sepolia]: { - id: CHAINS.Sepolia, - rpcUrl: 'https://endpoints.omniatech.io/v1/eth/sepolia/public', - stateContractAddress: '0x8a9F505bD8a22BF09b0c19F65C17426cd33f3912', + targetChainId: CHAINS.Sepolia, + targetRpcUrl: 'https://endpoints.omniatech.io/v1/eth/sepolia/public', + targetStateContractAddress: '0x8a9F505bD8a22BF09b0c19F65C17426cd33f3912', + + rarimoApiUrl: config.RARIMO_CORE_URL.beta, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.beta, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.beta, + rarimoNetworkType: 'beta', }, [CHAINS.Goerly]: { - id: CHAINS.Goerly, - rpcUrl: 'https://ethereum-goerli.publicnode.com', - stateContractAddress: '0x0F08e8EA245E63F2090Bf3fF3772402Da9c047ee', + targetChainId: CHAINS.Goerly, + targetRpcUrl: 'https://ethereum-goerli.publicnode.com', + targetStateContractAddress: '0x0F08e8EA245E63F2090Bf3fF3772402Da9c047ee', + + rarimoApiUrl: config.RARIMO_CORE_URL.beta, + rarimoEvmRpcApiUrl: config.RARIMO_EVM_RPC_URL.beta, + rarimoStateContractAddress: config.RARIMO_STATE_CONTRACT_ADDRESS.beta, + rarimoNetworkType: 'beta', }, }; diff --git a/packages/snap/src/const/global-const.ts b/packages/snap/src/const/global-const.ts deleted file mode 100644 index 73494818..00000000 --- a/packages/snap/src/const/global-const.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Operators } from '../enums'; - -export const defaultMTLevels = 40; // max MT levels, default value for identity circuits -export const defaultValueArraySize = 64; // max value array size, default value for identity circuits -export const defaultMTLevelsOnChain = 64; // max MT levels on chain, default value for identity circuits -export const defaultMTLevelsClaimsMerklization = 32; // max MT levels of JSON-LD merklization on claim - -export const QueryOperators = { - $noop: Operators.NOOP, - $eq: Operators.EQ, - $lt: Operators.LT, - $gt: Operators.GT, - $in: Operators.IN, - $nin: Operators.NIN, - $ne: Operators.NE, -}; diff --git a/packages/snap/src/const/index.ts b/packages/snap/src/const/index.ts deleted file mode 100644 index fc0c5837..00000000 --- a/packages/snap/src/const/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './global-const'; diff --git a/packages/snap/src/enums/credential-enums.ts b/packages/snap/src/enums/credential-enums.ts deleted file mode 100644 index 41dd2df5..00000000 --- a/packages/snap/src/enums/credential-enums.ts +++ /dev/null @@ -1,3 +0,0 @@ -export enum JSONLDSchemas { - Iden3Credential = 'https://schema.iden3.io/core/jsonld/iden3proofs.jsonld', -} diff --git a/packages/snap/src/enums/index.ts b/packages/snap/src/enums/index.ts index b8ae5099..85674ee7 100644 --- a/packages/snap/src/enums/index.ts +++ b/packages/snap/src/enums/index.ts @@ -1,3 +1 @@ -export * from './storage-enums'; -export * from './proof-enums'; -export * from './credential-enums'; +export * from './storage'; diff --git a/packages/snap/src/enums/proof-enums.ts b/packages/snap/src/enums/proof-enums.ts deleted file mode 100644 index 2a106541..00000000 --- a/packages/snap/src/enums/proof-enums.ts +++ /dev/null @@ -1,25 +0,0 @@ -export enum CircuitId { - // AtomicQueryMTPV2 is a type for credentialAtomicQueryMTPV2.circom - AtomicQueryMTPV2 = 'credentialAtomicQueryMTPV2', - // AtomicQueryMTPV2OnChain is a type for credentialAtomicQueryMTPV2OnChain.circom - AtomicQueryMTPV2OnChain = 'credentialAtomicQueryMTPV2OnChain', - // AtomicQuerySig is a type for credentialAttrQuerySig.circom - AtomicQuerySigV2 = 'credentialAtomicQuerySigV2', - // AtomicQuerySigOnChain is a type for credentialAtomicQuerySigOnChain.circom - AtomicQuerySigV2OnChain = 'credentialAtomicQuerySigV2OnChain', -} - -export enum ProofType { - BJJSignature = 'BJJSignature2021', - Iden3SparseMerkleTreeProof = 'Iden3SparseMerkleTreeProof', -} - -export enum Operators { - NOOP = 0, // No operation, skip query verification in circuit - EQ = 1, - LT = 2, - GT = 3, - IN = 4, - NIN = 5, - NE = 6, -} diff --git a/packages/snap/src/enums/storage-enums.ts b/packages/snap/src/enums/storage.ts similarity index 80% rename from packages/snap/src/enums/storage-enums.ts rename to packages/snap/src/enums/storage.ts index 8a8dbcd8..7e8e02a4 100644 --- a/packages/snap/src/enums/storage-enums.ts +++ b/packages/snap/src/enums/storage.ts @@ -1,4 +1,5 @@ export enum StorageKeys { identity = 'identity', credentials = 'credentials', + chains = 'chains', } diff --git a/packages/snap/src/helpers/common-helpers.ts b/packages/snap/src/helpers/common-helpers.ts deleted file mode 100644 index 583503a4..00000000 --- a/packages/snap/src/helpers/common-helpers.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { providers } from 'ethers'; - -import { config, HOSTNAMES_WHITELIST, SUPPORTED_CHAINS } from '../config'; -import type { ChainInfo } from '../types'; - -export const getChainInfo = (chainId: number): ChainInfo => { - const chainInfo = SUPPORTED_CHAINS[chainId]; - if (!chainInfo) { - throw new Error(`ChainId ${chainId} not supported`); - } - - return chainInfo; -}; - -export const getProviderChainInfo = async (): Promise => { - const provider = new providers.Web3Provider( - ethereum as any as providers.ExternalProvider, - ); - const network = await provider.getNetwork(); - - return getChainInfo(network.chainId); -}; - -export const getRarimoEvmRpcUrl = (chainId: number) => { - return config.RARIMO_EVM_RPC_URL[SUPPORTED_CHAINS[chainId].rarimoNetworkType]; -}; - -export const getRarimoCoreUrl = (chainId: number) => { - return config.RARIMO_CORE_URL[SUPPORTED_CHAINS[chainId].rarimoNetworkType]; -}; - -export const getRarimoStateContractAddress = (chainId: number) => { - return config.RARIMO_STATE_CONTRACT_ADDRESS[ - SUPPORTED_CHAINS[chainId].rarimoNetworkType - ]; -}; - -export const getHostname = (origin: string): string => { - return new URL(origin).hostname; -}; - -export const isOriginInWhitelist = (origin: string) => { - return HOSTNAMES_WHITELIST.includes(getHostname(origin)); -}; - -export const uniqBy = (arr: any[], predicate: string) => { - return [ - ...arr - .reduce((map, item) => { - const key = - item === null || item === undefined ? item : item[predicate]; - - map.has(key) || map.set(key, item); - - return map; - }, new Map()) - .values(), - ]; -}; diff --git a/packages/snap/src/helpers/error-helper.ts b/packages/snap/src/helpers/error-helper.ts deleted file mode 100644 index 7f11840e..00000000 --- a/packages/snap/src/helpers/error-helper.ts +++ /dev/null @@ -1,10 +0,0 @@ -export class FetcherError extends Error { - public name = 'FetcherError'; - - public response: Response; - - constructor(resp: Response) { - super(); - this.response = resp; - } -} diff --git a/packages/snap/src/helpers/identity-helpers.ts b/packages/snap/src/helpers/identity-helpers.ts deleted file mode 100644 index 61194b2b..00000000 --- a/packages/snap/src/helpers/identity-helpers.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { Hex, PrivateKey } from '@iden3/js-crypto'; -import { DID } from '@iden3/js-iden3-core'; - -export const initPrivateKey = (hexString?: string): string => { - let arr; - if (hexString) { - arr = Hex.decodeString(hexString); - } else { - arr = new Uint8Array(32); - window.crypto.getRandomValues(arr); - - return initPrivateKey(new PrivateKey(arr).hex()); - } - return new PrivateKey(arr).hex(); -}; - -export const parseDidV2 = (did: string): DID => { - const splitted = did.split(':'); - - return DID.parse(`did:iden3:readonly:${splitted[splitted.length - 1]}`); -}; - -export const isDidSupported = (identityId: string): boolean => { - try { - const parsed = DID.parse(identityId); - - const id = DID.idFromDID(parsed); - - const parts = DID.decodePartsFromId(id); - - return !DID.isUnsupported(parts.method, parts.blockchain, parts.networkId); - } catch (error) { - return false; - } -}; - -export const genPkHexFromEntropy = async (salt?: string) => { - const entropy = await snap.request({ - method: 'snap_getEntropy', - params: { - version: 1, - ...(salt ? { salt } : {}), - }, - }); - return entropy.startsWith('0x') ? entropy.substring(2) : entropy; -}; diff --git a/packages/snap/src/helpers/index.ts b/packages/snap/src/helpers/index.ts index d76fea4a..d4068169 100644 --- a/packages/snap/src/helpers/index.ts +++ b/packages/snap/src/helpers/index.ts @@ -1,9 +1 @@ -export * from './identity-helpers'; -export * from './file-helpers'; -export * from './state-v2-helpers'; -export * from './credential-helpers'; -export * from './json-query-helpers'; -export * from './proof-helpers'; -export * from './model-helpers'; -export * from './common-helpers'; -export * from './ceramic-helpers'; +export * from './store'; diff --git a/packages/snap/src/helpers/json-query-helpers.ts b/packages/snap/src/helpers/json-query-helpers.ts deleted file mode 100644 index 80cbe9e3..00000000 --- a/packages/snap/src/helpers/json-query-helpers.ts +++ /dev/null @@ -1,136 +0,0 @@ -/* eslint-disable @typescript-eslint/no-parameter-properties */ -import type { ProofQuery } from '@rarimo/rarime-connector'; - -import type { W3CCredential } from '../types'; - -export enum SearchError { - NotDefinedQueryKey = 'not defined query key', - NotDefinedComparator = 'not defined comparator', -} - -export type FilterOperatorMethod = - | '$noop' - | '$eq' - | '$in' - | '$nin' - | '$gt' - | '$lt' - | '$ne'; - -export type FilterOperatorFunction = (a: any, b: any) => boolean; - -const comparatorOptions: { - [v in FilterOperatorMethod]: FilterOperatorFunction; -} = { - $noop: () => true, - $eq: (a, b) => a === b, - $in: (a: string, b: string[]) => b.includes(a), - $nin: (a: string, b: string[]) => !b.includes(a), - $gt: (a: number, b: number) => a > b, - $lt: (a: number, b: number) => a < b, - $ne: (a, b) => a !== b, -}; - -type PathObject = { [key: string]: any }; - -export const resolvePath = ( - object: PathObject, - path: string, - defaultValue = null, -) => path.split('.').reduce((o, p) => (o ? o[p] : defaultValue), object); - -export class FilterQuery { - constructor( - public path: string, - public operatorFunc: FilterOperatorFunction, - public value: any, - public isReverseParams = false, - ) {} - - execute(credential: W3CCredential): boolean { - if (!this.operatorFunc) { - throw new Error(SearchError.NotDefinedComparator); - } - const credentialPathValue = resolvePath(credential, this.path); - if (credentialPathValue === null || credentialPathValue === undefined) { - return false; - } - - if (this.isReverseParams) { - return this.operatorFunc(this.value, credentialPathValue); - } - return this.operatorFunc(credentialPathValue, this.value); - } -} - -export const StandardJSONCredentialsQueryFilter = ( - query: ProofQuery, -): FilterQuery[] => { - return Object.keys(query).reduce((acc: FilterQuery[], queryKey) => { - const queryValue = query[queryKey as keyof ProofQuery]; - switch (queryKey) { - case 'claimId': - return acc.concat( - new FilterQuery('id', comparatorOptions.$eq, queryValue), - ); - case 'allowedIssuers': { - const [first] = (queryValue as string[]) ?? []; - if (first && first === '*') { - return acc; - } - return acc.concat( - new FilterQuery('issuer', comparatorOptions.$in, queryValue), - ); - } - case 'type': - return acc.concat( - new FilterQuery('type', comparatorOptions.$in, queryValue, true), - ); - case 'context': - return acc.concat( - new FilterQuery('@context', comparatorOptions.$in, queryValue, true), - ); - case 'credentialSubjectId': - return acc.concat( - new FilterQuery( - 'credentialSubject.id', - comparatorOptions.$eq, - queryValue, - ), - ); - case 'schema': - return acc.concat( - new FilterQuery( - 'credentialSchema.id', - comparatorOptions.$eq, - queryValue, - ), - ); - case 'skipClaimRevocationCheck': - return acc; - case 'credentialSubject': { - const queryVal = queryValue as { [key: string]: any }; - const reqFilters = Object.keys(queryVal).reduce( - (arr: FilterQuery[], fieldKey) => { - const fieldParams = queryVal[fieldKey]; - const res = Object.keys(fieldParams).map((comparator) => { - const value = fieldParams[comparator]; - const path = `credentialSubject.${fieldKey}`; - return new FilterQuery( - path, - comparatorOptions[comparator as FilterOperatorMethod], - value, - ); - }); - return arr.concat(res); - }, - [], - ); - - return acc.concat(reqFilters); - } - default: - throw new Error(SearchError.NotDefinedQueryKey); - } - }, []); -}; diff --git a/packages/snap/src/helpers/model-helpers.ts b/packages/snap/src/helpers/model-helpers.ts deleted file mode 100644 index d656e355..00000000 --- a/packages/snap/src/helpers/model-helpers.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type { Claim as CoreClaim, Id } from '@iden3/js-iden3-core'; -import { Proof } from '@iden3/js-merkletree'; - -import type { ProofType } from '../enums'; -import type { - BJJSignatureProof, - CredentialStatus, - State, - TreeState, -} from '../types'; - -export class IssuerData { - id!: string; - - state!: State; - - authCoreClaim?: string; - - mtp?: Proof; - - credentialStatus?: CredentialStatus; - - updateUrl!: string; -} - -export class Iden3SparseMerkleTreeProof { - type!: ProofType; - - issuerData!: IssuerData; - - mtp!: Proof; - - coreClaim!: string; - - id!: string; -} - -export class BJJSignatureProof2021 { - type!: ProofType; - - issuerData!: IssuerData; - - signature!: string; - - coreClaim!: string; -} - -export class CircuitClaim { - issuerId!: Id; - - claim!: CoreClaim; - - signatureProof!: BJJSignatureProof; - - incProof!: { - proof: Proof; - treeState: TreeState; - }; -} - -export class ValueProof { - path: bigint; - - value?: bigint; - - mtp: Proof; - - constructor() { - this.path = BigInt(0); - this.value = BigInt(0); - this.mtp = new Proof(); - } -} - -export class Query { - slotIndex!: number; - - values!: bigint[]; - - operator!: number; - - valueProof?: ValueProof; -} diff --git a/packages/snap/src/helpers/proof-helpers.ts b/packages/snap/src/helpers/proof-helpers.ts deleted file mode 100644 index 0b47d24e..00000000 --- a/packages/snap/src/helpers/proof-helpers.ts +++ /dev/null @@ -1,593 +0,0 @@ -/* eslint-disable camelcase */ -/* eslint-disable @typescript-eslint/prefer-for-of */ -import { Hex, Signature } from '@iden3/js-crypto'; -import { - Claim, - DID, - fromLittleEndian, - MerklizedRootPosition, -} from '@iden3/js-iden3-core'; -import type { MtValue } from '@iden3/js-jsonld-merklization'; -import { - getDocumentLoader, - Merklizer, - Path, -} from '@iden3/js-jsonld-merklization'; -import { - newHashFromBigInt, - newHashFromHex, - Proof, - ZERO_HASH, -} from '@iden3/js-merkletree'; -import type { Hash, NodeAux } from '@iden3/js-merkletree'; -import type { ProofQuery } from '@rarimo/rarime-connector'; - -import { getRevocationStatus, loadDataByUrl } from './credential-helpers'; -import { parseDidV2 } from './identity-helpers'; -import { - BJJSignatureProof2021, - CircuitClaim, - Iden3SparseMerkleTreeProof, - Query, - ValueProof, -} from './model-helpers'; -import { QueryOperators } from '../const'; -import { ProofType } from '../enums'; -import type { - GISTProof, - JSONSchema, - MTProof, - NodeAuxValue, - QueryWithFieldName, - RevocationStatus, - StateProof, - TreeState, - W3CCredential, -} from '../types'; - -export const extractProof = (proof: { - [key: string]: any; -}): { claim: Claim; proofType: ProofType } => { - if (proof instanceof Iden3SparseMerkleTreeProof) { - return { - claim: new Claim().fromHex(proof.coreClaim), - proofType: ProofType.Iden3SparseMerkleTreeProof, - }; - } - - if (proof instanceof BJJSignatureProof2021) { - return { - claim: new Claim().fromHex(proof.coreClaim), - proofType: ProofType.BJJSignature, - }; - } - - if (typeof proof === 'object') { - const defaultProofType = proof.type; - if (!defaultProofType) { - throw new Error('proof type is not specified'); - } - const coreClaimHex = proof.coreClaim; - if (!coreClaimHex) { - throw new Error( - `coreClaim field is not defined in proof type ${defaultProofType}`, - ); - } - return { - claim: new Claim().fromHex(coreClaimHex), - proofType: defaultProofType as ProofType, - }; - } - - throw new Error('proof format is not supported'); -}; - -export const getCoreClaimFromProof = ( - credentialProof: object | any[], - proofType: ProofType, -): Claim | null => { - if (Array.isArray(credentialProof)) { - for (const proof of credentialProof) { - const { claim, proofType: extractedProofType } = extractProof(proof); - if (proofType === extractedProofType) { - return claim; - } - } - } else if (typeof credentialProof === 'object') { - const { claim, proofType: extractedProofType } = - extractProof(credentialProof); - if (extractedProofType === proofType) { - return claim; - } - } - return null; -}; - -export const getBJJSignature2021Proof = ( - credentialProof: object | any[], -): BJJSignatureProof2021 | null => { - const proofType: ProofType = ProofType.BJJSignature; - if (Array.isArray(credentialProof)) { - for (const proof of credentialProof) { - const { proofType: extractedProofType } = extractProof(proof); - if (proofType === extractedProofType) { - return proof as BJJSignatureProof2021; - } - } - } else if (typeof credentialProof === 'object') { - const { proofType: extractedProofType } = extractProof(credentialProof); - if (extractedProofType === proofType) { - return credentialProof as BJJSignatureProof2021; - } - } - return null; -}; - -export const getIden3SparseMerkleTreeProof = ( - credentialProof: object | any[], -): Iden3SparseMerkleTreeProof | null => { - const proofType: ProofType = ProofType.Iden3SparseMerkleTreeProof; - if (Array.isArray(credentialProof)) { - for (const proof of credentialProof) { - const { proofType: extractedProofType } = extractProof(proof); - if (proofType === extractedProofType) { - return proof as Iden3SparseMerkleTreeProof; - } - } - } else if (typeof credentialProof === 'object') { - const { proofType: extractedProofType } = extractProof(credentialProof); - if (extractedProofType === proofType) { - return credentialProof as Iden3SparseMerkleTreeProof; - } - } - return null; -}; - -export const buildTreeState = ( - state: string, - claimsTreeRoot: string, - revocationTreeRoot: string, - rootOfRoots: string, -): TreeState => ({ - state: newHashFromHex(state), - claimsRoot: newHashFromHex(claimsTreeRoot), - revocationRoot: newHashFromHex(revocationTreeRoot), - rootOfRoots: newHashFromHex(rootOfRoots), -}); - -export const convertEndianSwappedCoreStateHashHex = (hash: string) => { - const convertedStateHash = fromLittleEndian( - Hex.decodeString(hash.slice(2)), - ).toString(16); - - return convertedStateHash?.length < 64 - ? `0x0${convertedStateHash}` - : `0x${convertedStateHash}`; -}; - -export const newCircuitClaimData = async ( - credential: W3CCredential, - coreClaim: Claim, - coreStateHash: string, -): Promise => { - const circuitClaim = new CircuitClaim(); - circuitClaim.claim = coreClaim; - - const issuerDid = parseDidV2(credential.issuer); - - circuitClaim.issuerId = DID.idFromDID(issuerDid); - - const smtProof = getIden3SparseMerkleTreeProof(credential.proof!); - - if (smtProof) { - const data = await loadDataByUrl( - smtProof.id, - convertEndianSwappedCoreStateHashHex(coreStateHash), - ); - - circuitClaim.incProof = { - proof: data.mtp, - treeState: buildTreeState( - data.issuer.state, - data.issuer.claimsTreeRoot, - data.issuer.revocationTreeRoot, - data.issuer.rootOfRoots, - ), - }; - } - - const sigProof = getBJJSignature2021Proof(credential.proof!); - - if (sigProof) { - const decodedSignature = Hex.decodeString(sigProof.signature); - const signature = Signature.newFromCompressed(decodedSignature); - const issuerAuthClaimIncMtp = await loadDataByUrl( - sigProof.issuerData.updateUrl, - convertEndianSwappedCoreStateHashHex(coreStateHash), - ); - const rs: RevocationStatus = await getRevocationStatus( - sigProof.issuerData.credentialStatus!, - ); - - const issuerAuthNonRevProof: MTProof = { - treeState: buildTreeState( - rs.issuer.state!, - rs.issuer.claimsTreeRoot!, - rs.issuer.revocationTreeRoot!, - rs.issuer.rootOfRoots!, - ), - proof: rs.mtp, - }; - if (!sigProof.issuerData.mtp) { - throw new Error('issuer auth credential must have a mtp proof'); - } - - if (!sigProof.issuerData.authCoreClaim) { - throw new Error('issuer auth credential must have a core claim proof'); - } - - circuitClaim.signatureProof = { - signature, - issuerAuthIncProof: { - proof: issuerAuthClaimIncMtp.mtp, - treeState: buildTreeState( - issuerAuthClaimIncMtp.issuer.state!, - issuerAuthClaimIncMtp.issuer.claimsTreeRoot!, - issuerAuthClaimIncMtp.issuer.revocationTreeRoot!, - issuerAuthClaimIncMtp.issuer.rootOfRoots!, - ), - }, - issuerAuthClaim: new Claim().fromHex(sigProof.issuerData.authCoreClaim), - issuerAuthNonRevProof, - }; - } - - return circuitClaim; -}; - -export const prepareSiblingsStr = ( - proof: Proof | { siblings: Hash[] }, - levels: number, -): string[] => { - const siblings = - proof instanceof Proof ? proof.allSiblings() : proof.siblings; - - // Add the rest of empty levels to the siblings - for (let i = siblings.length; i < levels; i++) { - siblings.push(ZERO_HASH); - } - return siblings.map((s) => - typeof s === 'string' ? s : s.bigInt().toString(), - ); -}; - -export const parseRequest = async (req?: { - [key: string]: any; -}): Promise => { - if (!req) { - const query = new Query(); - query.operator = QueryOperators.$eq; - return { query, fieldName: '' }; - } - - const entries = Object.entries(req); - if (entries.length > 1) { - throw new Error(`multiple requests not supported`); - } - - const [fieldName, fieldReq] = entries[0]; - - const fieldReqEntries = Object.entries(fieldReq); - - if (fieldReqEntries.length > 1) { - throw new Error(`multiple predicates for one field not supported`); - } - - const isSelectiveDisclosure = fieldReqEntries.length === 0; - const query = new Query(); - - if (isSelectiveDisclosure) { - return { query, fieldName, isSelectiveDisclosure }; - } - - let operator = 0; - const values: bigint[] = new Array(64).fill(BigInt(0)); - const [kv, value] = fieldReqEntries[0]; - const key = kv as keyof typeof QueryOperators; - if (!QueryOperators[key]) { - throw new Error(`operator is not supported by lib`); - } - operator = QueryOperators[key]; - if (Array.isArray(value)) { - for (let index = 0; index < value.length; index++) { - values[index] = BigInt(value[index]); - } - } else { - values[0] = BigInt(value); - } - - query.operator = operator; - query.values = values; - - return { query, fieldName }; -}; - -export const merklize = async ( - credential: W3CCredential, -): Promise => { - const crdntl = { ...credential }; - delete crdntl.proof; - return await Merklizer.merklizeJSONLD(JSON.stringify(crdntl)); -}; - -export const prepareMerklizedQuery = async ( - query: ProofQuery, - credential: W3CCredential, -): Promise => { - const parsedQuery = await parseRequest(query.credentialSubject); - - const loader = getDocumentLoader(); - let schema: object; - try { - schema = (await loader(credential['@context'][2])).document; - } catch (e) { - throw new Error( - `can't load credential schema ${credential['@context'][2]}`, - ); - } - - let path: Path = new Path(); - if (parsedQuery.fieldName) { - path = await Path.getContextPathKey( - JSON.stringify(schema), - credential.type[1], - parsedQuery.fieldName, - ); - } - path.prepend(['https://www.w3.org/2018/credentials#credentialSubject']); - - const mk = await merklize(credential); - const { proof, value: mtValue } = await mk.proof(path); - - const pathKey = await path.mtEntry(); - parsedQuery.query.valueProof = new ValueProof(); - parsedQuery.query.valueProof.mtp = proof; - parsedQuery.query.valueProof.path = pathKey; - parsedQuery.query.valueProof.mtp = proof; - const mtEntry = await mtValue?.mtEntry(); - parsedQuery.query.valueProof.value = mtEntry; - - // for merklized credentials slotIndex in query must be equal to zero - // and not a position of merklization root. - // it has no influence on check in the off-chain circuits, but it aligns with onchain verification standard - parsedQuery.query.slotIndex = 0; - - if (!parsedQuery.fieldName || parsedQuery.isSelectiveDisclosure) { - const resultQuery = parsedQuery.query; - resultQuery.operator = QueryOperators.$eq; - resultQuery.values = [mtEntry!]; - return resultQuery; - } - - return parsedQuery.query; -}; - -export const getFieldSlotIndex = ( - field: string, - schemaBytes: Uint8Array, -): number => { - const schema: JSONSchema = JSON.parse(new TextDecoder().decode(schemaBytes)); - if (!schema?.$metadata?.serialization) { - throw new Error('serialization info is not set'); - } - - switch (field) { - case schema.$metadata?.serialization?.indexDataSlotA: - return 2; - case schema.$metadata?.serialization?.indexDataSlotB: - return 3; - case schema.$metadata?.serialization?.valueDataSlotA: - return 6; - case schema.$metadata?.serialization?.valueDataSlotB: - return 7; - default: - throw new Error(`field ${field} not specified in serialization info`); - } -}; - -export const stringByPath = ( - obj: { [key: string]: any }, - path: string, -): string => { - const parts = path.split('.'); - - let value = obj; - for (let index = 0; index < parts.length; index++) { - const key = parts[index]; - if (!key) { - throw new Error('path is empty'); - } - value = value[key]; - if (value === undefined) { - throw new Error('path not found'); - } - } - return value.toString(); -}; - -export const buildQueryPath = async ( - contextURL: string, - contextType: string, - field: string, -): Promise => { - let resp; - try { - resp = await (await fetch(contextURL)).json(); - } catch (error) { - throw new Error(`context not found: ${error.message}`); - } - - const path = await Path.getContextPathKey( - JSON.stringify(resp), - contextType, - field, - ); - path.prepend(['https://www.w3.org/2018/credentials#credentialSubject']); - return path; -}; - -export const verifiablePresentationFromCred = async ( - w3cCred: W3CCredential, - requestObj: ProofQuery, - field: string, -): Promise => { - const mz = await merklize(w3cCred); - - const contextType = stringByPath(requestObj, 'type'); - - const contextURL = stringByPath(requestObj, 'context'); - - const path = await buildQueryPath(contextURL, contextType, field); - - const { value } = await mz.proof(path); - - return value; -}; - -export const prepareNonMerklizedQuery = async ( - query: ProofQuery, - credential: W3CCredential, -): Promise => { - const loader = getDocumentLoader(); - - let schema: object; - try { - schema = (await loader(credential.credentialSchema.id)).document; - } catch (e) { - throw new Error( - `can't load credential schema ${credential['@context'][2]}`, - ); - } - - if ( - query.credentialSubject && - Object.keys(query.credentialSubject).length > 1 - ) { - throw new Error('multiple requests are not supported'); - } - - const parsedQuery = await parseRequest(query.credentialSubject); - parsedQuery.query.slotIndex = getFieldSlotIndex( - parsedQuery.fieldName, - new TextEncoder().encode(JSON.stringify(schema)), - ); - - if (parsedQuery.isSelectiveDisclosure) { - const mzValue = await verifiablePresentationFromCred( - credential, - query, - parsedQuery.fieldName, - ); - const resultQuery = parsedQuery.query; - resultQuery.operator = QueryOperators.$eq; - resultQuery.values = [await mzValue!.mtEntry()]; - return resultQuery; - } - - return parsedQuery.query; -}; - -export const toCircuitsQuery = async ( - query: ProofQuery, - credential: W3CCredential, - coreClaim: Claim, -): Promise => { - const mtPosition = coreClaim.getMerklizedPosition(); - - return mtPosition === MerklizedRootPosition.None - ? prepareNonMerklizedQuery(query, credential) - : prepareMerklizedQuery(query, credential); -}; - -export const prepareCircuitArrayValues = ( - arr: bigint[], - size: number, -): bigint[] => { - if (arr.length > size) { - throw new Error( - `array size ${arr.length} is bigger max expected size ${size}`, - ); - } - - // Add the empty values - for (let i = arr.length; i < size; i++) { - arr.push(BigInt(0)); - } - - return arr; -}; - -export const getNodeAuxValue = (p: Proof | undefined): NodeAuxValue => { - // proof of inclusion - if (p?.existence) { - return { - key: ZERO_HASH, - value: ZERO_HASH, - noAux: '0', - }; - } - - // proof of non-inclusion (NodeAux exists) - if (p?.nodeAux?.value !== undefined && p?.nodeAux?.key !== undefined) { - return { - key: p.nodeAux.key, - value: p.nodeAux.value, - noAux: '0', - }; - } - // proof of non-inclusion (NodeAux does not exist) - return { - key: ZERO_HASH, - value: ZERO_HASH, - noAux: '1', - }; -}; - -const newProofFromData = ( - existence: boolean, - allSiblings: Hash[], - nodeAux?: NodeAux, -): Proof => { - return new Proof({ - existence, - nodeAux, - siblings: allSiblings, - }); -}; - -export const toGISTProof = (smtProof: StateProof): GISTProof => { - let existence = false; - let nodeAux; - - if (smtProof.existence) { - existence = true; - } else if (smtProof.auxExistence) { - nodeAux = { - key: newHashFromBigInt(smtProof.auxIndex), - value: newHashFromBigInt(smtProof.auxValue), - }; - } - - const allSiblings: Hash[] = smtProof.siblings.map((s) => - newHashFromBigInt(s), - ); - - const proof = newProofFromData(existence, allSiblings, nodeAux); - - const root = newHashFromBigInt(smtProof.root); - - return { - root, - proof, - }; -}; diff --git a/packages/snap/src/helpers/state-v2-helpers.ts b/packages/snap/src/helpers/state-v2-helpers.ts deleted file mode 100644 index 0a664d32..00000000 --- a/packages/snap/src/helpers/state-v2-helpers.ts +++ /dev/null @@ -1,211 +0,0 @@ -/* eslint-disable camelcase */ -import type { TransactionRequest } from '@ethersproject/providers'; -import { providers, utils } from 'ethers'; - -import { - getChainInfo, - getProviderChainInfo, - getRarimoCoreUrl, - getRarimoEvmRpcUrl, - getRarimoStateContractAddress, -} from './common-helpers'; -import { FetcherError } from './error-helper'; -import type { - ChainInfo, - StateInfo, - OperationResponse, - OperationProof, - StateProof, -} from '../types'; -import { LightweightStateV2__factory, StateV2__factory } from '../types'; -import type { ILightweightStateV2 } from '../types/contracts/LightweightStateV2'; - -export const getGISTProof = async ({ - rpcUrl, - contractAddress, - userId, - rootHash, -}: { - rpcUrl: string; - contractAddress: string; - userId: string; - rootHash?: string; -}): Promise => { - const rawProvider = new providers.JsonRpcProvider(rpcUrl, 'any'); - - const contractInstance = StateV2__factory.connect( - contractAddress, - rawProvider, - ); - const data = rootHash - ? await contractInstance.getGISTProofByRoot(userId, rootHash) - : await contractInstance.getGISTProof(userId); - - return { - root: BigInt(data.root.toString()), - existence: data.existence, - siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())), - index: BigInt(data.index.toString()), - value: BigInt(data.value.toString()), - auxExistence: data.auxExistence, - auxIndex: BigInt(data.auxIndex.toString()), - auxValue: BigInt(data.auxValue.toString()), - }; -}; - -// getRarimoGISTRoot returns the latest GIST root from the Rarimo state contract -export const getRarimoGISTRoot = async ({ - rpcUrl, - contractAddress, -}: { - rpcUrl?: string; - contractAddress?: string; -} = {}): Promise => { - const providerChainInfo = await getProviderChainInfo(); - - const _rpcUrl = rpcUrl ?? getRarimoEvmRpcUrl(providerChainInfo.id); - const _contractAddress = - contractAddress ?? getRarimoStateContractAddress(providerChainInfo.id); - - const rawProvider = new providers.JsonRpcProvider(_rpcUrl, 'any'); - - const contractInstance = StateV2__factory.connect( - _contractAddress, - rawProvider, - ); - - const root = await contractInstance.getGISTRoot(); - - return BigInt(root.toString()); -}; - -// getCurrentChainGISTRoot returns the GIST root from a lightweight state contract deployed on the current chain -export const getCurrentChainGISTRoot = async (): Promise => { - const provider = new providers.Web3Provider( - ethereum as any as providers.ExternalProvider, - ); - const network = await provider.getNetwork(); - const chainInfo = getChainInfo(network.chainId); - - const contractInstance = LightweightStateV2__factory.connect( - chainInfo.stateContractAddress, - provider, - ); - const root = await contractInstance.getGISTRoot(); - return BigInt(root.toString()); -}; - -// checkIfStateSynced returns true if the GIST root from the Rarimo state contract matches the GIST root from the current chain -export const checkIfStateSynced = async (): Promise => { - /* - NOTE: for now we assume that the state must be synced if the GIST roots don't match - some more sophisticated logic could be added here in the future - */ - const rarimoGISTRoot = await getRarimoGISTRoot(); - const currentChainGISTRoot = await getCurrentChainGISTRoot(); - return rarimoGISTRoot === currentChainGISTRoot; -}; - -export const loadDataFromRarimoCore = async ( - url: string, - blockHeight?: string, -): Promise => { - const providerChainInfo = await getProviderChainInfo(); - - const rarimoCoreUrl = getRarimoCoreUrl(providerChainInfo.id); - - const response = await fetch(`${rarimoCoreUrl}${url}`, { - headers: { - 'Content-Type': 'application/json', - ...(blockHeight && { 'X-Cosmos-Block-Height': blockHeight }), - }, - }); - - if (!response.ok) { - throw new FetcherError(response); - } - - return await response.json(); -}; - -type UpdateStateDetails = { - stateRootHash: string; - gistRootDataStruct: ILightweightStateV2.GistRootDataStruct; - proof: string; -}; - -export const getCoreOperationByIndex = async (index: string) => { - return loadDataFromRarimoCore( - `/rarimo/rarimo-core/rarimocore/operation/${index}`, - ); -}; - -export const getUpdateStateDetails = async ( - state: StateInfo, - operation: OperationResponse, -): Promise => { - let operationProof; - do { - try { - operationProof = await loadDataFromRarimoCore( - `/rarimo/rarimo-core/rarimocore/operation/${state.lastUpdateOperationIndex}/proof`, - ); - } catch (e) { - if (e instanceof FetcherError && e.response.status === 400) { - await new Promise((resolve) => setTimeout(resolve, 5_000)); - } else { - throw e; - } - } - } while (!operationProof); - - const decodedPath = operationProof?.path?.map((el: string) => - utils.arrayify(el), - ); - const decodedSignature = operationProof?.signature - ? utils.arrayify(operationProof?.signature) - : undefined; - - if (decodedSignature?.[64] !== undefined) { - decodedSignature[64] += 27; - } - - const proof = utils.defaultAbiCoder.encode( - ['bytes32[]', 'bytes'], - [decodedPath, decodedSignature], - ); - - return { - stateRootHash: operation.operation.details.stateRootHash, - gistRootDataStruct: { - root: operation.operation.details.GISTHash, - createdAtTimestamp: Number(operation.operation.details.timestamp), - }, - proof, - }; -}; - -export const getUpdateStateTx = async ( - accountId: string, - chainInfo: ChainInfo, - state: StateInfo, - operation: OperationResponse, - updateStateDetails?: UpdateStateDetails, -): Promise => { - const { stateRootHash, gistRootDataStruct, proof } = - updateStateDetails ?? (await getUpdateStateDetails(state, operation)); - - const contractInterface = LightweightStateV2__factory.createInterface(); - - const txData = contractInterface.encodeFunctionData('signedTransitState', [ - stateRootHash, - gistRootDataStruct, - proof, - ]); - return { - to: chainInfo.stateContractAddress, - from: accountId, - chainId: chainInfo.id, - data: txData, - }; -}; diff --git a/packages/snap/src/rpc/store.ts b/packages/snap/src/helpers/store.ts similarity index 68% rename from packages/snap/src/rpc/store.ts rename to packages/snap/src/helpers/store.ts index 94bdbbec..283fe385 100644 --- a/packages/snap/src/rpc/store.ts +++ b/packages/snap/src/helpers/store.ts @@ -1,3 +1,6 @@ +import type { StorageKeys } from '@/enums'; +import type { StorageMap } from '@/types'; + const getState = async () => { return await snap.request({ method: 'snap_manageState', @@ -5,14 +8,19 @@ const getState = async () => { }); }; -export const getItemFromStore = async (key: string): Promise => { +const getItem = async ( + key: T, +): Promise => { const state = await getState(); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return state?.[key] ? JSON.parse(state[key]) : null; }; -export const setItemInStore = async (key: string, inputData: any) => { +const setItem = async ( + key: T, + inputData: StorageMap[T], +) => { const state = (await getState()) ?? {}; state[key] = JSON.stringify(inputData); @@ -22,7 +30,7 @@ export const setItemInStore = async (key: string, inputData: any) => { }); }; -export const clearState = async () => { +const clear = async () => { return await snap.request({ method: 'snap_manageState', params: { operation: 'clear' }, @@ -31,7 +39,7 @@ export const clearState = async () => { export const snapStorage = { getState, - getItemFromStore, - setItemInStore, - clearState, + getItem, + setItem, + clear, }; diff --git a/packages/snap/src/identity.ts b/packages/snap/src/identity.ts deleted file mode 100644 index e36970bb..00000000 --- a/packages/snap/src/identity.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { Hex, PrivateKey } from '@iden3/js-crypto'; -import { - Claim, - ClaimOptions, - DID, - fromBigEndian, - idenState, - SchemaHash, -} from '@iden3/js-iden3-core'; -import type { Proof } from '@iden3/js-merkletree'; -import { hashElems, InMemoryDB, Merkletree } from '@iden3/js-merkletree'; - -import { config } from './config'; -import { defaultMTLevels } from './const'; -import { initPrivateKey, prepareSiblingsStr } from './helpers'; - -export type TreeState = { - state: string; - claimsRoot: string; - revocationRoot: string; - rootOfRoots: string; -}; - -export class Identity { - privateKeyHex = '' as string; - - did: DID = {} as DID; - - authClaimIncProofSiblings: string[] = []; - - authClaimNonRevProof: Proof = {} as Proof; - - treeState: TreeState = {} as TreeState; - - coreAuthClaim: Claim = {} as Claim; - - public static async create(privateKeyHex?: string): Promise { - const identity = new Identity(privateKeyHex); - - await identity.createIdentity(); - - return identity; - } - - constructor(privateKeyHex?: string) { - this.privateKeyHex = initPrivateKey(privateKeyHex); - } - - public get privateKey() { - return new PrivateKey(Hex.decodeString(this.privateKeyHex)); - } - - public get didString() { - return this.did.string(); - } - - public get identityIdBigIntString() { - const id = DID.idFromDID(this.did); - - return String(id.bigInt()); - } - - async createIdentity() { - this.coreAuthClaim = this.createCoreAuthClaim(); - - const authResponse = this.coreAuthClaim.hiHv(); - - const uint8array1 = new TextEncoder().encode('claims'); - const uint8array2 = new TextEncoder().encode('revocations'); - const uint8array3 = new TextEncoder().encode('roots'); - - const storage1 = new InMemoryDB(uint8array1); - const storage2 = new InMemoryDB(uint8array2); - const storage3 = new InMemoryDB(uint8array3); - - const claimsTree = new Merkletree(storage1, true, 32); - const revocationsTree = new Merkletree(storage2, true, 32); - const rootsTree = new Merkletree(storage3, true, 32); - - await claimsTree.add(authResponse.hi, authResponse.hv); - - const claimsTreeRoot = await claimsTree.root(); - const revocationsTreeRoot = await revocationsTree.root(); - const rootsTreeRoot = await rootsTree.root(); - - const identity = idenState( - claimsTreeRoot.bigInt(), - revocationsTreeRoot.bigInt(), - rootsTreeRoot.bigInt(), - ); - - this.did = DID.newFromIdenState(config.ID_TYPE, identity); - - const authClaimIncProof = await claimsTree.generateProof( - this.coreAuthClaim.hIndex(), - claimsTreeRoot, - ); - - const authClaimIncProofSiblings = prepareSiblingsStr( - authClaimIncProof.proof, - defaultMTLevels, - ); - - const authClaimNonRevProof = await revocationsTree.generateProof( - this.coreAuthClaim.getRevocationNonce(), - revocationsTreeRoot, - ); - - this.authClaimIncProofSiblings = authClaimIncProofSiblings; - this.authClaimNonRevProof = authClaimNonRevProof.proof; - - const stateHash = hashElems([ - claimsTreeRoot.bigInt(), - revocationsTreeRoot.bigInt(), - rootsTreeRoot.bigInt(), - ]); - - this.treeState = { - state: stateHash.string(), - claimsRoot: claimsTreeRoot.string(), - revocationRoot: revocationsTreeRoot.string(), - rootOfRoots: rootsTreeRoot.string(), - }; - } - - createCoreAuthClaim() { - const hash = SchemaHash.newSchemaHashFromHex( - config.AUTH_BJJ_CREDENTIAL_HASH, - ); - const revNonce = new Uint8Array(64); - const key = this.privateKey.public(); - - return Claim.newClaim( - hash, - ClaimOptions.withIndexDataInts(key.p[0], key.p[1]), - ClaimOptions.withRevocationNonce(fromBigEndian(revNonce)), - ); - } -} diff --git a/packages/snap/src/index.ts b/packages/snap/src/index.ts index 61350bb5..ad3b619a 100644 --- a/packages/snap/src/index.ts +++ b/packages/snap/src/index.ts @@ -1,48 +1,21 @@ // eslint-disable-next-line import/no-unassigned-import import './polyfill'; -import { DID } from '@iden3/js-iden3-core'; -import type { Component } from '@metamask/snaps-sdk'; -import { copyable, divider, heading, panel, text } from '@metamask/snaps-sdk'; + import type { JsonRpcRequest } from '@metamask/utils'; -import type { - CheckCredentialExistenceRequestParams, - RemoveCredentialsRequestParams, - CreateIdentityRequestParams, - SaveCredentialsResponse, -} from '@rarimo/rarime-connector'; import { RPCMethods } from '@rarimo/rarime-connector'; -import { utils } from 'ethers'; -import { AuthZkp } from './auth-zkp'; -import { CircuitId, StorageKeys } from './enums'; -import { - checkIfStateSynced, - genPkHexFromEntropy, - getClaimIdFromVCId, - getCoreOperationByIndex, - getProviderChainInfo, - getRarimoCoreUrl, - isDidSupported, - isOriginInWhitelist, - loadDataFromRarimoCore, - migrateVCsToLastCeramicModel, - parseDidV2, - VCManager, -} from './helpers'; -import { Identity } from './identity'; -import { getItemFromStore, setItemInStore } from './rpc'; -import type { - SaveCredentialsRequestParams, - CreateProofRequestParams, - GetStateInfoResponse, - MerkleProof, - TextField, -} from './types'; import { - isValidCreateProofRequest, - isValidSaveCredentialsOfferRequest, -} from './typia-generated'; -import { ZkpGen } from './zkp-gen'; + CheckCredentialExistence, + checkStateContractSync, + createIdentity, + createProof, + exportIdentity, + getCredentials, + getIdentity, + removeCredentials, + saveCredentials, +} from '@/zkp'; +import { migrateVCsToLastCeramicModel } from '@/zkp/helpers'; export const onRpcRequest = async ({ request, @@ -57,430 +30,39 @@ export const onRpcRequest = async ({ switch (request.method) { case RPCMethods.CheckCredentialExistence: { - const identityStorage = await getItemFromStore(StorageKeys.identity); - if (!identityStorage) { - throw new Error('Identity not created'); - } - - const { claimOffer, proofRequest } = - request.params as CheckCredentialExistenceRequestParams; - - const vcManager = await VCManager.create(); - - let result: SaveCredentialsResponse[] = []; - - if (claimOffer && proofRequest) { - const vcs = await vcManager.getDecryptedVCsByOfferAndQuery( - claimOffer, - proofRequest, - ); - - result = vcs?.map((vc) => ({ - type: vc.type, - issuer: vc.issuer, - })); - } else if (claimOffer) { - const vcs = await vcManager.getDecryptedVCsByOffer(claimOffer); - - result = vcs?.map((vc) => ({ - type: vc.type, - issuer: vc.issuer, - })); - } else if (proofRequest) { - const vcs = await vcManager.getDecryptedVCsByQuery( - proofRequest.query, - proofRequest.issuerDid, - ); - - result = vcs?.map((vc) => ({ - type: vc.type, - issuer: vc.issuer, - })); - } - - return result; + return CheckCredentialExistence({ request, origin }); } case RPCMethods.RemoveCredentials: { - if (!isOriginInWhitelist(origin)) { - throw new Error( - 'This origin does not have access to the RemoveCredentials method', - ); - } - - const identityStorage = await getItemFromStore(StorageKeys.identity); - if (!identityStorage) { - throw new Error('Identity not created'); - } - - const params = request.params as RemoveCredentialsRequestParams; - - const claimIds = params.ids.map((id) => getClaimIdFromVCId(id)); - - const vcManager = await VCManager.create(); - - const vcs = await vcManager.getDecryptedVCsByClaimIds(claimIds); - - const res = await snap.request({ - method: 'snap_dialog', - params: { - type: 'confirmation', - content: panel([ - heading('Remove Credentials'), - divider(), - - ...vcs.reduce((acc, el, idx) => { - const vcTargetType = el.type[1]; - const vcID = el.id; - - return acc.concat([ - text(`**Credential #${idx + 1}**`), - text(`Type: ${vcTargetType}`), - text(`ID: ${vcID}`), - divider(), - ]); - }, []), - ]), - }, - }); - - if (!res) { - throw new Error('User rejected request'); - } - - await Promise.all(vcs.map(async (vc) => vcManager.clearMatchedVcs(vc))); - - return undefined; + return removeCredentials({ request, origin }); } case RPCMethods.SaveCredentials: { - const identityStorage = await getItemFromStore(StorageKeys.identity); - if (!identityStorage) { - throw new Error('Identity not created'); - } - - // FIXME: mb multiple offers? - const offer = request.params as any as SaveCredentialsRequestParams; - - isValidSaveCredentialsOfferRequest(offer); - - const dialogContent = [ - heading('Credentials'), - divider(), - text(`From: ${offer.from}`), - text(`Url: ${offer.body.url}`), - ]; - - const dialogCredentials = offer.body.Credentials.reduce( - (acc: any, cred: any) => { - return acc.concat([divider(), text(cred.description), text(cred.id)]); - }, - [], - ); - - const res = await snap.request({ - method: 'snap_dialog', - params: { - type: 'confirmation', - content: panel([...dialogContent, ...dialogCredentials]), - }, - }); - - if (res) { - const vcManager = await VCManager.create(); - - const identity = await Identity.create(identityStorage.privateKeyHex); - - const authProof = new AuthZkp(identity, offer); - - const credentials = await authProof.getVerifiableCredentials(); - - await Promise.all( - credentials.map(async (credential) => { - await vcManager.clearMatchedVcs(credential); - await vcManager.encryptAndSaveVC(credential); - }), - ); - - return credentials.map((cred) => ({ - type: cred.type, - issuer: cred.issuer, - })); - } - throw new Error('User rejected request'); + return saveCredentials({ request, origin }); } case RPCMethods.CreateIdentity: { - const identityStorage = await getItemFromStore(StorageKeys.identity); - - const params = request.params as CreateIdentityRequestParams; - - if ( - params?.privateKeyHex && - !utils.isHexString(`0x${params?.privateKeyHex}`) - ) { - throw new Error('Invalid private key'); - } - - if ( - identityStorage?.did && - identityStorage?.didBigInt && - isDidSupported(identityStorage.did) - ) { - return { - identityIdString: identityStorage.did, - identityIdBigIntString: identityStorage.didBigInt, - }; - } - - const res = - Boolean(identityStorage?.did && identityStorage?.didBigInt) || - (await snap.request({ - method: 'snap_dialog', - params: { - type: 'confirmation', - content: panel([ - heading('Identity creation'), - divider(), - text(`You don't have an identity yet`), - text('Would you like to create one?'), - ]), - }, - })); - - if (!res) { - throw new Error('User rejected request'); - } - - const identity = await Identity.create( - params?.privateKeyHex || (await genPkHexFromEntropy()), - ); - - await setItemInStore(StorageKeys.identity, { - privateKeyHex: identity.privateKeyHex, - did: identity.didString, - didBigInt: identity.identityIdBigIntString, - }); - - await snap.request({ - method: 'snap_dialog', - params: { - type: 'alert', - content: panel([ - heading('Your RariMe is ready for use!'), - divider(), - text('Your unique identifier(DID):'), - copyable(identity.didString), - ]), - }, - }); - - return { - identityIdString: identity.didString, - identityIdBigIntString: identity.identityIdBigIntString, - }; + return createIdentity({ request, origin }); } case RPCMethods.GetIdentity: { - const identityStorage = await getItemFromStore(StorageKeys.identity); - - if (!identityStorage) { - throw new Error('Identity not created'); - } - - return { - identityIdString: identityStorage.did, - identityIdBigIntString: identityStorage.didBigInt, - }; + return getIdentity(); } case RPCMethods.CreateProof: { - const identityStorage = await getItemFromStore(StorageKeys.identity); - if (!identityStorage) { - throw new Error('Identity not created'); - } - - const params = request.params as CreateProofRequestParams; - - const { issuerDid, ...createProofRequest } = params; - - isValidCreateProofRequest(createProofRequest); - - const { query } = createProofRequest; - const { circuitId, accountAddress } = createProofRequest; - - const isOnChainProof = - circuitId === CircuitId.AtomicQuerySigV2OnChain || - circuitId === CircuitId.AtomicQueryMTPV2OnChain; - - if (isOnChainProof && !accountAddress) { - throw new Error('Account address is required'); - } - - const vcManager = await VCManager.create(); - - const credentials = ( - await vcManager.getDecryptedVCsByQuery(query, issuerDid) - ).filter((cred) => { - const CredSubjId = parseDidV2(cred.credentialSubject.id as string); - - const IdentityStorageDid = parseDidV2(identityStorage.did); - - return CredSubjId.string() === IdentityStorageDid.string(); - }); - - if (!credentials.length) { - throw new Error( - `no credential were issued on the given id ${identityStorage.did}`, - ); - } - - const vc = credentials[0]; - - const res = await snap.request({ - method: 'snap_dialog', - params: { - type: 'confirmation', - content: panel([ - heading('Generate a zero-knowledge proof?'), - - divider(), - - text('**Credential**'), - text(`${vc.type?.[1]}\n`), - - divider(), - text('**Query**'), - - ...(query.credentialSubject - ? Object.keys(query.credentialSubject).reduce( - (accSubj: TextField[], fieldName) => { - const fieldOperators = query.credentialSubject?.[fieldName]; - - const isString = typeof fieldOperators === 'string'; - const isNumber = typeof fieldOperators === 'number'; - - if (isString || isNumber) { - return accSubj.concat( - text(`${fieldName} - ${fieldOperators}\n`), - ); - } - - const textField = Object.keys(fieldOperators).map( - (operator) => { - return text( - `${fieldName} - ${operator} ${ - (fieldOperators as any)?.[operator] - }\n`, - ); - }, - ); - - return accSubj.concat(textField); - }, - [], - ) - : []), - - divider(), - - ...(circuitId ? [text('**ZK Circuit**'), text(circuitId)] : []), - ]), - }, - }); - - if (res) { - const identity = await Identity.create(identityStorage.privateKeyHex); - - const zkpGen = new ZkpGen(identity, createProofRequest, vc); - - // ================ LOAD STATE DETAILS ===================== - - const chainInfo = await getProviderChainInfo(); - - const rarimoCoreUrl = getRarimoCoreUrl(chainInfo.id); - - const isSynced = await checkIfStateSynced(); - - const did = parseDidV2(issuerDid); - - const issuerId = DID.idFromDID(did); - - const issuerHexId = `0x0${issuerId.bigInt().toString(16)}`; - - const stateData = await loadDataFromRarimoCore( - `/rarimo/rarimo-core/identity/state/${issuerHexId}`, - ); - const merkleProof = await loadDataFromRarimoCore( - `/rarimo/rarimo-core/identity/state/${issuerHexId}/proof`, - stateData.state.createdAtBlock, - ); - - const operation = await getCoreOperationByIndex( - stateData.state.lastUpdateOperationIndex, - ); - - // ================== USE STATE DETAILS TO GEN PROOF ===================== - - const zkpProof = await zkpGen.generateProof( - stateData.state.hash, - operation.operation.details.GISTHash, - ); - - return { - chainInfo, - rarimoCoreUrl, - isSynced, - - issuerHexId, - - stateData: stateData.state, - merkleProof, - operation: operation.operation, - - zkpProof, - }; - } - throw new Error('User rejected request'); + return createProof({ request, origin }); } case RPCMethods.CheckStateContractSync: { - return await checkIfStateSynced(); + return checkStateContractSync(); } case RPCMethods.GetCredentials: { - if (!isOriginInWhitelist(origin)) { - throw new Error('This origin does not have access to credentials'); - } - - const vcManager = await VCManager.create(); - - return await vcManager.getAllDecryptedVCs(); + return getCredentials({ request, origin }); } case RPCMethods.ExportIdentity: { - if (!isOriginInWhitelist(origin)) { - throw new Error('This origin does not have access to export identity'); - } - - const identityStorage = await getItemFromStore(StorageKeys.identity); - - if (!identityStorage.privateKeyHex) { - throw new Error('Identity not created'); - } - - return snap.request({ - method: 'snap_dialog', - params: { - type: 'alert', - content: panel([ - heading('Your RariMe private key'), - divider(), - text('Сopy:'), - copyable(identityStorage.privateKeyHex), - ]), - }, - }); + return exportIdentity({ request, origin }); } default: diff --git a/packages/snap/src/polyfill.ts b/packages/snap/src/polyfill.ts index 9acf4920..b50d7b24 100644 --- a/packages/snap/src/polyfill.ts +++ b/packages/snap/src/polyfill.ts @@ -5,7 +5,7 @@ global.Intl = intl; // eslint-disable-next-line import/unambiguous if (typeof global.crypto.getRandomValues !== 'function') { global.crypto.getRandomValues = (array: any) => { - for (let i = 0, l = array.length; i < l; i++) { + for (let i = 0, { length } = array; i < length; i++) { array[i] = Math.floor(Math.random() * 256); } return array; diff --git a/packages/snap/src/rpc/index.ts b/packages/snap/src/rpc/index.ts deleted file mode 100644 index d4068169..00000000 --- a/packages/snap/src/rpc/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './store'; diff --git a/packages/snap/src/types/contracts/LightweightStateV2.ts b/packages/snap/src/types/contracts/LightweightStateV2.ts deleted file mode 100644 index af08c19e..00000000 --- a/packages/snap/src/types/contracts/LightweightStateV2.ts +++ /dev/null @@ -1,966 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BigNumber, - BigNumberish, - BytesLike, - CallOverrides, - ContractTransaction, - Overrides, - PayableOverrides, - PopulatedTransaction, - Signer, - utils, -} from "ethers"; -import type { - FunctionFragment, - Result, - EventFragment, -} from "@ethersproject/abi"; -import type { Listener, Provider } from "@ethersproject/providers"; -import type { - TypedEventFilter, - TypedEvent, - TypedListener, - OnEvent, -} from "./common"; - -export declare namespace ILightweightStateV2 { - export type GistRootDataStruct = { - root: BigNumberish; - createdAtTimestamp: BigNumberish; - }; - - export type GistRootDataStructOutput = [BigNumber, BigNumber] & { - root: BigNumber; - createdAtTimestamp: BigNumber; - }; - - export type IdentitiesStatesRootDataStruct = { - root: BytesLike; - setTimestamp: BigNumberish; - }; - - export type IdentitiesStatesRootDataStructOutput = [string, BigNumber] & { - root: string; - setTimestamp: BigNumber; - }; -} - -export interface LightweightStateV2Interface extends utils.Interface { - functions: { - "P()": FunctionFragment; - "__LightweightStateV2_init(address,address,string,string)": FunctionFragment; - "__Signers_init(address,string)": FunctionFragment; - "chainName()": FunctionFragment; - "changeSigner(bytes,bytes)": FunctionFragment; - "changeSourceStateContract(address,bytes)": FunctionFragment; - "checkSignatureAndIncrementNonce(uint8,address,bytes32,bytes)": FunctionFragment; - "getCurrentGISTRootInfo()": FunctionFragment; - "getGISTRoot()": FunctionFragment; - "getGISTRootInfo(uint256)": FunctionFragment; - "getIdentitiesStatesRootData(bytes32)": FunctionFragment; - "getSigComponents(uint8,address)": FunctionFragment; - "identitiesStatesRoot()": FunctionFragment; - "isIdentitiesStatesRootExists(bytes32)": FunctionFragment; - "nonces(address,uint8)": FunctionFragment; - "proxiableUUID()": FunctionFragment; - "signedTransitState(bytes32,(uint256,uint256),bytes)": FunctionFragment; - "signer()": FunctionFragment; - "sourceChainName()": FunctionFragment; - "sourceStateContract()": FunctionFragment; - "upgradeTo(address)": FunctionFragment; - "upgradeToAndCall(address,bytes)": FunctionFragment; - "upgradeToWithSig(address,bytes)": FunctionFragment; - "validateChangeAddressSignature(uint8,address,address,bytes)": FunctionFragment; - }; - - getFunction( - nameOrSignatureOrTopic: - | "P" - | "__LightweightStateV2_init" - | "__Signers_init" - | "chainName" - | "changeSigner" - | "changeSourceStateContract" - | "checkSignatureAndIncrementNonce" - | "getCurrentGISTRootInfo" - | "getGISTRoot" - | "getGISTRootInfo" - | "getIdentitiesStatesRootData" - | "getSigComponents" - | "identitiesStatesRoot" - | "isIdentitiesStatesRootExists" - | "nonces" - | "proxiableUUID" - | "signedTransitState" - | "signer" - | "sourceChainName" - | "sourceStateContract" - | "upgradeTo" - | "upgradeToAndCall" - | "upgradeToWithSig" - | "validateChangeAddressSignature" - ): FunctionFragment; - - encodeFunctionData(functionFragment: "P", values?: undefined): string; - encodeFunctionData( - functionFragment: "__LightweightStateV2_init", - values: [string, string, string, string] - ): string; - encodeFunctionData( - functionFragment: "__Signers_init", - values: [string, string] - ): string; - encodeFunctionData(functionFragment: "chainName", values?: undefined): string; - encodeFunctionData( - functionFragment: "changeSigner", - values: [BytesLike, BytesLike] - ): string; - encodeFunctionData( - functionFragment: "changeSourceStateContract", - values: [string, BytesLike] - ): string; - encodeFunctionData( - functionFragment: "checkSignatureAndIncrementNonce", - values: [BigNumberish, string, BytesLike, BytesLike] - ): string; - encodeFunctionData( - functionFragment: "getCurrentGISTRootInfo", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "getGISTRoot", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "getGISTRootInfo", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getIdentitiesStatesRootData", - values: [BytesLike] - ): string; - encodeFunctionData( - functionFragment: "getSigComponents", - values: [BigNumberish, string] - ): string; - encodeFunctionData( - functionFragment: "identitiesStatesRoot", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "isIdentitiesStatesRootExists", - values: [BytesLike] - ): string; - encodeFunctionData( - functionFragment: "nonces", - values: [string, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "proxiableUUID", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "signedTransitState", - values: [BytesLike, ILightweightStateV2.GistRootDataStruct, BytesLike] - ): string; - encodeFunctionData(functionFragment: "signer", values?: undefined): string; - encodeFunctionData( - functionFragment: "sourceChainName", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "sourceStateContract", - values?: undefined - ): string; - encodeFunctionData(functionFragment: "upgradeTo", values: [string]): string; - encodeFunctionData( - functionFragment: "upgradeToAndCall", - values: [string, BytesLike] - ): string; - encodeFunctionData( - functionFragment: "upgradeToWithSig", - values: [string, BytesLike] - ): string; - encodeFunctionData( - functionFragment: "validateChangeAddressSignature", - values: [BigNumberish, string, string, BytesLike] - ): string; - - decodeFunctionResult(functionFragment: "P", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "__LightweightStateV2_init", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "__Signers_init", - data: BytesLike - ): Result; - decodeFunctionResult(functionFragment: "chainName", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "changeSigner", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "changeSourceStateContract", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "checkSignatureAndIncrementNonce", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getCurrentGISTRootInfo", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRoot", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootInfo", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getIdentitiesStatesRootData", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getSigComponents", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "identitiesStatesRoot", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "isIdentitiesStatesRootExists", - data: BytesLike - ): Result; - decodeFunctionResult(functionFragment: "nonces", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "proxiableUUID", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "signedTransitState", - data: BytesLike - ): Result; - decodeFunctionResult(functionFragment: "signer", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "sourceChainName", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "sourceStateContract", - data: BytesLike - ): Result; - decodeFunctionResult(functionFragment: "upgradeTo", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "upgradeToAndCall", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "upgradeToWithSig", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "validateChangeAddressSignature", - data: BytesLike - ): Result; - - events: { - "AdminChanged(address,address)": EventFragment; - "BeaconUpgraded(address)": EventFragment; - "Initialized(uint8)": EventFragment; - "SignedStateTransited(uint256,bytes32)": EventFragment; - "Upgraded(address)": EventFragment; - }; - - getEvent(nameOrSignatureOrTopic: "AdminChanged"): EventFragment; - getEvent(nameOrSignatureOrTopic: "BeaconUpgraded"): EventFragment; - getEvent(nameOrSignatureOrTopic: "Initialized"): EventFragment; - getEvent(nameOrSignatureOrTopic: "SignedStateTransited"): EventFragment; - getEvent(nameOrSignatureOrTopic: "Upgraded"): EventFragment; -} - -export interface AdminChangedEventObject { - previousAdmin: string; - newAdmin: string; -} -export type AdminChangedEvent = TypedEvent< - [string, string], - AdminChangedEventObject ->; - -export type AdminChangedEventFilter = TypedEventFilter; - -export interface BeaconUpgradedEventObject { - beacon: string; -} -export type BeaconUpgradedEvent = TypedEvent< - [string], - BeaconUpgradedEventObject ->; - -export type BeaconUpgradedEventFilter = TypedEventFilter; - -export interface InitializedEventObject { - version: number; -} -export type InitializedEvent = TypedEvent<[number], InitializedEventObject>; - -export type InitializedEventFilter = TypedEventFilter; - -export interface SignedStateTransitedEventObject { - newGistRoot: BigNumber; - newIdentitesStatesRoot: string; -} -export type SignedStateTransitedEvent = TypedEvent< - [BigNumber, string], - SignedStateTransitedEventObject ->; - -export type SignedStateTransitedEventFilter = - TypedEventFilter; - -export interface UpgradedEventObject { - implementation: string; -} -export type UpgradedEvent = TypedEvent<[string], UpgradedEventObject>; - -export type UpgradedEventFilter = TypedEventFilter; - -export interface LightweightStateV2 extends BaseContract { - connect(signerOrProvider: Signer | Provider | string): this; - attach(addressOrName: string): this; - deployed(): Promise; - - interface: LightweightStateV2Interface; - - queryFilter( - event: TypedEventFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>; - - listeners( - eventFilter?: TypedEventFilter - ): Array>; - listeners(eventName?: string): Array; - removeAllListeners( - eventFilter: TypedEventFilter - ): this; - removeAllListeners(eventName?: string): this; - off: OnEvent; - on: OnEvent; - once: OnEvent; - removeListener: OnEvent; - - functions: { - P(overrides?: CallOverrides): Promise<[BigNumber]>; - - __LightweightStateV2_init( - signer_: string, - sourceStateContract_: string, - sourceChainName_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - __Signers_init( - signer_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - chainName(overrides?: CallOverrides): Promise<[string]>; - - changeSigner( - newSignerPubKey_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - changeSourceStateContract( - newSourceStateContract_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - checkSignatureAndIncrementNonce( - methodId_: BigNumberish, - contractAddress_: string, - signHash_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - getCurrentGISTRootInfo( - overrides?: CallOverrides - ): Promise<[ILightweightStateV2.GistRootDataStructOutput]>; - - getGISTRoot(overrides?: CallOverrides): Promise<[BigNumber]>; - - getGISTRootInfo( - root_: BigNumberish, - overrides?: CallOverrides - ): Promise<[ILightweightStateV2.GistRootDataStructOutput]>; - - getIdentitiesStatesRootData( - root_: BytesLike, - overrides?: CallOverrides - ): Promise<[ILightweightStateV2.IdentitiesStatesRootDataStructOutput]>; - - getSigComponents( - methodId_: BigNumberish, - contractAddress_: string, - overrides?: CallOverrides - ): Promise<[string, BigNumber] & { chainName_: string; nonce_: BigNumber }>; - - identitiesStatesRoot(overrides?: CallOverrides): Promise<[string]>; - - isIdentitiesStatesRootExists( - root_: BytesLike, - overrides?: CallOverrides - ): Promise<[boolean]>; - - nonces( - arg0: string, - arg1: BigNumberish, - overrides?: CallOverrides - ): Promise<[BigNumber]>; - - proxiableUUID(overrides?: CallOverrides): Promise<[string]>; - - signedTransitState( - newIdentitiesStatesRoot_: BytesLike, - gistData_: ILightweightStateV2.GistRootDataStruct, - proof_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - signer(overrides?: CallOverrides): Promise<[string]>; - - sourceChainName(overrides?: CallOverrides): Promise<[string]>; - - sourceStateContract(overrides?: CallOverrides): Promise<[string]>; - - upgradeTo( - newImplementation: string, - overrides?: Overrides & { from?: string } - ): Promise; - - upgradeToAndCall( - newImplementation: string, - data: BytesLike, - overrides?: PayableOverrides & { from?: string } - ): Promise; - - upgradeToWithSig( - newImplementation_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - validateChangeAddressSignature( - methodId_: BigNumberish, - contractAddress_: string, - newAddress_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - }; - - P(overrides?: CallOverrides): Promise; - - __LightweightStateV2_init( - signer_: string, - sourceStateContract_: string, - sourceChainName_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - __Signers_init( - signer_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - chainName(overrides?: CallOverrides): Promise; - - changeSigner( - newSignerPubKey_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - changeSourceStateContract( - newSourceStateContract_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - checkSignatureAndIncrementNonce( - methodId_: BigNumberish, - contractAddress_: string, - signHash_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - getCurrentGISTRootInfo( - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root_: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getIdentitiesStatesRootData( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - getSigComponents( - methodId_: BigNumberish, - contractAddress_: string, - overrides?: CallOverrides - ): Promise<[string, BigNumber] & { chainName_: string; nonce_: BigNumber }>; - - identitiesStatesRoot(overrides?: CallOverrides): Promise; - - isIdentitiesStatesRootExists( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - nonces( - arg0: string, - arg1: BigNumberish, - overrides?: CallOverrides - ): Promise; - - proxiableUUID(overrides?: CallOverrides): Promise; - - signedTransitState( - newIdentitiesStatesRoot_: BytesLike, - gistData_: ILightweightStateV2.GistRootDataStruct, - proof_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - sourceChainName(overrides?: CallOverrides): Promise; - - sourceStateContract(overrides?: CallOverrides): Promise; - - upgradeTo( - newImplementation: string, - overrides?: Overrides & { from?: string } - ): Promise; - - upgradeToAndCall( - newImplementation: string, - data: BytesLike, - overrides?: PayableOverrides & { from?: string } - ): Promise; - - upgradeToWithSig( - newImplementation_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - validateChangeAddressSignature( - methodId_: BigNumberish, - contractAddress_: string, - newAddress_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - callStatic: { - P(overrides?: CallOverrides): Promise; - - __LightweightStateV2_init( - signer_: string, - sourceStateContract_: string, - sourceChainName_: string, - chainName_: string, - overrides?: CallOverrides - ): Promise; - - __Signers_init( - signer_: string, - chainName_: string, - overrides?: CallOverrides - ): Promise; - - chainName(overrides?: CallOverrides): Promise; - - changeSigner( - newSignerPubKey_: BytesLike, - signature_: BytesLike, - overrides?: CallOverrides - ): Promise; - - changeSourceStateContract( - newSourceStateContract_: string, - signature_: BytesLike, - overrides?: CallOverrides - ): Promise; - - checkSignatureAndIncrementNonce( - methodId_: BigNumberish, - contractAddress_: string, - signHash_: BytesLike, - signature_: BytesLike, - overrides?: CallOverrides - ): Promise; - - getCurrentGISTRootInfo( - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root_: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getIdentitiesStatesRootData( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - getSigComponents( - methodId_: BigNumberish, - contractAddress_: string, - overrides?: CallOverrides - ): Promise<[string, BigNumber] & { chainName_: string; nonce_: BigNumber }>; - - identitiesStatesRoot(overrides?: CallOverrides): Promise; - - isIdentitiesStatesRootExists( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - nonces( - arg0: string, - arg1: BigNumberish, - overrides?: CallOverrides - ): Promise; - - proxiableUUID(overrides?: CallOverrides): Promise; - - signedTransitState( - newIdentitiesStatesRoot_: BytesLike, - gistData_: ILightweightStateV2.GistRootDataStruct, - proof_: BytesLike, - overrides?: CallOverrides - ): Promise; - - signer(overrides?: CallOverrides): Promise; - - sourceChainName(overrides?: CallOverrides): Promise; - - sourceStateContract(overrides?: CallOverrides): Promise; - - upgradeTo( - newImplementation: string, - overrides?: CallOverrides - ): Promise; - - upgradeToAndCall( - newImplementation: string, - data: BytesLike, - overrides?: CallOverrides - ): Promise; - - upgradeToWithSig( - newImplementation_: string, - signature_: BytesLike, - overrides?: CallOverrides - ): Promise; - - validateChangeAddressSignature( - methodId_: BigNumberish, - contractAddress_: string, - newAddress_: string, - signature_: BytesLike, - overrides?: CallOverrides - ): Promise; - }; - - filters: { - "AdminChanged(address,address)"( - previousAdmin?: null, - newAdmin?: null - ): AdminChangedEventFilter; - AdminChanged( - previousAdmin?: null, - newAdmin?: null - ): AdminChangedEventFilter; - - "BeaconUpgraded(address)"( - beacon?: string | null - ): BeaconUpgradedEventFilter; - BeaconUpgraded(beacon?: string | null): BeaconUpgradedEventFilter; - - "Initialized(uint8)"(version?: null): InitializedEventFilter; - Initialized(version?: null): InitializedEventFilter; - - "SignedStateTransited(uint256,bytes32)"( - newGistRoot?: null, - newIdentitesStatesRoot?: null - ): SignedStateTransitedEventFilter; - SignedStateTransited( - newGistRoot?: null, - newIdentitesStatesRoot?: null - ): SignedStateTransitedEventFilter; - - "Upgraded(address)"(implementation?: string | null): UpgradedEventFilter; - Upgraded(implementation?: string | null): UpgradedEventFilter; - }; - - estimateGas: { - P(overrides?: CallOverrides): Promise; - - __LightweightStateV2_init( - signer_: string, - sourceStateContract_: string, - sourceChainName_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - __Signers_init( - signer_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - chainName(overrides?: CallOverrides): Promise; - - changeSigner( - newSignerPubKey_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - changeSourceStateContract( - newSourceStateContract_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - checkSignatureAndIncrementNonce( - methodId_: BigNumberish, - contractAddress_: string, - signHash_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - getCurrentGISTRootInfo(overrides?: CallOverrides): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root_: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getIdentitiesStatesRootData( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - getSigComponents( - methodId_: BigNumberish, - contractAddress_: string, - overrides?: CallOverrides - ): Promise; - - identitiesStatesRoot(overrides?: CallOverrides): Promise; - - isIdentitiesStatesRootExists( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - nonces( - arg0: string, - arg1: BigNumberish, - overrides?: CallOverrides - ): Promise; - - proxiableUUID(overrides?: CallOverrides): Promise; - - signedTransitState( - newIdentitiesStatesRoot_: BytesLike, - gistData_: ILightweightStateV2.GistRootDataStruct, - proof_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - signer(overrides?: CallOverrides): Promise; - - sourceChainName(overrides?: CallOverrides): Promise; - - sourceStateContract(overrides?: CallOverrides): Promise; - - upgradeTo( - newImplementation: string, - overrides?: Overrides & { from?: string } - ): Promise; - - upgradeToAndCall( - newImplementation: string, - data: BytesLike, - overrides?: PayableOverrides & { from?: string } - ): Promise; - - upgradeToWithSig( - newImplementation_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - validateChangeAddressSignature( - methodId_: BigNumberish, - contractAddress_: string, - newAddress_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - }; - - populateTransaction: { - P(overrides?: CallOverrides): Promise; - - __LightweightStateV2_init( - signer_: string, - sourceStateContract_: string, - sourceChainName_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - __Signers_init( - signer_: string, - chainName_: string, - overrides?: Overrides & { from?: string } - ): Promise; - - chainName(overrides?: CallOverrides): Promise; - - changeSigner( - newSignerPubKey_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - changeSourceStateContract( - newSourceStateContract_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - checkSignatureAndIncrementNonce( - methodId_: BigNumberish, - contractAddress_: string, - signHash_: BytesLike, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - getCurrentGISTRootInfo( - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root_: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getIdentitiesStatesRootData( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - getSigComponents( - methodId_: BigNumberish, - contractAddress_: string, - overrides?: CallOverrides - ): Promise; - - identitiesStatesRoot( - overrides?: CallOverrides - ): Promise; - - isIdentitiesStatesRootExists( - root_: BytesLike, - overrides?: CallOverrides - ): Promise; - - nonces( - arg0: string, - arg1: BigNumberish, - overrides?: CallOverrides - ): Promise; - - proxiableUUID(overrides?: CallOverrides): Promise; - - signedTransitState( - newIdentitiesStatesRoot_: BytesLike, - gistData_: ILightweightStateV2.GistRootDataStruct, - proof_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - signer(overrides?: CallOverrides): Promise; - - sourceChainName(overrides?: CallOverrides): Promise; - - sourceStateContract( - overrides?: CallOverrides - ): Promise; - - upgradeTo( - newImplementation: string, - overrides?: Overrides & { from?: string } - ): Promise; - - upgradeToAndCall( - newImplementation: string, - data: BytesLike, - overrides?: PayableOverrides & { from?: string } - ): Promise; - - upgradeToWithSig( - newImplementation_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - - validateChangeAddressSignature( - methodId_: BigNumberish, - contractAddress_: string, - newAddress_: string, - signature_: BytesLike, - overrides?: Overrides & { from?: string } - ): Promise; - }; -} diff --git a/packages/snap/src/types/contracts/StateV2.ts b/packages/snap/src/types/contracts/StateV2.ts deleted file mode 100644 index 4725bd99..00000000 --- a/packages/snap/src/types/contracts/StateV2.ts +++ /dev/null @@ -1,1073 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BigNumber, - BigNumberish, - BytesLike, - CallOverrides, - ContractTransaction, - Overrides, - PopulatedTransaction, - Signer, - utils, -} from "ethers"; -import type { - FunctionFragment, - Result, - EventFragment, -} from "@ethersproject/abi"; -import type { Listener, Provider } from "@ethersproject/providers"; -import type { - TypedEventFilter, - TypedEvent, - TypedListener, - OnEvent, -} from "./common"; - -export declare namespace IState { - export type GistProofStruct = { - root: BigNumberish; - existence: boolean; - siblings: BigNumberish[]; - index: BigNumberish; - value: BigNumberish; - auxExistence: boolean; - auxIndex: BigNumberish; - auxValue: BigNumberish; - }; - - export type GistProofStructOutput = [ - BigNumber, - boolean, - BigNumber[], - BigNumber, - BigNumber, - boolean, - BigNumber, - BigNumber - ] & { - root: BigNumber; - existence: boolean; - siblings: BigNumber[]; - index: BigNumber; - value: BigNumber; - auxExistence: boolean; - auxIndex: BigNumber; - auxValue: BigNumber; - }; - - export type GistRootInfoStruct = { - root: BigNumberish; - replacedByRoot: BigNumberish; - createdAtTimestamp: BigNumberish; - replacedAtTimestamp: BigNumberish; - createdAtBlock: BigNumberish; - replacedAtBlock: BigNumberish; - }; - - export type GistRootInfoStructOutput = [ - BigNumber, - BigNumber, - BigNumber, - BigNumber, - BigNumber, - BigNumber - ] & { - root: BigNumber; - replacedByRoot: BigNumber; - createdAtTimestamp: BigNumber; - replacedAtTimestamp: BigNumber; - createdAtBlock: BigNumber; - replacedAtBlock: BigNumber; - }; - - export type StateInfoStruct = { - id: BigNumberish; - state: BigNumberish; - replacedByState: BigNumberish; - createdAtTimestamp: BigNumberish; - replacedAtTimestamp: BigNumberish; - createdAtBlock: BigNumberish; - replacedAtBlock: BigNumberish; - }; - - export type StateInfoStructOutput = [ - BigNumber, - BigNumber, - BigNumber, - BigNumber, - BigNumber, - BigNumber, - BigNumber - ] & { - id: BigNumber; - state: BigNumber; - replacedByState: BigNumber; - createdAtTimestamp: BigNumber; - replacedAtTimestamp: BigNumber; - createdAtBlock: BigNumber; - replacedAtBlock: BigNumber; - }; -} - -export interface StateV2Interface extends utils.Interface { - functions: { - "VERSION()": FunctionFragment; - "acceptOwnership()": FunctionFragment; - "getGISTProof(uint256)": FunctionFragment; - "getGISTProofByBlock(uint256,uint256)": FunctionFragment; - "getGISTProofByRoot(uint256,uint256)": FunctionFragment; - "getGISTProofByTime(uint256,uint256)": FunctionFragment; - "getGISTRoot()": FunctionFragment; - "getGISTRootHistory(uint256,uint256)": FunctionFragment; - "getGISTRootHistoryLength()": FunctionFragment; - "getGISTRootInfo(uint256)": FunctionFragment; - "getGISTRootInfoByBlock(uint256)": FunctionFragment; - "getGISTRootInfoByTime(uint256)": FunctionFragment; - "getStateInfoById(uint256)": FunctionFragment; - "getStateInfoByIdAndState(uint256,uint256)": FunctionFragment; - "getStateInfoHistoryById(uint256,uint256,uint256)": FunctionFragment; - "getStateInfoHistoryLengthById(uint256)": FunctionFragment; - "getVerifier()": FunctionFragment; - "idExists(uint256)": FunctionFragment; - "initialize(address)": FunctionFragment; - "owner()": FunctionFragment; - "pendingOwner()": FunctionFragment; - "renounceOwnership()": FunctionFragment; - "setVerifier(address)": FunctionFragment; - "stateExists(uint256,uint256)": FunctionFragment; - "transferOwnership(address)": FunctionFragment; - "transitState(uint256,uint256,uint256,bool,uint256[2],uint256[2][2],uint256[2])": FunctionFragment; - }; - - getFunction( - nameOrSignatureOrTopic: - | "VERSION" - | "acceptOwnership" - | "getGISTProof" - | "getGISTProofByBlock" - | "getGISTProofByRoot" - | "getGISTProofByTime" - | "getGISTRoot" - | "getGISTRootHistory" - | "getGISTRootHistoryLength" - | "getGISTRootInfo" - | "getGISTRootInfoByBlock" - | "getGISTRootInfoByTime" - | "getStateInfoById" - | "getStateInfoByIdAndState" - | "getStateInfoHistoryById" - | "getStateInfoHistoryLengthById" - | "getVerifier" - | "idExists" - | "initialize" - | "owner" - | "pendingOwner" - | "renounceOwnership" - | "setVerifier" - | "stateExists" - | "transferOwnership" - | "transitState" - ): FunctionFragment; - - encodeFunctionData(functionFragment: "VERSION", values?: undefined): string; - encodeFunctionData( - functionFragment: "acceptOwnership", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "getGISTProof", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTProofByBlock", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTProofByRoot", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTProofByTime", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTRoot", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "getGISTRootHistory", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTRootHistoryLength", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "getGISTRootInfo", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTRootInfoByBlock", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getGISTRootInfoByTime", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getStateInfoById", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getStateInfoByIdAndState", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getStateInfoHistoryById", - values: [BigNumberish, BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getStateInfoHistoryLengthById", - values: [BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "getVerifier", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "idExists", - values: [BigNumberish] - ): string; - encodeFunctionData(functionFragment: "initialize", values: [string]): string; - encodeFunctionData(functionFragment: "owner", values?: undefined): string; - encodeFunctionData( - functionFragment: "pendingOwner", - values?: undefined - ): string; - encodeFunctionData( - functionFragment: "renounceOwnership", - values?: undefined - ): string; - encodeFunctionData(functionFragment: "setVerifier", values: [string]): string; - encodeFunctionData( - functionFragment: "stateExists", - values: [BigNumberish, BigNumberish] - ): string; - encodeFunctionData( - functionFragment: "transferOwnership", - values: [string] - ): string; - encodeFunctionData( - functionFragment: "transitState", - values: [ - BigNumberish, - BigNumberish, - BigNumberish, - boolean, - [BigNumberish, BigNumberish], - [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - [BigNumberish, BigNumberish] - ] - ): string; - - decodeFunctionResult(functionFragment: "VERSION", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "acceptOwnership", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTProof", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTProofByBlock", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTProofByRoot", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTProofByTime", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRoot", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootHistory", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootHistoryLength", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootInfo", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootInfoByBlock", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getGISTRootInfoByTime", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getStateInfoById", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getStateInfoByIdAndState", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getStateInfoHistoryById", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getStateInfoHistoryLengthById", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "getVerifier", - data: BytesLike - ): Result; - decodeFunctionResult(functionFragment: "idExists", data: BytesLike): Result; - decodeFunctionResult(functionFragment: "initialize", data: BytesLike): Result; - decodeFunctionResult(functionFragment: "owner", data: BytesLike): Result; - decodeFunctionResult( - functionFragment: "pendingOwner", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "renounceOwnership", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "setVerifier", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "stateExists", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "transferOwnership", - data: BytesLike - ): Result; - decodeFunctionResult( - functionFragment: "transitState", - data: BytesLike - ): Result; - - events: { - "Initialized(uint8)": EventFragment; - "OwnershipTransferStarted(address,address)": EventFragment; - "OwnershipTransferred(address,address)": EventFragment; - }; - - getEvent(nameOrSignatureOrTopic: "Initialized"): EventFragment; - getEvent(nameOrSignatureOrTopic: "OwnershipTransferStarted"): EventFragment; - getEvent(nameOrSignatureOrTopic: "OwnershipTransferred"): EventFragment; -} - -export interface InitializedEventObject { - version: number; -} -export type InitializedEvent = TypedEvent<[number], InitializedEventObject>; - -export type InitializedEventFilter = TypedEventFilter; - -export interface OwnershipTransferStartedEventObject { - previousOwner: string; - newOwner: string; -} -export type OwnershipTransferStartedEvent = TypedEvent< - [string, string], - OwnershipTransferStartedEventObject ->; - -export type OwnershipTransferStartedEventFilter = - TypedEventFilter; - -export interface OwnershipTransferredEventObject { - previousOwner: string; - newOwner: string; -} -export type OwnershipTransferredEvent = TypedEvent< - [string, string], - OwnershipTransferredEventObject ->; - -export type OwnershipTransferredEventFilter = - TypedEventFilter; - -export interface StateV2 extends BaseContract { - connect(signerOrProvider: Signer | Provider | string): this; - attach(addressOrName: string): this; - deployed(): Promise; - - interface: StateV2Interface; - - queryFilter( - event: TypedEventFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>; - - listeners( - eventFilter?: TypedEventFilter - ): Array>; - listeners(eventName?: string): Array; - removeAllListeners( - eventFilter: TypedEventFilter - ): this; - removeAllListeners(eventName?: string): this; - off: OnEvent; - on: OnEvent; - once: OnEvent; - removeListener: OnEvent; - - functions: { - VERSION(overrides?: CallOverrides): Promise<[string]>; - - acceptOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - getGISTProof( - id: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistProofStructOutput]>; - - getGISTProofByBlock( - id: BigNumberish, - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistProofStructOutput]>; - - getGISTProofByRoot( - id: BigNumberish, - root: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistProofStructOutput]>; - - getGISTProofByTime( - id: BigNumberish, - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistProofStructOutput]>; - - getGISTRoot(overrides?: CallOverrides): Promise<[BigNumber]>; - - getGISTRootHistory( - start: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistRootInfoStructOutput[]]>; - - getGISTRootHistoryLength(overrides?: CallOverrides): Promise<[BigNumber]>; - - getGISTRootInfo( - root: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistRootInfoStructOutput]>; - - getGISTRootInfoByBlock( - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistRootInfoStructOutput]>; - - getGISTRootInfoByTime( - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.GistRootInfoStructOutput]>; - - getStateInfoById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.StateInfoStructOutput]>; - - getStateInfoByIdAndState( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.StateInfoStructOutput]>; - - getStateInfoHistoryById( - id: BigNumberish, - startIndex: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise<[IState.StateInfoStructOutput[]]>; - - getStateInfoHistoryLengthById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise<[BigNumber]>; - - getVerifier(overrides?: CallOverrides): Promise<[string]>; - - idExists(id: BigNumberish, overrides?: CallOverrides): Promise<[boolean]>; - - initialize( - verifierContractAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - owner(overrides?: CallOverrides): Promise<[string]>; - - pendingOwner(overrides?: CallOverrides): Promise<[string]>; - - renounceOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - setVerifier( - newVerifierAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - stateExists( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise<[boolean]>; - - transferOwnership( - newOwner: string, - overrides?: Overrides & { from?: string } - ): Promise; - - transitState( - id: BigNumberish, - oldState: BigNumberish, - newState: BigNumberish, - isOldStateGenesis: boolean, - a: [BigNumberish, BigNumberish], - b: [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - c: [BigNumberish, BigNumberish], - overrides?: Overrides & { from?: string } - ): Promise; - }; - - VERSION(overrides?: CallOverrides): Promise; - - acceptOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - getGISTProof( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByBlock( - id: BigNumberish, - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByRoot( - id: BigNumberish, - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByTime( - id: BigNumberish, - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootHistory( - start: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootHistoryLength(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByBlock( - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByTime( - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoByIdAndState( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryById( - id: BigNumberish, - startIndex: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryLengthById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getVerifier(overrides?: CallOverrides): Promise; - - idExists(id: BigNumberish, overrides?: CallOverrides): Promise; - - initialize( - verifierContractAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - owner(overrides?: CallOverrides): Promise; - - pendingOwner(overrides?: CallOverrides): Promise; - - renounceOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - setVerifier( - newVerifierAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - stateExists( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - transferOwnership( - newOwner: string, - overrides?: Overrides & { from?: string } - ): Promise; - - transitState( - id: BigNumberish, - oldState: BigNumberish, - newState: BigNumberish, - isOldStateGenesis: boolean, - a: [BigNumberish, BigNumberish], - b: [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - c: [BigNumberish, BigNumberish], - overrides?: Overrides & { from?: string } - ): Promise; - - callStatic: { - VERSION(overrides?: CallOverrides): Promise; - - acceptOwnership(overrides?: CallOverrides): Promise; - - getGISTProof( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByBlock( - id: BigNumberish, - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByRoot( - id: BigNumberish, - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByTime( - id: BigNumberish, - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootHistory( - start: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootHistoryLength(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByBlock( - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByTime( - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoByIdAndState( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryById( - id: BigNumberish, - startIndex: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryLengthById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getVerifier(overrides?: CallOverrides): Promise; - - idExists(id: BigNumberish, overrides?: CallOverrides): Promise; - - initialize( - verifierContractAddr: string, - overrides?: CallOverrides - ): Promise; - - owner(overrides?: CallOverrides): Promise; - - pendingOwner(overrides?: CallOverrides): Promise; - - renounceOwnership(overrides?: CallOverrides): Promise; - - setVerifier( - newVerifierAddr: string, - overrides?: CallOverrides - ): Promise; - - stateExists( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - transferOwnership( - newOwner: string, - overrides?: CallOverrides - ): Promise; - - transitState( - id: BigNumberish, - oldState: BigNumberish, - newState: BigNumberish, - isOldStateGenesis: boolean, - a: [BigNumberish, BigNumberish], - b: [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - c: [BigNumberish, BigNumberish], - overrides?: CallOverrides - ): Promise; - }; - - filters: { - "Initialized(uint8)"(version?: null): InitializedEventFilter; - Initialized(version?: null): InitializedEventFilter; - - "OwnershipTransferStarted(address,address)"( - previousOwner?: string | null, - newOwner?: string | null - ): OwnershipTransferStartedEventFilter; - OwnershipTransferStarted( - previousOwner?: string | null, - newOwner?: string | null - ): OwnershipTransferStartedEventFilter; - - "OwnershipTransferred(address,address)"( - previousOwner?: string | null, - newOwner?: string | null - ): OwnershipTransferredEventFilter; - OwnershipTransferred( - previousOwner?: string | null, - newOwner?: string | null - ): OwnershipTransferredEventFilter; - }; - - estimateGas: { - VERSION(overrides?: CallOverrides): Promise; - - acceptOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - getGISTProof( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByBlock( - id: BigNumberish, - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByRoot( - id: BigNumberish, - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByTime( - id: BigNumberish, - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootHistory( - start: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootHistoryLength(overrides?: CallOverrides): Promise; - - getGISTRootInfo( - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByBlock( - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByTime( - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoByIdAndState( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryById( - id: BigNumberish, - startIndex: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryLengthById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getVerifier(overrides?: CallOverrides): Promise; - - idExists(id: BigNumberish, overrides?: CallOverrides): Promise; - - initialize( - verifierContractAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - owner(overrides?: CallOverrides): Promise; - - pendingOwner(overrides?: CallOverrides): Promise; - - renounceOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - setVerifier( - newVerifierAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - stateExists( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - transferOwnership( - newOwner: string, - overrides?: Overrides & { from?: string } - ): Promise; - - transitState( - id: BigNumberish, - oldState: BigNumberish, - newState: BigNumberish, - isOldStateGenesis: boolean, - a: [BigNumberish, BigNumberish], - b: [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - c: [BigNumberish, BigNumberish], - overrides?: Overrides & { from?: string } - ): Promise; - }; - - populateTransaction: { - VERSION(overrides?: CallOverrides): Promise; - - acceptOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - getGISTProof( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByBlock( - id: BigNumberish, - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByRoot( - id: BigNumberish, - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTProofByTime( - id: BigNumberish, - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRoot(overrides?: CallOverrides): Promise; - - getGISTRootHistory( - start: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootHistoryLength( - overrides?: CallOverrides - ): Promise; - - getGISTRootInfo( - root: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByBlock( - blockNumber: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getGISTRootInfoByTime( - timestamp: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoByIdAndState( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryById( - id: BigNumberish, - startIndex: BigNumberish, - length: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getStateInfoHistoryLengthById( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - getVerifier(overrides?: CallOverrides): Promise; - - idExists( - id: BigNumberish, - overrides?: CallOverrides - ): Promise; - - initialize( - verifierContractAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - owner(overrides?: CallOverrides): Promise; - - pendingOwner(overrides?: CallOverrides): Promise; - - renounceOwnership( - overrides?: Overrides & { from?: string } - ): Promise; - - setVerifier( - newVerifierAddr: string, - overrides?: Overrides & { from?: string } - ): Promise; - - stateExists( - id: BigNumberish, - state: BigNumberish, - overrides?: CallOverrides - ): Promise; - - transferOwnership( - newOwner: string, - overrides?: Overrides & { from?: string } - ): Promise; - - transitState( - id: BigNumberish, - oldState: BigNumberish, - newState: BigNumberish, - isOldStateGenesis: boolean, - a: [BigNumberish, BigNumberish], - b: [[BigNumberish, BigNumberish], [BigNumberish, BigNumberish]], - c: [BigNumberish, BigNumberish], - overrides?: Overrides & { from?: string } - ): Promise; - }; -} diff --git a/packages/snap/src/types/contracts/common.ts b/packages/snap/src/types/contracts/common.ts deleted file mode 100644 index 2fc40c7f..00000000 --- a/packages/snap/src/types/contracts/common.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { Listener } from "@ethersproject/providers"; -import type { Event, EventFilter } from "ethers"; - -export interface TypedEvent< - TArgsArray extends Array = any, - TArgsObject = any -> extends Event { - args: TArgsArray & TArgsObject; -} - -export interface TypedEventFilter<_TEvent extends TypedEvent> - extends EventFilter {} - -export interface TypedListener { - (...listenerArg: [...__TypechainArgsArray, TEvent]): void; -} - -type __TypechainArgsArray = T extends TypedEvent ? U : never; - -export interface OnEvent { - ( - eventFilter: TypedEventFilter, - listener: TypedListener - ): TRes; - (eventName: string, listener: Listener): TRes; -} - -export type MinEthersFactory = { - deploy(...a: ARGS[]): Promise; -}; - -export type GetContractTypeFromFactory = F extends MinEthersFactory< - infer C, - any -> - ? C - : never; - -export type GetARGsTypeFromFactory = F extends MinEthersFactory - ? Parameters - : never; diff --git a/packages/snap/src/types/contracts/factories/LightweightStateV2__factory.ts b/packages/snap/src/types/contracts/factories/LightweightStateV2__factory.ts deleted file mode 100644 index f5d06d63..00000000 --- a/packages/snap/src/types/contracts/factories/LightweightStateV2__factory.ts +++ /dev/null @@ -1,588 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ - -import { Contract, Signer, utils } from "ethers"; -import type { Provider } from "@ethersproject/providers"; -import type { - LightweightStateV2, - LightweightStateV2Interface, -} from "../LightweightStateV2"; - -const _abi = [ - { - anonymous: false, - inputs: [ - { - indexed: false, - internalType: "address", - name: "previousAdmin", - type: "address", - }, - { - indexed: false, - internalType: "address", - name: "newAdmin", - type: "address", - }, - ], - name: "AdminChanged", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: "address", - name: "beacon", - type: "address", - }, - ], - name: "BeaconUpgraded", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: false, - internalType: "uint8", - name: "version", - type: "uint8", - }, - ], - name: "Initialized", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: false, - internalType: "uint256", - name: "newGistRoot", - type: "uint256", - }, - { - indexed: false, - internalType: "bytes32", - name: "newIdentitesStatesRoot", - type: "bytes32", - }, - ], - name: "SignedStateTransited", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: "address", - name: "implementation", - type: "address", - }, - ], - name: "Upgraded", - type: "event", - }, - { - inputs: [], - name: "P", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "signer_", - type: "address", - }, - { - internalType: "address", - name: "sourceStateContract_", - type: "address", - }, - { - internalType: "string", - name: "sourceChainName_", - type: "string", - }, - { - internalType: "string", - name: "chainName_", - type: "string", - }, - ], - name: "__LightweightStateV2_init", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "signer_", - type: "address", - }, - { - internalType: "string", - name: "chainName_", - type: "string", - }, - ], - name: "__Signers_init", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "chainName", - outputs: [ - { - internalType: "string", - name: "", - type: "string", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "bytes", - name: "newSignerPubKey_", - type: "bytes", - }, - { - internalType: "bytes", - name: "signature_", - type: "bytes", - }, - ], - name: "changeSigner", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newSourceStateContract_", - type: "address", - }, - { - internalType: "bytes", - name: "signature_", - type: "bytes", - }, - ], - name: "changeSourceStateContract", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "uint8", - name: "methodId_", - type: "uint8", - }, - { - internalType: "address", - name: "contractAddress_", - type: "address", - }, - { - internalType: "bytes32", - name: "signHash_", - type: "bytes32", - }, - { - internalType: "bytes", - name: "signature_", - type: "bytes", - }, - ], - name: "checkSignatureAndIncrementNonce", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "getCurrentGISTRootInfo", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - ], - internalType: "struct ILightweightStateV2.GistRootData", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "getGISTRoot", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "root_", - type: "uint256", - }, - ], - name: "getGISTRootInfo", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - ], - internalType: "struct ILightweightStateV2.GistRootData", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "bytes32", - name: "root_", - type: "bytes32", - }, - ], - name: "getIdentitiesStatesRootData", - outputs: [ - { - components: [ - { - internalType: "bytes32", - name: "root", - type: "bytes32", - }, - { - internalType: "uint256", - name: "setTimestamp", - type: "uint256", - }, - ], - internalType: "struct ILightweightStateV2.IdentitiesStatesRootData", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint8", - name: "methodId_", - type: "uint8", - }, - { - internalType: "address", - name: "contractAddress_", - type: "address", - }, - ], - name: "getSigComponents", - outputs: [ - { - internalType: "string", - name: "chainName_", - type: "string", - }, - { - internalType: "uint256", - name: "nonce_", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "identitiesStatesRoot", - outputs: [ - { - internalType: "bytes32", - name: "", - type: "bytes32", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "bytes32", - name: "root_", - type: "bytes32", - }, - ], - name: "isIdentitiesStatesRootExists", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - { - internalType: "uint8", - name: "", - type: "uint8", - }, - ], - name: "nonces", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "proxiableUUID", - outputs: [ - { - internalType: "bytes32", - name: "", - type: "bytes32", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "bytes32", - name: "newIdentitiesStatesRoot_", - type: "bytes32", - }, - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - ], - internalType: "struct ILightweightStateV2.GistRootData", - name: "gistData_", - type: "tuple", - }, - { - internalType: "bytes", - name: "proof_", - type: "bytes", - }, - ], - name: "signedTransitState", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "signer", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "sourceChainName", - outputs: [ - { - internalType: "string", - name: "", - type: "string", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "sourceStateContract", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newImplementation", - type: "address", - }, - ], - name: "upgradeTo", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newImplementation", - type: "address", - }, - { - internalType: "bytes", - name: "data", - type: "bytes", - }, - ], - name: "upgradeToAndCall", - outputs: [], - stateMutability: "payable", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newImplementation_", - type: "address", - }, - { - internalType: "bytes", - name: "signature_", - type: "bytes", - }, - ], - name: "upgradeToWithSig", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "uint8", - name: "methodId_", - type: "uint8", - }, - { - internalType: "address", - name: "contractAddress_", - type: "address", - }, - { - internalType: "address", - name: "newAddress_", - type: "address", - }, - { - internalType: "bytes", - name: "signature_", - type: "bytes", - }, - ], - name: "validateChangeAddressSignature", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, -] as const; - -export class LightweightStateV2__factory { - static readonly abi = _abi; - static createInterface(): LightweightStateV2Interface { - return new utils.Interface(_abi) as LightweightStateV2Interface; - } - static connect( - address: string, - signerOrProvider: Signer | Provider - ): LightweightStateV2 { - return new Contract(address, _abi, signerOrProvider) as LightweightStateV2; - } -} diff --git a/packages/snap/src/types/contracts/factories/StateV2__factory.ts b/packages/snap/src/types/contracts/factories/StateV2__factory.ts deleted file mode 100644 index dd1fd1c8..00000000 --- a/packages/snap/src/types/contracts/factories/StateV2__factory.ts +++ /dev/null @@ -1,966 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ - -import { Contract, Signer, utils } from "ethers"; -import type { Provider } from "@ethersproject/providers"; -import type { StateV2, StateV2Interface } from "../StateV2"; - -const _abi = [ - { - inputs: [], - stateMutability: "nonpayable", - type: "constructor", - }, - { - anonymous: false, - inputs: [ - { - indexed: false, - internalType: "uint8", - name: "version", - type: "uint8", - }, - ], - name: "Initialized", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: "address", - name: "previousOwner", - type: "address", - }, - { - indexed: true, - internalType: "address", - name: "newOwner", - type: "address", - }, - ], - name: "OwnershipTransferStarted", - type: "event", - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: "address", - name: "previousOwner", - type: "address", - }, - { - indexed: true, - internalType: "address", - name: "newOwner", - type: "address", - }, - ], - name: "OwnershipTransferred", - type: "event", - }, - { - inputs: [], - name: "VERSION", - outputs: [ - { - internalType: "string", - name: "", - type: "string", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "acceptOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - ], - name: "getGISTProof", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "bool", - name: "existence", - type: "bool", - }, - { - internalType: "uint256[64]", - name: "siblings", - type: "uint256[64]", - }, - { - internalType: "uint256", - name: "index", - type: "uint256", - }, - { - internalType: "uint256", - name: "value", - type: "uint256", - }, - { - internalType: "bool", - name: "auxExistence", - type: "bool", - }, - { - internalType: "uint256", - name: "auxIndex", - type: "uint256", - }, - { - internalType: "uint256", - name: "auxValue", - type: "uint256", - }, - ], - internalType: "struct IState.GistProof", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "blockNumber", - type: "uint256", - }, - ], - name: "getGISTProofByBlock", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "bool", - name: "existence", - type: "bool", - }, - { - internalType: "uint256[64]", - name: "siblings", - type: "uint256[64]", - }, - { - internalType: "uint256", - name: "index", - type: "uint256", - }, - { - internalType: "uint256", - name: "value", - type: "uint256", - }, - { - internalType: "bool", - name: "auxExistence", - type: "bool", - }, - { - internalType: "uint256", - name: "auxIndex", - type: "uint256", - }, - { - internalType: "uint256", - name: "auxValue", - type: "uint256", - }, - ], - internalType: "struct IState.GistProof", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - ], - name: "getGISTProofByRoot", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "bool", - name: "existence", - type: "bool", - }, - { - internalType: "uint256[64]", - name: "siblings", - type: "uint256[64]", - }, - { - internalType: "uint256", - name: "index", - type: "uint256", - }, - { - internalType: "uint256", - name: "value", - type: "uint256", - }, - { - internalType: "bool", - name: "auxExistence", - type: "bool", - }, - { - internalType: "uint256", - name: "auxIndex", - type: "uint256", - }, - { - internalType: "uint256", - name: "auxValue", - type: "uint256", - }, - ], - internalType: "struct IState.GistProof", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "timestamp", - type: "uint256", - }, - ], - name: "getGISTProofByTime", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "bool", - name: "existence", - type: "bool", - }, - { - internalType: "uint256[64]", - name: "siblings", - type: "uint256[64]", - }, - { - internalType: "uint256", - name: "index", - type: "uint256", - }, - { - internalType: "uint256", - name: "value", - type: "uint256", - }, - { - internalType: "bool", - name: "auxExistence", - type: "bool", - }, - { - internalType: "uint256", - name: "auxIndex", - type: "uint256", - }, - { - internalType: "uint256", - name: "auxValue", - type: "uint256", - }, - ], - internalType: "struct IState.GistProof", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "getGISTRoot", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "start", - type: "uint256", - }, - { - internalType: "uint256", - name: "length", - type: "uint256", - }, - ], - name: "getGISTRootHistory", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByRoot", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.GistRootInfo[]", - name: "", - type: "tuple[]", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "getGISTRootHistoryLength", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - ], - name: "getGISTRootInfo", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByRoot", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.GistRootInfo", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "blockNumber", - type: "uint256", - }, - ], - name: "getGISTRootInfoByBlock", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByRoot", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.GistRootInfo", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "timestamp", - type: "uint256", - }, - ], - name: "getGISTRootInfoByTime", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "root", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByRoot", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.GistRootInfo", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - ], - name: "getStateInfoById", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "state", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByState", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.StateInfo", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "state", - type: "uint256", - }, - ], - name: "getStateInfoByIdAndState", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "state", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByState", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.StateInfo", - name: "", - type: "tuple", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "startIndex", - type: "uint256", - }, - { - internalType: "uint256", - name: "length", - type: "uint256", - }, - ], - name: "getStateInfoHistoryById", - outputs: [ - { - components: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "state", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedByState", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtTimestamp", - type: "uint256", - }, - { - internalType: "uint256", - name: "createdAtBlock", - type: "uint256", - }, - { - internalType: "uint256", - name: "replacedAtBlock", - type: "uint256", - }, - ], - internalType: "struct IState.StateInfo[]", - name: "", - type: "tuple[]", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - ], - name: "getStateInfoHistoryLengthById", - outputs: [ - { - internalType: "uint256", - name: "", - type: "uint256", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "getVerifier", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - ], - name: "idExists", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "contract IStateTransitionVerifier", - name: "verifierContractAddr", - type: "address", - }, - ], - name: "initialize", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [], - name: "owner", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "pendingOwner", - outputs: [ - { - internalType: "address", - name: "", - type: "address", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [], - name: "renounceOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newVerifierAddr", - type: "address", - }, - ], - name: "setVerifier", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "state", - type: "uint256", - }, - ], - name: "stateExists", - outputs: [ - { - internalType: "bool", - name: "", - type: "bool", - }, - ], - stateMutability: "view", - type: "function", - }, - { - inputs: [ - { - internalType: "address", - name: "newOwner", - type: "address", - }, - ], - name: "transferOwnership", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, - { - inputs: [ - { - internalType: "uint256", - name: "id", - type: "uint256", - }, - { - internalType: "uint256", - name: "oldState", - type: "uint256", - }, - { - internalType: "uint256", - name: "newState", - type: "uint256", - }, - { - internalType: "bool", - name: "isOldStateGenesis", - type: "bool", - }, - { - internalType: "uint256[2]", - name: "a", - type: "uint256[2]", - }, - { - internalType: "uint256[2][2]", - name: "b", - type: "uint256[2][2]", - }, - { - internalType: "uint256[2]", - name: "c", - type: "uint256[2]", - }, - ], - name: "transitState", - outputs: [], - stateMutability: "nonpayable", - type: "function", - }, -] as const; - -export class StateV2__factory { - static readonly abi = _abi; - static createInterface(): StateV2Interface { - return new utils.Interface(_abi) as StateV2Interface; - } - static connect( - address: string, - signerOrProvider: Signer | Provider - ): StateV2 { - return new Contract(address, _abi, signerOrProvider) as StateV2; - } -} diff --git a/packages/snap/src/types/contracts/factories/index.ts b/packages/snap/src/types/contracts/factories/index.ts deleted file mode 100644 index f26bc134..00000000 --- a/packages/snap/src/types/contracts/factories/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export { LightweightStateV2__factory } from "./LightweightStateV2__factory"; -export { StateV2__factory } from "./StateV2__factory"; diff --git a/packages/snap/src/types/contracts/index.ts b/packages/snap/src/types/contracts/index.ts deleted file mode 100644 index 36c3c77b..00000000 --- a/packages/snap/src/types/contracts/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export type { LightweightStateV2 } from "./LightweightStateV2"; -export type { StateV2 } from "./StateV2"; -export * as factories from "./factories"; -export { LightweightStateV2__factory } from "./factories/LightweightStateV2__factory"; -export { StateV2__factory } from "./factories/StateV2__factory"; diff --git a/packages/snap/src/types/credential-types.ts b/packages/snap/src/types/credential-types.ts deleted file mode 100644 index 1d95035d..00000000 --- a/packages/snap/src/types/credential-types.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* eslint-disable jsdoc/check-tag-names */ -import type { Proof } from '@iden3/js-merkletree'; - -export type { SaveCredentialsRequestParams } from '@rarimo/rarime-connector'; - -export type CredentialStatus = { - id: string; - type: string; - revocationNonce?: number; - statusIssuer?: CredentialStatus; -}; - -export type CredentialSchema = { - id: string; - type: string; -}; - -export type W3CCredential = { - id: string; - '@context': string[]; - type: string[]; - expirationDate?: string; - issuanceDate?: string; - credentialSubject: { [key: string]: object | string | number }; - credentialStatus: CredentialStatus; - issuer: string; - credentialSchema: CredentialSchema; - proof?: { [key: string]: any } | any[]; -}; - -export type ClaimOffer = { - body: { - Credentials: [ - { - description: string; - id: string; - }, - ]; - /** - * - * @format - * url - */ - url: string; - }; - from: string; - id: string; - threadID?: string; - to: string; - typ?: string; - type: string; -}; - -export type Issuer = { - state?: string; - rootOfRoots?: string; - claimsTreeRoot?: string; - revocationTreeRoot?: string; -}; - -export type RevocationStatus = { - mtp: Proof; - issuer: Issuer; -}; diff --git a/packages/snap/src/types/global-types.ts b/packages/snap/src/types/global-types.ts index e399502a..85957f7e 100644 --- a/packages/snap/src/types/global-types.ts +++ b/packages/snap/src/types/global-types.ts @@ -1,23 +1,6 @@ import type { NodeType } from '@metamask/snaps-sdk'; -import type { providers } from 'ethers'; export type TextField = { value: string; type: NodeType.Text; }; - -declare global { - // eslint-disable-next-line @typescript-eslint/consistent-type-definitions - interface Window { - ethereum: providers.ExternalProvider; - } -} - -export type RarimoNetworkType = 'mainnet' | 'beta'; - -export type ChainInfo = { - id: number; - rpcUrl: string; - stateContractAddress: string; - rarimoNetworkType: RarimoNetworkType; -}; diff --git a/packages/snap/src/types/index.ts b/packages/snap/src/types/index.ts index 75419b09..1c16bc64 100644 --- a/packages/snap/src/types/index.ts +++ b/packages/snap/src/types/index.ts @@ -1,6 +1,2 @@ -export * from './credential-types'; -export * from './contracts'; -export * from './proof-types'; export * from './global-types'; -export * from './state-types'; -export * from './graphql'; +export * from './storage'; diff --git a/packages/snap/src/types/proof-types.ts b/packages/snap/src/types/proof-types.ts deleted file mode 100644 index 7fcbb07c..00000000 --- a/packages/snap/src/types/proof-types.ts +++ /dev/null @@ -1,100 +0,0 @@ -import type { Signature } from '@iden3/js-crypto'; -import type { Claim } from '@iden3/js-iden3-core'; -import type { Hash, Proof } from '@iden3/js-merkletree'; -import type { ProofQuery } from '@rarimo/rarime-connector'; - -import type { CircuitId } from '../enums'; -import type { Query } from '../helpers'; - -export type CreateProofRequest = { - id?: number; - accountAddress?: string; - circuitId: CircuitId; - challenge?: string; // bigint string - query: ProofQuery; -}; - -export type CreateProofRequestParams = { - issuerDid: string; -} & CreateProofRequest; - -export type State = { - txId?: string; - blockTimestamp?: number; - blockNumber?: number; - rootOfRoots: string; - claimsTreeRoot: string; - revocationTreeRoot: string; - value: string; - status?: string; -}; - -export type TreeState = { - state: Hash; - claimsRoot: Hash; - revocationRoot: Hash; - rootOfRoots: Hash; -}; - -export type ClaimNonRevStatus = { - treeState: TreeState; - proof: Proof; -}; - -export type MTProof = { - proof: Proof; - treeState?: TreeState; -}; - -export type BJJSignatureProof = { - signature: Signature; - issuerAuthClaim?: Claim; - issuerAuthIncProof: MTProof; - issuerAuthNonRevProof: MTProof; -}; - -export type QueryWithFieldName = { - query: Query; - fieldName: string; - isSelectiveDisclosure?: boolean; -}; - -export type SerializationSchema = { - indexDataSlotA: string; - indexDataSlotB: string; - valueDataSlotA: string; - valueDataSlotB: string; -}; - -export type SchemaMetadata = { - uris: { [key: string]: string }; - serialization?: SerializationSchema; -}; - -export type JSONSchema = { - $metadata: SchemaMetadata; - $schema: string; - type: string; -}; - -export type NodeAuxValue = { - key: Hash; - value: Hash; - noAux: string; -}; - -export type StateProof = { - root: bigint; - existence: boolean; - siblings: bigint[]; - index: bigint; - value: bigint; - auxExistence: boolean; - auxIndex: bigint; - auxValue: bigint; -}; - -export type GISTProof = { - root: Hash; - proof: Proof; -}; diff --git a/packages/snap/src/types/state-types.ts b/packages/snap/src/types/state-types.ts deleted file mode 100644 index 65b01c76..00000000 --- a/packages/snap/src/types/state-types.ts +++ /dev/null @@ -1,47 +0,0 @@ -export type MerkleProof = { - proof: string[]; -}; - -export type StateInfo = { - index: string; - hash: string; - createdAtTimestamp: string; - createdAtBlock: string; - lastUpdateOperationIndex: string; -}; - -export type GetStateInfoResponse = { - state: StateInfo; -}; - -export type OperationProof = { - path: string[]; - signature: string; -}; - -export enum OperationStatus { - Signed = 'SIGNED', - Initialized = 'INITIALIZED', - Approved = 'APPROVED', - NotApproved = 'NOT_APPROVED', -} - -export type Operation = { - index: string; - operationType: string; - details: { - '@type': string; - contract: string; - chain: string; - GISTHash: string; - stateRootHash: string; - timestamp: string; - }; - status: OperationStatus; - creator: string; - timestamp: string; -}; - -export type OperationResponse = { - operation: Operation; -}; diff --git a/packages/snap/src/types/storage.ts b/packages/snap/src/types/storage.ts new file mode 100644 index 00000000..8f4b69f4 --- /dev/null +++ b/packages/snap/src/types/storage.ts @@ -0,0 +1,14 @@ +import type { ChainInfo } from '@rarimo/rarime-connector'; +import type { W3CCredential } from '@rarimo/zkp-iden3'; + +import type { StorageKeys } from '@/enums'; + +export type StorageMap = { + [StorageKeys.identity]: { + privateKeyHex: string; + did: string; + didBigInt: string; + }; + [StorageKeys.credentials]: W3CCredential[]; + [StorageKeys.chains]: Record; +}; diff --git a/packages/snap/src/typia-generated/is-param.ts b/packages/snap/src/typia-generated/is-param.ts index be8b22cc..f6895332 100644 --- a/packages/snap/src/typia-generated/is-param.ts +++ b/packages/snap/src/typia-generated/is-param.ts @@ -1,5 +1,9 @@ import typia from 'typia'; -import { CreateProofRequest, SaveCredentialsRequestParams } from '../types'; +import { + CreateProofRequest, + SaveCredentialsRequestParams, +} from '@rarimo/rarime-connector'; + const formatErrorMessages = (errors: typia.IValidation.IError[]): string => { let errorMessage = 'invalid_argument: '; for (let i = 0; i < errors.length; i += 1) { diff --git a/packages/snap/src/typia-templates/is-param.ts b/packages/snap/src/typia-templates/is-param.ts index c0e7ed4b..7231b4af 100644 --- a/packages/snap/src/typia-templates/is-param.ts +++ b/packages/snap/src/typia-templates/is-param.ts @@ -1,9 +1,8 @@ -import typia from 'typia'; - import type { SaveCredentialsRequestParams, CreateProofRequest, -} from '../types'; +} from '@rarimo/rarime-connector'; +import typia from 'typia'; const formatErrorMessages = (errors: typia.IValidation.IError[]): string => { let errorMessage = 'invalid_argument: '; diff --git a/packages/snap/src/zkp-gen.ts b/packages/snap/src/zkp-gen.ts deleted file mode 100644 index 82917942..00000000 --- a/packages/snap/src/zkp-gen.ts +++ /dev/null @@ -1,555 +0,0 @@ -import type { Signature } from '@iden3/js-crypto'; -import { Hex } from '@iden3/js-crypto'; -import { fromLittleEndian } from '@iden3/js-iden3-core'; -import { proving, type ZKProof } from '@iden3/js-jwz'; - -import { config } from './config'; -import { - defaultMTLevels, - defaultMTLevelsClaimsMerklization, - defaultMTLevelsOnChain, - defaultValueArraySize, -} from './const'; -import { CircuitId } from './enums'; -import { - buildTreeState, - getGISTProof, - getNodeAuxValue, - getPreparedCredential, - getProviderChainInfo, - getRarimoEvmRpcUrl, - getRarimoStateContractAddress, - getFileBytes, - newCircuitClaimData, - prepareCircuitArrayValues, - prepareSiblingsStr, - toCircuitsQuery, - toGISTProof, -} from './helpers'; -import type { CircuitClaim, Query } from './helpers'; -import { type Identity } from './identity'; -import type { - ClaimNonRevStatus, - CreateProofRequest, - GISTProof, - NodeAuxValue, - W3CCredential, -} from './types'; - -export class ZkpGen { - identity: Identity = {} as Identity; - - verifiableCredential: W3CCredential = {} as W3CCredential; - - subjectProof: ZKProof = {} as ZKProof; - - proofRequest: CreateProofRequest = {} as CreateProofRequest; - - circuitClaimData: CircuitClaim = {} as CircuitClaim; - - query: Query = {} as Query; - - nodeAuxIssuerAuthNonRev: NodeAuxValue = {} as NodeAuxValue; - - nodeAuxNonRev: NodeAuxValue = {} as NodeAuxValue; - - nodAuxJSONLD: NodeAuxValue = {} as NodeAuxValue; - - nonRevProof: ClaimNonRevStatus = {} as ClaimNonRevStatus; - - value: string[] = []; - - timestamp?: number; - - gistProof?: GISTProof; - - challenge?: bigint; - - signatureChallenge?: Signature; - - globalNodeAux?: NodeAuxValue; - - nodeAuxAuth?: NodeAuxValue; - - constructor( - identity: Identity, - proofRequest: CreateProofRequest, - verifiableCredential: W3CCredential, - ) { - this.identity = identity; - this.verifiableCredential = verifiableCredential; - this.proofRequest = proofRequest; - } - - async generateProof(coreStateHash: string, operationGistHash: string) { - const preparedCredential = await getPreparedCredential( - this.verifiableCredential, - ); - - this.circuitClaimData = await newCircuitClaimData( - preparedCredential.credential, - preparedCredential.credentialCoreClaim, - coreStateHash, - ); - - this.query = await toCircuitsQuery( - this.proofRequest.query, - preparedCredential.credential, - preparedCredential.credentialCoreClaim, - ); - - this.nonRevProof = { - proof: preparedCredential.revStatus.mtp, - treeState: buildTreeState( - preparedCredential.revStatus.issuer.state!, - preparedCredential.revStatus.issuer.claimsTreeRoot!, - preparedCredential.revStatus.issuer.revocationTreeRoot!, - preparedCredential.revStatus.issuer.rootOfRoots!, - ), - }; - - this.timestamp = Math.floor(Date.now() / 1000); - - this.nodeAuxIssuerAuthNonRev = getNodeAuxValue( - this.circuitClaimData.signatureProof.issuerAuthNonRevProof.proof, - ); - this.nodeAuxNonRev = getNodeAuxValue(this.nonRevProof.proof); - this.nodAuxJSONLD = getNodeAuxValue(this.query.valueProof!.mtp); - this.value = prepareCircuitArrayValues( - this.query.values, - defaultValueArraySize, - ).map((a) => a.toString()); - - if ( - this.proofRequest.circuitId === CircuitId.AtomicQuerySigV2OnChain || - this.proofRequest.circuitId === CircuitId.AtomicQueryMTPV2OnChain - ) { - const providerChainInfo = await getProviderChainInfo(); - - const gistInfo = await getGISTProof({ - rpcUrl: getRarimoEvmRpcUrl(providerChainInfo.id), - contractAddress: getRarimoStateContractAddress(providerChainInfo.id), - userId: this.identity.identityIdBigIntString, - rootHash: operationGistHash, - }); - this.gistProof = toGISTProof(gistInfo); - - const challenge = fromLittleEndian( - Hex.decodeString(this.proofRequest.accountAddress!.substring(2)), - ).toString(); - this.challenge = BigInt(this.proofRequest.challenge ?? challenge); - - this.signatureChallenge = this.identity.privateKey.signPoseidon( - this.challenge, - ); - - this.globalNodeAux = getNodeAuxValue(this.gistProof.proof); - this.nodeAuxAuth = getNodeAuxValue(this.identity.authClaimNonRevProof); - } - - const circuiInfo = this.getCircuitInfo(); - - const [wasm, provingKey] = await Promise.all([ - getFileBytes(circuiInfo.wasm), - getFileBytes(circuiInfo.finalKey), - ]); - this.subjectProof = await proving.provingMethodGroth16AuthV2Instance.prove( - new TextEncoder().encode(circuiInfo.generateInputFn()), - provingKey, - wasm, - ); - - return this.subjectProof; - } - - getCircuitInfo() { - switch (this.proofRequest.circuitId) { - case CircuitId.AtomicQuerySigV2OnChain: - return { - wasm: config.CIRCUIT_SIG_V2_ON_CHAIN_WASM_URL, - finalKey: config.CIRCUIT_SIG_V2_ON_CHAIN_FINAL_KEY_URL, - generateInputFn: this.generateQuerySigV2OnChainInputs.bind(this), - }; - case CircuitId.AtomicQuerySigV2: - return { - wasm: config.CIRCUIT_SIG_V2_WASM_URL, - finalKey: config.CIRCUIT_SIG_V2_FINAL_KEY_URL, - generateInputFn: this.generateQuerySigV2Inputs.bind(this), - }; - case CircuitId.AtomicQueryMTPV2: - return { - wasm: config.CIRCUIT_MTP_V2_WASM_URL, - finalKey: config.CIRCUIT_MTP_V2_FINAL_KEY_URL, - generateInputFn: this.generateQueryMTPV2Inputs.bind(this), - }; - case CircuitId.AtomicQueryMTPV2OnChain: - return { - wasm: config.CIRCUIT_MTP_V2_ON_CHAIN_WASM_URL, - finalKey: config.CIRCUIT_MTP_V2_ON_CHAIN_FINAL_KEY_URL, - generateInputFn: this.generateQueryMTPV2OnChainInputs.bind(this), - }; - default: - throw new Error( - `circuit with id ${this.proofRequest.circuitId} is not supported by issuer`, - ); - } - } - - generateQuerySigV2OnChainInputs() { - return JSON.stringify({ - /* we have no constraints for "requestID" in this circuit, it is used as a unique identifier for the request */ - /* and verifier can use it to identify the request, and verify the proof of specific request in case of multiple query requests */ - requestID: this.proofRequest.id?.toString || '1', - - userGenesisID: this.identity.identityIdBigIntString, - profileNonce: '0', - - userState: this.identity.treeState.state, - userClaimsTreeRoot: this.identity.treeState.claimsRoot, - userRevTreeRoot: this.identity.treeState.revocationRoot, - userRootsTreeRoot: this.identity.treeState.rootOfRoots, - - authClaim: this.identity.coreAuthClaim.marshalJson(), - - authClaimIncMtp: this.identity.authClaimIncProofSiblings, - - authClaimNonRevMtp: prepareSiblingsStr( - this.identity.authClaimNonRevProof, - defaultMTLevels, - ), - authClaimNonRevMtpAuxHi: this.nodeAuxAuth?.key.string(), - authClaimNonRevMtpAuxHv: this.nodeAuxAuth?.value.string(), - authClaimNonRevMtpNoAux: this.nodeAuxAuth?.noAux, - - challenge: this.challenge?.toString(), - challengeSignatureR8x: this.signatureChallenge?.R8[0].toString(), - challengeSignatureR8y: this.signatureChallenge?.R8[1].toString(), - challengeSignatureS: this.signatureChallenge?.S.toString(), - - gistRoot: this.gistProof?.root.string(), - gistMtp: prepareSiblingsStr( - this.gistProof!.proof, - defaultMTLevelsOnChain, - ), - gistMtpAuxHi: this.globalNodeAux?.key.string(), - gistMtpAuxHv: this.globalNodeAux?.value.string(), - gistMtpNoAux: this.globalNodeAux?.noAux, - - claimSubjectProfileNonce: '0', - - issuerID: this.circuitClaimData.issuerId.bigInt().toString(), - - issuerAuthClaim: - this.circuitClaimData.signatureProof.issuerAuthClaim?.marshalJson(), - issuerAuthClaimMtp: prepareSiblingsStr( - this.circuitClaimData.signatureProof.issuerAuthIncProof.proof, - defaultMTLevels, - ), - issuerAuthClaimsTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.claimsRoot.string(), - issuerAuthRevTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.revocationRoot.string(), - issuerAuthRootsTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.rootOfRoots.string(), - - issuerAuthClaimNonRevMtp: prepareSiblingsStr( - this.circuitClaimData.signatureProof.issuerAuthNonRevProof.proof, - defaultMTLevels, - ), - issuerAuthClaimNonRevMtpNoAux: this.nodeAuxIssuerAuthNonRev.noAux, - issuerAuthClaimNonRevMtpAuxHi: this.nodeAuxIssuerAuthNonRev.key.string(), - issuerAuthClaimNonRevMtpAuxHv: - this.nodeAuxIssuerAuthNonRev.value.string(), - - issuerClaim: this.circuitClaimData.claim.marshalJson(), - isRevocationChecked: '1', - issuerClaimNonRevMtp: prepareSiblingsStr( - this.nonRevProof.proof, - defaultMTLevels, - ), - issuerClaimNonRevMtpNoAux: this.nodeAuxNonRev.noAux, - issuerClaimNonRevMtpAuxHi: this.nodeAuxNonRev.key.string(), - issuerClaimNonRevMtpAuxHv: this.nodeAuxNonRev.value.string(), - issuerClaimNonRevClaimsTreeRoot: - this.nonRevProof.treeState.claimsRoot.string(), - issuerClaimNonRevRevTreeRoot: - this.nonRevProof.treeState.revocationRoot.string(), - issuerClaimNonRevRootsTreeRoot: - this.nonRevProof.treeState.rootOfRoots.string(), - issuerClaimNonRevState: this.nonRevProof.treeState.state.string(), - - issuerClaimSignatureR8x: - this.circuitClaimData.signatureProof.signature.R8[0].toString(), - issuerClaimSignatureR8y: - this.circuitClaimData.signatureProof.signature.R8[1].toString(), - issuerClaimSignatureS: - this.circuitClaimData.signatureProof.signature.S.toString(), - - timestamp: this.timestamp, - - claimSchema: this.circuitClaimData.claim - .getSchemaHash() - .bigInt() - .toString(), - claimPathNotExists: this.query.valueProof?.mtp.existence ? 0 : 1, - claimPathMtp: prepareSiblingsStr( - this.query.valueProof!.mtp, - defaultMTLevelsClaimsMerklization, - ), - claimPathMtpNoAux: this.nodAuxJSONLD.noAux, - claimPathMtpAuxHi: this.nodAuxJSONLD.key.string(), - claimPathMtpAuxHv: this.nodAuxJSONLD.value.string(), - claimPathKey: this.query.valueProof?.path.toString(), - claimPathValue: this.query.valueProof?.value?.toString(), - - slotIndex: this.query.slotIndex, - operator: this.query.operator, - value: this.value, - }); - } - - generateQuerySigV2Inputs() { - return JSON.stringify({ - /* we have no constraints for "requestID" in this circuit, it is used as a unique identifier for the request */ - /* and verifier can use it to identify the request, and verify the proof of specific request in case of multiple query requests */ - requestID: this.proofRequest.id?.toString || '1', - - userGenesisID: this.identity.identityIdBigIntString, - profileNonce: '0', - - claimSubjectProfileNonce: '0', - - issuerID: this.circuitClaimData.issuerId.bigInt().toString(), - - issuerAuthClaim: - this.circuitClaimData.signatureProof.issuerAuthClaim?.marshalJson(), - issuerAuthClaimMtp: prepareSiblingsStr( - this.circuitClaimData.signatureProof.issuerAuthIncProof.proof, - defaultMTLevels, - ), - issuerAuthClaimsTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.claimsRoot.string(), - issuerAuthRevTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.revocationRoot.string(), - issuerAuthRootsTreeRoot: - this.circuitClaimData.signatureProof.issuerAuthIncProof.treeState?.rootOfRoots.string(), - - issuerAuthClaimNonRevMtp: prepareSiblingsStr( - this.circuitClaimData.signatureProof.issuerAuthNonRevProof.proof, - defaultMTLevels, - ), - issuerAuthClaimNonRevMtpNoAux: this.nodeAuxIssuerAuthNonRev.noAux, - issuerAuthClaimNonRevMtpAuxHi: this.nodeAuxIssuerAuthNonRev.key.string(), - issuerAuthClaimNonRevMtpAuxHv: - this.nodeAuxIssuerAuthNonRev.value.string(), - - issuerClaim: this.circuitClaimData.claim.marshalJson(), - isRevocationChecked: '1', - issuerClaimNonRevMtp: prepareSiblingsStr( - this.nonRevProof.proof, - defaultMTLevels, - ), - issuerClaimNonRevMtpNoAux: this.nodeAuxNonRev.noAux, - issuerClaimNonRevMtpAuxHi: this.nodeAuxNonRev.key.string(), - issuerClaimNonRevMtpAuxHv: this.nodeAuxNonRev.value.string(), - issuerClaimNonRevClaimsTreeRoot: - this.nonRevProof.treeState.claimsRoot.string(), - issuerClaimNonRevRevTreeRoot: - this.nonRevProof.treeState.revocationRoot.string(), - issuerClaimNonRevRootsTreeRoot: - this.nonRevProof.treeState.rootOfRoots.string(), - issuerClaimNonRevState: this.nonRevProof.treeState.state.string(), - - issuerClaimSignatureR8x: - this.circuitClaimData.signatureProof.signature.R8[0].toString(), - issuerClaimSignatureR8y: - this.circuitClaimData.signatureProof.signature.R8[1].toString(), - issuerClaimSignatureS: - this.circuitClaimData.signatureProof.signature.S.toString(), - - timestamp: this.timestamp, - - claimSchema: this.circuitClaimData.claim - .getSchemaHash() - .bigInt() - .toString(), - claimPathNotExists: this.query.valueProof?.mtp.existence ? 0 : 1, - claimPathMtp: prepareSiblingsStr( - this.query.valueProof!.mtp, - defaultMTLevelsClaimsMerklization, - ), - claimPathMtpNoAux: this.nodAuxJSONLD.noAux, - claimPathMtpAuxHi: this.nodAuxJSONLD.key.string(), - claimPathMtpAuxHv: this.nodAuxJSONLD.value.string(), - claimPathKey: this.query.valueProof?.path.toString(), - claimPathValue: this.query.valueProof?.value?.toString(), - - slotIndex: this.query.slotIndex, - operator: this.query.operator, - value: this.value, - }); - } - - generateQueryMTPV2Inputs() { - return JSON.stringify({ - /* we have no constraints for "requestID" in this circuit, it is used as a unique identifier for the request */ - /* and verifier can use it to identify the request, and verify the proof of specific request in case of multiple query requests */ - requestID: this.proofRequest.id?.toString || '1', - - userGenesisID: this.identity.identityIdBigIntString, - profileNonce: '0', - - claimSubjectProfileNonce: '0', - - issuerID: this.circuitClaimData.issuerId.bigInt().toString(), - - issuerClaim: this.circuitClaimData.claim.marshalJson(), - isRevocationChecked: '1', - issuerClaimNonRevMtp: prepareSiblingsStr( - this.nonRevProof.proof, - defaultMTLevels, - ), - issuerClaimNonRevMtpNoAux: this.nodeAuxNonRev.noAux, - issuerClaimNonRevMtpAuxHi: this.nodeAuxNonRev.key.string(), - issuerClaimNonRevMtpAuxHv: this.nodeAuxNonRev.value.string(), - issuerClaimNonRevClaimsTreeRoot: - this.nonRevProof.treeState.claimsRoot.string(), - issuerClaimNonRevRevTreeRoot: - this.nonRevProof.treeState.revocationRoot.string(), - issuerClaimNonRevRootsTreeRoot: - this.nonRevProof.treeState.rootOfRoots.string(), - issuerClaimNonRevState: this.nonRevProof.treeState.state.string(), - - issuerClaimMtp: prepareSiblingsStr( - this.circuitClaimData.incProof.proof, - defaultMTLevels, - ), - issuerClaimClaimsTreeRoot: - this.circuitClaimData.incProof.treeState?.claimsRoot.string(), - issuerClaimRevTreeRoot: - this.circuitClaimData.incProof.treeState?.revocationRoot.string(), - issuerClaimRootsTreeRoot: - this.circuitClaimData.incProof.treeState?.rootOfRoots.string(), - issuerClaimIdenState: - this.circuitClaimData.incProof.treeState?.state.string(), - - timestamp: this.timestamp, - - claimSchema: this.circuitClaimData.claim - .getSchemaHash() - .bigInt() - .toString(), - claimPathNotExists: this.query.valueProof?.mtp.existence ? 0 : 1, - claimPathMtp: prepareSiblingsStr( - this.query.valueProof!.mtp, - defaultMTLevelsClaimsMerklization, - ), - claimPathMtpNoAux: this.nodAuxJSONLD.noAux, - claimPathMtpAuxHi: this.nodAuxJSONLD.key.string(), - claimPathMtpAuxHv: this.nodAuxJSONLD.value.string(), - claimPathKey: this.query.valueProof?.path.toString(), - claimPathValue: this.query.valueProof?.value?.toString(), - - slotIndex: this.query.slotIndex, - operator: this.query.operator, - value: this.value, - }); - } - - generateQueryMTPV2OnChainInputs() { - return JSON.stringify({ - /* we have no constraints for "requestID" in this circuit, it is used as a unique identifier for the request */ - /* and verifier can use it to identify the request, and verify the proof of specific request in case of multiple query requests */ - requestID: this.proofRequest.id?.toString || '1', - - userGenesisID: this.identity.identityIdBigIntString, - profileNonce: '0', - - userState: this.identity.treeState.state, - userClaimsTreeRoot: this.identity.treeState.claimsRoot, - userRevTreeRoot: this.identity.treeState.revocationRoot, - userRootsTreeRoot: this.identity.treeState.rootOfRoots, - - authClaim: this.identity.coreAuthClaim.marshalJson(), - - authClaimIncMtp: this.identity.authClaimIncProofSiblings, - - authClaimNonRevMtp: prepareSiblingsStr( - this.identity.authClaimNonRevProof, - defaultMTLevels, - ), - authClaimNonRevMtpAuxHi: this.nodeAuxAuth?.key.string(), - authClaimNonRevMtpAuxHv: this.nodeAuxAuth?.value.string(), - authClaimNonRevMtpNoAux: this.nodeAuxAuth?.noAux, - - challenge: this.challenge?.toString(), - challengeSignatureR8x: this.signatureChallenge?.R8[0].toString(), - challengeSignatureR8y: this.signatureChallenge?.R8[1].toString(), - challengeSignatureS: this.signatureChallenge?.S.toString(), - - gistRoot: this.gistProof?.root.string(), - gistMtp: prepareSiblingsStr( - this.gistProof!.proof, - defaultMTLevelsOnChain, - ), - gistMtpAuxHi: this.globalNodeAux?.key.string(), - gistMtpAuxHv: this.globalNodeAux?.value.string(), - gistMtpNoAux: this.globalNodeAux?.noAux, - - claimSubjectProfileNonce: '0', - - issuerID: this.circuitClaimData.issuerId.bigInt().toString(), - - issuerClaim: this.circuitClaimData.claim.marshalJson(), - isRevocationChecked: '1', - issuerClaimNonRevMtp: prepareSiblingsStr( - this.nonRevProof.proof, - defaultMTLevels, - ), - issuerClaimNonRevMtpNoAux: this.nodeAuxNonRev.noAux, - issuerClaimNonRevMtpAuxHi: this.nodeAuxNonRev.key.string(), - issuerClaimNonRevMtpAuxHv: this.nodeAuxNonRev.value.string(), - issuerClaimNonRevClaimsTreeRoot: - this.nonRevProof.treeState.claimsRoot.string(), - issuerClaimNonRevRevTreeRoot: - this.nonRevProof.treeState.revocationRoot.string(), - issuerClaimNonRevRootsTreeRoot: - this.nonRevProof.treeState.rootOfRoots.string(), - issuerClaimNonRevState: this.nonRevProof.treeState.state.string(), - - issuerClaimMtp: prepareSiblingsStr( - this.circuitClaimData.incProof.proof, - defaultMTLevels, - ), - issuerClaimClaimsTreeRoot: - this.circuitClaimData.incProof.treeState?.claimsRoot.string(), - issuerClaimRevTreeRoot: - this.circuitClaimData.incProof.treeState?.revocationRoot.string(), - issuerClaimRootsTreeRoot: - this.circuitClaimData.incProof.treeState?.rootOfRoots.string(), - issuerClaimIdenState: - this.circuitClaimData.incProof.treeState?.state.string(), - - timestamp: this.timestamp, - - claimSchema: this.circuitClaimData.claim - .getSchemaHash() - .bigInt() - .toString(), - claimPathNotExists: this.query.valueProof?.mtp.existence ? 0 : 1, - claimPathMtp: prepareSiblingsStr( - this.query.valueProof!.mtp, - defaultMTLevelsClaimsMerklization, - ), - claimPathMtpNoAux: this.nodAuxJSONLD.noAux, - claimPathMtpAuxHi: this.nodAuxJSONLD.key.string(), - claimPathMtpAuxHv: this.nodAuxJSONLD.value.string(), - claimPathKey: this.query.valueProof?.path.toString(), - claimPathValue: this.query.valueProof?.value?.toString(), - - slotIndex: this.query.slotIndex, - operator: this.query.operator, - value: this.value, - }); - } -} diff --git a/packages/snap/src/zkp/handlers/CheckCredentialExistence.ts b/packages/snap/src/zkp/handlers/CheckCredentialExistence.ts new file mode 100644 index 00000000..f75db327 --- /dev/null +++ b/packages/snap/src/zkp/handlers/CheckCredentialExistence.ts @@ -0,0 +1,62 @@ +import type { JsonRpcRequest } from '@metamask/utils'; +import type { + RPCMethods, + SaveCredentialsResponse, + SnapRequestParams, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; + +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { VCManager } from '@/zkp/helpers'; + +export const CheckCredentialExistence = async ({ + request, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage) { + throw new Error('Identity not created'); + } + + const { claimOffer, proofRequest } = + request.params as SnapRequestParams[RPCMethods.CheckCredentialExistence]; + + const vcManager = await VCManager.create(); + + let result: SaveCredentialsResponse[] = []; + + if (claimOffer && proofRequest) { + const vcs = await vcManager.getDecryptedVCsByOfferAndQuery( + claimOffer, + proofRequest, + ); + + result = vcs?.map((vc) => ({ + type: vc.type, + issuer: vc.issuer, + })); + } else if (claimOffer) { + const vcs = await vcManager.getDecryptedVCsByOffer(claimOffer); + + result = vcs?.map((vc) => ({ + type: vc.type, + issuer: vc.issuer, + })); + } else if (proofRequest) { + const vcs = await vcManager.getDecryptedVCsByQuery( + proofRequest.query, + proofRequest.issuerDid, + ); + + result = vcs?.map((vc) => ({ + type: vc.type, + issuer: vc.issuer, + })); + } + + return result; +}; diff --git a/packages/snap/src/zkp/handlers/CheckStateContractSync.ts b/packages/snap/src/zkp/handlers/CheckStateContractSync.ts new file mode 100644 index 00000000..8297b830 --- /dev/null +++ b/packages/snap/src/zkp/handlers/CheckStateContractSync.ts @@ -0,0 +1,15 @@ +import type { + RPCMethods, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; +import { checkIfStateSynced } from '@rarimo/rarime-connector'; + +import { getProviderChainInfo } from '@/zkp/helpers'; + +export const checkStateContractSync = async (): Promise< + SnapRequestsResponses[RPCMethods.CheckStateContractSync] +> => { + const chainInfo = await getProviderChainInfo(); + + return checkIfStateSynced(chainInfo); +}; diff --git a/packages/snap/src/zkp/handlers/CreateIdentity.ts b/packages/snap/src/zkp/handlers/CreateIdentity.ts new file mode 100644 index 00000000..666102b0 --- /dev/null +++ b/packages/snap/src/zkp/handlers/CreateIdentity.ts @@ -0,0 +1,94 @@ +import { copyable, divider, heading, panel, text } from '@metamask/snaps-sdk'; +import type { JsonRpcRequest } from '@metamask/utils'; +import type { + RPCMethods, + SnapRequestParams, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; +import { Identity, isDidSupported } from '@rarimo/zkp-iden3'; +import { utils } from 'ethers'; + +import { config } from '@/config'; +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { genPkHexFromEntropy } from '@/zkp/helpers'; + +export const createIdentity = async ({ + request, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + const params = request.params as SnapRequestParams[RPCMethods.CreateIdentity]; + + if ( + params?.privateKeyHex && + !utils.isHexString(`0x${params?.privateKeyHex}`) + ) { + throw new Error('Invalid private key'); + } + + if ( + identityStorage?.did && + identityStorage?.didBigInt && + isDidSupported(identityStorage.did) + ) { + return { + identityIdString: identityStorage.did, + identityIdBigIntString: identityStorage.didBigInt, + }; + } + + const res = + Boolean(identityStorage?.did && identityStorage?.didBigInt) || + (await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: panel([ + heading('Identity creation'), + divider(), + text(`You don't have an identity yet`), + text('Would you like to create one?'), + ]), + }, + })); + + if (!res) { + throw new Error('User rejected request'); + } + + const identity = await Identity.create( + { + schemaHashHex: config.AUTH_BJJ_CREDENTIAL_HASH, + idType: config.ID_TYPE, + }, + params?.privateKeyHex || (await genPkHexFromEntropy()), + ); + + await snapStorage.setItem(StorageKeys.identity, { + privateKeyHex: identity.privateKeyHex, + did: identity.didString, + didBigInt: identity.identityIdBigIntString, + }); + + await snap.request({ + method: 'snap_dialog', + params: { + type: 'alert', + content: panel([ + heading('Your RariMe is ready for use!'), + divider(), + text('Your unique identifier(DID):'), + copyable(identity.didString), + ]), + }, + }); + + return { + identityIdString: identity.didString, + identityIdBigIntString: identity.identityIdBigIntString, + }; +}; diff --git a/packages/snap/src/zkp/handlers/CreateProof.ts b/packages/snap/src/zkp/handlers/CreateProof.ts new file mode 100644 index 00000000..8de77fd3 --- /dev/null +++ b/packages/snap/src/zkp/handlers/CreateProof.ts @@ -0,0 +1,210 @@ +import { DID } from '@iden3/js-iden3-core'; +import { divider, heading, panel, text } from '@metamask/snaps-sdk'; +import type { JsonRpcRequest } from '@metamask/utils'; +import { + checkIfStateSynced, + getCoreOperationByIndex, + CircuitId, + loadDataFromRarimoCore, +} from '@rarimo/rarime-connector'; +import type { + RPCMethods, + SnapRequestParams, + SnapRequestsResponses, + GetStateInfoResponse, + MerkleProof, +} from '@rarimo/rarime-connector'; +import { ZkpGen, Identity, parseDidV2 } from '@rarimo/zkp-iden3'; + +import { config } from '@/config'; +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import type { TextField } from '@/types'; +import { isValidCreateProofRequest } from '@/typia-generated'; +import { + getSnapFileBytes, + VCManager, + getProviderChainInfo, +} from '@/zkp/helpers'; + +export const createProof = async ({ + request, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage) { + throw new Error('Identity not created'); + } + + const { issuerDid, ...createProofRequest } = + request.params as SnapRequestParams[RPCMethods.CreateProof]; + + isValidCreateProofRequest(createProofRequest); + + const { query } = createProofRequest; + const { circuitId, accountAddress } = createProofRequest; + + const isOnChainProof = + circuitId === CircuitId.AtomicQuerySigV2OnChain || + circuitId === CircuitId.AtomicQueryMTPV2OnChain; + + if (isOnChainProof && !accountAddress) { + throw new Error('Account address is required'); + } + + const vcManager = await VCManager.create(); + + const credentials = ( + await vcManager.getDecryptedVCsByQuery(query, issuerDid) + ).filter((cred) => { + const CredSubjId = parseDidV2(cred.credentialSubject.id as string); + + const IdentityStorageDid = parseDidV2(identityStorage.did); + + return CredSubjId.string() === IdentityStorageDid.string(); + }); + + if (!credentials.length) { + throw new Error( + `no credential were issued on the given id ${identityStorage.did}`, + ); + } + + const vc = credentials[0]; + + const res = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: panel([ + heading('Generate a zero-knowledge proof?'), + + divider(), + + text('**Credential**'), + text(`${vc.type?.[1]}\n`), + + divider(), + text('**Query**'), + + ...(query.credentialSubject + ? Object.keys(query.credentialSubject).reduce( + (accSubj: TextField[], fieldName) => { + const fieldOperators = query.credentialSubject?.[fieldName]; + + const isString = typeof fieldOperators === 'string'; + const isNumber = typeof fieldOperators === 'number'; + + if (isString || isNumber) { + return accSubj.concat( + text(`${fieldName} - ${fieldOperators}\n`), + ); + } + + const textField = Object.keys(fieldOperators).map( + (operator) => { + return text( + `${fieldName} - ${operator} ${fieldOperators?.[operator]}\n`, + ); + }, + ); + + return accSubj.concat(textField); + }, + [], + ) + : []), + + divider(), + + ...(circuitId ? [text('**ZK Circuit**'), text(circuitId)] : []), + ]), + }, + }); + + if (!res) { + throw new Error('User rejected request'); + } + + const identity = await Identity.create( + { + schemaHashHex: config.AUTH_BJJ_CREDENTIAL_HASH, + idType: config.ID_TYPE, + }, + identityStorage.privateKeyHex, + ); + + const chainInfo = await getProviderChainInfo(); + + const zkpGen = new ZkpGen(identity, createProofRequest, vc, { + chainInfo, + loadingCircuitCb: getSnapFileBytes, + circuitsUrls: { + [CircuitId.AtomicQuerySigV2]: { + wasmUrl: config.CIRCUIT_SIG_V2_WASM_URL, + keyUrl: config.CIRCUIT_SIG_V2_FINAL_KEY_URL, + }, + [CircuitId.AtomicQueryMTPV2]: { + wasmUrl: config.CIRCUIT_MTP_V2_WASM_URL, + keyUrl: config.CIRCUIT_MTP_V2_FINAL_KEY_URL, + }, + [CircuitId.AtomicQuerySigV2OnChain]: { + wasmUrl: config.CIRCUIT_SIG_V2_ON_CHAIN_WASM_URL, + keyUrl: config.CIRCUIT_SIG_V2_ON_CHAIN_FINAL_KEY_URL, + }, + [CircuitId.AtomicQueryMTPV2OnChain]: { + wasmUrl: config.CIRCUIT_MTP_V2_ON_CHAIN_WASM_URL, + keyUrl: config.CIRCUIT_MTP_V2_ON_CHAIN_FINAL_KEY_URL, + }, + }, + }); + + // ================ LOAD STATE DETAILS ===================== + + const isSynced = await checkIfStateSynced(chainInfo); + + const did = parseDidV2(issuerDid); + + const issuerId = DID.idFromDID(did); + + const issuerHexId = `0x0${issuerId.bigInt().toString(16)}`; + + const stateData = await loadDataFromRarimoCore( + `/rarimo/rarimo-core/identity/state/${issuerHexId}`, + chainInfo.rarimoApiUrl, + ); + const merkleProof = await loadDataFromRarimoCore( + `/rarimo/rarimo-core/identity/state/${issuerHexId}/proof`, + chainInfo.rarimoApiUrl, + stateData.state.createdAtBlock, + ); + + const operation = await getCoreOperationByIndex( + chainInfo, + stateData.state.lastUpdateOperationIndex, + ); + + // ================== USE STATE DETAILS TO GEN PROOF ===================== + + const zkpProof = await zkpGen.generateProof( + stateData.state.hash, + operation.operation.details.GISTHash, + ); + + return { + chainInfo, + rarimoCoreUrl: chainInfo.rarimoApiUrl, + isSynced, + + issuerHexId, + + stateData: stateData.state, + merkleProof, + operation: operation.operation, + + zkpProof, + }; +}; diff --git a/packages/snap/src/zkp/handlers/ExportIdentity.ts b/packages/snap/src/zkp/handlers/ExportIdentity.ts new file mode 100644 index 00000000..b766b337 --- /dev/null +++ b/packages/snap/src/zkp/handlers/ExportIdentity.ts @@ -0,0 +1,36 @@ +import { copyable, divider, heading, panel, text } from '@metamask/snaps-sdk'; +import type { JsonRpcRequest } from '@metamask/utils'; + +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { isOriginInWhitelist } from '@/zkp/helpers'; + +export const exportIdentity = async ({ + origin, +}: { + request: JsonRpcRequest; + origin: string; +}) => { + if (!isOriginInWhitelist(origin)) { + throw new Error('This origin does not have access to export identity'); + } + + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage.privateKeyHex) { + throw new Error('Identity not created'); + } + + return snap.request({ + method: 'snap_dialog', + params: { + type: 'alert', + content: panel([ + heading('Your RariMe private key'), + divider(), + text('Сopy:'), + copyable(identityStorage.privateKeyHex), + ]), + }, + }); +}; diff --git a/packages/snap/src/zkp/handlers/GetCredentials.ts b/packages/snap/src/zkp/handlers/GetCredentials.ts new file mode 100644 index 00000000..7495dedf --- /dev/null +++ b/packages/snap/src/zkp/handlers/GetCredentials.ts @@ -0,0 +1,22 @@ +import type { JsonRpcRequest } from '@metamask/utils'; +import type { + RPCMethods, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; + +import { isOriginInWhitelist, VCManager } from '@/zkp/helpers'; + +export const getCredentials = async ({ + origin, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + if (!isOriginInWhitelist(origin)) { + throw new Error('This origin does not have access to credentials'); + } + + const vcManager = await VCManager.create(); + + return await vcManager.getAllDecryptedVCs(); +}; diff --git a/packages/snap/src/zkp/handlers/GetIdentity.ts b/packages/snap/src/zkp/handlers/GetIdentity.ts new file mode 100644 index 00000000..b45cf3b1 --- /dev/null +++ b/packages/snap/src/zkp/handlers/GetIdentity.ts @@ -0,0 +1,22 @@ +import type { + RPCMethods, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; + +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; + +export const getIdentity = async (): Promise< + SnapRequestsResponses[RPCMethods.GetIdentity] +> => { + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage) { + throw new Error('Identity not created'); + } + + return { + identityIdString: identityStorage.did, + identityIdBigIntString: identityStorage.didBigInt, + }; +}; diff --git a/packages/snap/src/zkp/handlers/RemoveCredentials.ts b/packages/snap/src/zkp/handlers/RemoveCredentials.ts new file mode 100644 index 00000000..101ad89c --- /dev/null +++ b/packages/snap/src/zkp/handlers/RemoveCredentials.ts @@ -0,0 +1,76 @@ +import type { Component } from '@metamask/snaps-sdk'; +import { divider, heading, panel, text } from '@metamask/snaps-sdk'; +import type { JsonRpcRequest } from '@metamask/utils'; +import type { + RPCMethods, + SnapRequestParams, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; + +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { + getClaimIdFromVCId, + isOriginInWhitelist, + VCManager, +} from '@/zkp/helpers'; + +export const removeCredentials = async ({ + request, + origin, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + if (!isOriginInWhitelist(origin)) { + throw new Error( + 'This origin does not have access to the RemoveCredentials method', + ); + } + + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage) { + throw new Error('Identity not created'); + } + + const params = + request.params as SnapRequestParams[RPCMethods.RemoveCredentials]; + + const claimIds = params.ids.map((id) => getClaimIdFromVCId(id)); + + const vcManager = await VCManager.create(); + + const vcs = await vcManager.getDecryptedVCsByClaimIds(claimIds); + + const res = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: panel([ + heading('Remove Credentials'), + divider(), + + ...vcs.reduce((acc, el, idx) => { + const vcTargetType = el.type[1]; + const vcID = el.id; + + return acc.concat([ + text(`**Credential #${idx + 1}**`), + text(`Type: ${vcTargetType}`), + text(`ID: ${vcID}`), + divider(), + ]); + }, []), + ]), + }, + }); + + if (!res) { + throw new Error('User rejected request'); + } + + await Promise.all(vcs.map(async (vc) => vcManager.clearMatchedVcs(vc))); + + return undefined; +}; diff --git a/packages/snap/src/zkp/handlers/SaveCredentials.ts b/packages/snap/src/zkp/handlers/SaveCredentials.ts new file mode 100644 index 00000000..30273599 --- /dev/null +++ b/packages/snap/src/zkp/handlers/SaveCredentials.ts @@ -0,0 +1,97 @@ +import { divider, heading, panel, text } from '@metamask/snaps-sdk'; +import type { JsonRpcRequest } from '@metamask/utils'; +import type { + RPCMethods, + SnapRequestParams, + SnapRequestsResponses, +} from '@rarimo/rarime-connector'; +import { AuthZkp, Identity } from '@rarimo/zkp-iden3'; + +import { config } from '@/config'; +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { isValidSaveCredentialsOfferRequest } from '@/typia-generated'; +import { + getProviderChainInfo, + getSnapFileBytes, + VCManager, +} from '@/zkp/helpers'; + +export const saveCredentials = async ({ + request, +}: { + request: JsonRpcRequest; + origin: string; +}): Promise => { + const identityStorage = await snapStorage.getItem(StorageKeys.identity); + + if (!identityStorage) { + throw new Error('Identity not created'); + } + + // FIXME: mb multiple offers? + const offer = request.params as SnapRequestParams[RPCMethods.SaveCredentials]; + + isValidSaveCredentialsOfferRequest(offer); + + const dialogContent = [ + heading('Credentials'), + divider(), + text(`From: ${offer.from}`), + text(`Url: ${offer.body.url}`), + ]; + + const dialogCredentials = offer.body.Credentials.reduce( + (acc: any, cred: any) => { + return acc.concat([divider(), text(cred.description), text(cred.id)]); + }, + [], + ); + + const res = await snap.request({ + method: 'snap_dialog', + params: { + type: 'confirmation', + content: panel([...dialogContent, ...dialogCredentials]), + }, + }); + + if (!res) { + throw new Error('User rejected request'); + } + + const vcManager = await VCManager.create(); + + const identity = await Identity.create( + { + schemaHashHex: config.AUTH_BJJ_CREDENTIAL_HASH, + idType: config.ID_TYPE, + }, + identityStorage.privateKeyHex, + ); + + const chainInfo = await getProviderChainInfo(); + + const authProof = new AuthZkp(identity, offer, { + chainInfo, + loadingCircuitCb: getSnapFileBytes, + circuitsUrls: { + wasmUrl: config.CIRCUIT_AUTH_WASM_URL, + keyUrl: config.CIRCUIT_AUTH_FINAL_KEY_URL, + }, + }); + + const credentials = await authProof.getVerifiableCredentials(); + + await Promise.all( + credentials.map(async (credential) => { + await vcManager.clearMatchedVcs(credential); + await vcManager.encryptAndSaveVC(credential); + }), + ); + + return credentials.map((cred) => ({ + type: cred.type, + issuer: cred.issuer, + })); +}; diff --git a/packages/snap/src/zkp/handlers/index.ts b/packages/snap/src/zkp/handlers/index.ts new file mode 100644 index 00000000..ecdafcad --- /dev/null +++ b/packages/snap/src/zkp/handlers/index.ts @@ -0,0 +1,9 @@ +export * from './CreateIdentity'; +export * from './SaveCredentials'; +export * from './RemoveCredentials'; +export * from './CheckCredentialExistence'; +export * from './CreateProof'; +export * from './CheckStateContractSync'; +export * from './GetCredentials'; +export * from './ExportIdentity'; +export * from './GetIdentity'; diff --git a/packages/snap/src/helpers/ceramic-helpers.ts b/packages/snap/src/zkp/helpers/ceramic-helpers.ts similarity index 93% rename from packages/snap/src/helpers/ceramic-helpers.ts rename to packages/snap/src/zkp/helpers/ceramic-helpers.ts index 923ae865..65c440b5 100644 --- a/packages/snap/src/helpers/ceramic-helpers.ts +++ b/packages/snap/src/zkp/helpers/ceramic-helpers.ts @@ -1,11 +1,11 @@ import { ComposeClient } from '@composedb/client'; import type { RuntimeCompositeDefinition } from '@composedb/types'; import { Hex } from '@iden3/js-crypto'; -import { DID as CeramicDID } from 'dids'; +import { DID } from 'dids'; import { Ed25519Provider } from 'key-did-provider-ed25519'; import { getResolver } from 'key-did-resolver'; -import { CERAMIC_URL } from '../config'; +import { CERAMIC_URL } from '@/config'; export class CeramicProvider { readonly #pkHex: string; @@ -31,7 +31,7 @@ export class CeramicProvider { } async auth() { - const did = new CeramicDID({ + const did = new DID({ provider: new Ed25519Provider(Hex.decodeString(this.#pkHex)), resolver: getResolver(), }); diff --git a/packages/snap/src/zkp/helpers/common-helpers.ts b/packages/snap/src/zkp/helpers/common-helpers.ts new file mode 100644 index 00000000..a51145ab --- /dev/null +++ b/packages/snap/src/zkp/helpers/common-helpers.ts @@ -0,0 +1,30 @@ +import type { ChainZkpInfo } from '@rarimo/rarime-connector'; +import { providers } from 'ethers'; + +import { HOSTNAMES_WHITELIST, SUPPORTED_CHAINS } from '@/config'; + +export const getChainInfo = (chainId: number): ChainZkpInfo => { + const chainInfo = SUPPORTED_CHAINS[chainId]; + if (!chainInfo) { + throw new Error(`ChainId ${chainId} not supported`); + } + + return chainInfo; +}; + +export const getProviderChainInfo = async (): Promise => { + const provider = new providers.Web3Provider( + ethereum as any as providers.ExternalProvider, + ); + const network = await provider.getNetwork(); + + return getChainInfo(network.chainId); +}; + +export const getHostname = (origin: string): string => { + return new URL(origin).hostname; +}; + +export const isOriginInWhitelist = (origin: string) => { + return HOSTNAMES_WHITELIST.includes(getHostname(origin)); +}; diff --git a/packages/snap/src/helpers/credential-helpers.ts b/packages/snap/src/zkp/helpers/credential-helpers.ts similarity index 81% rename from packages/snap/src/helpers/credential-helpers.ts rename to packages/snap/src/zkp/helpers/credential-helpers.ts index 6bcd69e4..21f0942a 100644 --- a/packages/snap/src/helpers/credential-helpers.ts +++ b/packages/snap/src/zkp/helpers/credential-helpers.ts @@ -1,36 +1,34 @@ -import type { Claim } from '@iden3/js-iden3-core'; import type { CreateProofRequestParams, ProofQuery, + SaveCredentialsRequestParams, } from '@rarimo/rarime-connector'; +import type { W3CCredential } from '@rarimo/zkp-iden3'; +import { Identity } from '@rarimo/zkp-iden3'; import { sha256 } from 'ethers/lib/utils'; import type { DocumentNode } from 'graphql/language'; -import { CeramicProvider } from './ceramic-helpers'; -import { genPkHexFromEntropy } from './identity-helpers'; -import { getCoreClaimFromProof } from './proof-helpers'; -import VerifiableRuntimeComposite from '../../ceramic/composites/VerifiableCredentials-runtime.json'; -import VerifiableRuntimeCompositeV2 from '../../ceramic/composites/VerifiableCredentialsV2-runtime.json'; -import { ProofType, StorageKeys } from '../enums'; -import { Identity } from '../identity'; -import { getItemFromStore, setItemInStore } from '../rpc'; +import VerifiableRuntimeComposite from '../../../ceramic/composites/VerifiableCredentials-runtime.json'; +import VerifiableRuntimeCompositeV2 from '../../../ceramic/composites/VerifiableCredentialsV2-runtime.json'; + +import { config } from '@/config'; +import { StorageKeys } from '@/enums'; +import { snapStorage } from '@/helpers'; +import { CeramicProvider } from '@/zkp/helpers/ceramic-helpers'; +import { genPkHexFromEntropy } from '@/zkp/helpers/identity-helpers'; import type { - SaveCredentialsRequestParams, ClearVcMutation, ClearVcMutationVariables, CreateVcMutationVariables, - CredentialStatus, GetAllVerifiableCredentialsQuery, GetAllVerifiableCredentialsQueryVariables, GetVerifiableCredentialsByClaimIdQuery, GetVerifiableCredentialsByClaimIdQueryVariables, GetVerifiableCredentialsByQueryHashQuery, GetVerifiableCredentialsByQueryHashQueryVariables, - RevocationStatus, - W3CCredential, GetVerifiableCredentialsByClaimIdAndQueryHashQueryVariables, GetVerifiableCredentialsByClaimIdAndQueryHashQuery, -} from '../types'; +} from '@/zkp/types'; import { ClearVc, CreateVc, @@ -38,7 +36,7 @@ import { GetVerifiableCredentialsByClaimId, GetVerifiableCredentialsByQueryHash, GetVerifiableCredentialsByClaimIdAndQueryHash, -} from '../types'; +} from '@/zkp/types'; const _SALT = 'pu?)Rx829U3ot.iB)D+z9Iyh'; @@ -144,7 +142,7 @@ export class VCManager { let privateKeyHex = opts?.pkHex; if (!privateKeyHex) { - const identityStorage = await getItemFromStore(StorageKeys.identity); + const identityStorage = await snapStorage.getItem(StorageKeys.identity); if (!identityStorage) { throw new Error('Identity was not created yet'); @@ -504,9 +502,15 @@ export const migrateVCsToLastCeramicModel = async () => { const entropyKeyHex = await genPkHexFromEntropy(); - const entropyIdentity = await Identity.create(entropyKeyHex); + const entropyIdentity = await Identity.create( + { + idType: config.ID_TYPE, + schemaHashHex: config.AUTH_BJJ_CREDENTIAL_HASH, + }, + entropyKeyHex, + ); - const identityStorage = await getItemFromStore(StorageKeys.identity); + const identityStorage = await snapStorage.getItem(StorageKeys.identity); const isPKImported = identityStorage.privateKeyHex !== entropyIdentity.privateKeyHex; @@ -525,7 +529,7 @@ export const migrateVCsToLastCeramicModel = async () => { const oldKeyHexVCs = await oldKeyHexManager.getAllDecryptedVCs(); const storeCredentials: W3CCredential[] = - (await getItemFromStore(StorageKeys.credentials)) || []; + (await snapStorage.getItem(StorageKeys.credentials)) || []; await Promise.all( [VerifiableRuntimeComposite].map(async (definition) => { @@ -556,101 +560,7 @@ export const migrateVCsToLastCeramicModel = async () => { }), ); - await setItemInStore(StorageKeys.credentials, []); + await snapStorage.setItem(StorageKeys.credentials, []); }), ); }; - -export const getRevocationStatus = async ( - credStatus: CredentialStatus, -): Promise => { - const data = await fetch(credStatus.id); - - return await data.json(); -}; - -export const findNonRevokedCredential = async ( - creds: W3CCredential[], -): Promise<{ - cred: W3CCredential; - revStatus: RevocationStatus; -}> => { - for (const cred of creds) { - const revStatus = await getRevocationStatus(cred.credentialStatus); - if (revStatus.mtp.existence) { - continue; - } - return { cred, revStatus }; - } - throw new Error('all claims are revoked'); -}; - -const getCoreClaimFromCredential = async ( - credential: W3CCredential, -): Promise => { - const coreClaimFromSigProof = getCoreClaimFromProof( - credential.proof!, - ProofType.BJJSignature, - ); - - const coreClaimFromMtpProof = getCoreClaimFromProof( - credential.proof!, - ProofType.Iden3SparseMerkleTreeProof, - ); - - if ( - coreClaimFromMtpProof && - coreClaimFromSigProof && - coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex() - ) { - throw new Error( - 'core claim representations is set in both proofs but they are not equal', - ); - } - - if (!coreClaimFromMtpProof && !coreClaimFromSigProof) { - throw new Error('core claim is not set in credential proofs'); - } - - const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof!; - - return coreClaim; -}; - -export const getPreparedCredential = async (credential: W3CCredential) => { - const { cred: nonRevokedCred, revStatus } = await findNonRevokedCredential([ - credential, - ]); - - const credCoreClaim = await getCoreClaimFromCredential(nonRevokedCred); - - return { - credential: nonRevokedCred, - revStatus, - credentialCoreClaim: credCoreClaim, - }; -}; - -export const loadDataByUrl = async ( - url: string, - endianSwappedCoreStateHash?: string, -) => { - const response = await fetch( - endianSwappedCoreStateHash - ? `${url}?state=${endianSwappedCoreStateHash}` - : url, - ); - - if (!response.ok) { - const message = `An error has occured: ${response.status}`; - throw new Error(message); - } - - return await response.json(); -}; - -export const isVCsV2 = (vcs: W3CCredential[]) => { - return vcs.every((vc) => { - return vc.issuer.includes('readonly'); - }); -}; diff --git a/packages/snap/src/helpers/file-helpers.ts b/packages/snap/src/zkp/helpers/file-helpers.ts similarity index 52% rename from packages/snap/src/helpers/file-helpers.ts rename to packages/snap/src/zkp/helpers/file-helpers.ts index 46189f2d..6ac8761e 100644 --- a/packages/snap/src/helpers/file-helpers.ts +++ b/packages/snap/src/zkp/helpers/file-helpers.ts @@ -1,8 +1,3 @@ -export const readBytesFile = async (path: string) => { - const response = await fetch(path); - return new Uint8Array(await response?.arrayBuffer?.()); -}; - export const getSnapFileBytes = async (path: string) => { const response = await snap.request({ method: 'snap_getFile', @@ -20,11 +15,3 @@ export const getSnapFileBytes = async (path: string) => { return bytes; }; - -export const getFileBytes = async (path: string) => { - try { - return await readBytesFile(new URL(path).href); - } catch (error) { - return await getSnapFileBytes(path); - } -}; diff --git a/packages/snap/src/zkp/helpers/identity-helpers.ts b/packages/snap/src/zkp/helpers/identity-helpers.ts new file mode 100644 index 00000000..e3c986d1 --- /dev/null +++ b/packages/snap/src/zkp/helpers/identity-helpers.ts @@ -0,0 +1,10 @@ +export const genPkHexFromEntropy = async (salt?: string) => { + const entropy = await snap.request({ + method: 'snap_getEntropy', + params: { + version: 1, + ...(salt ? { salt } : {}), + }, + }); + return entropy.startsWith('0x') ? entropy.substring(2) : entropy; +}; diff --git a/packages/snap/src/zkp/helpers/index.ts b/packages/snap/src/zkp/helpers/index.ts new file mode 100644 index 00000000..a3000ec4 --- /dev/null +++ b/packages/snap/src/zkp/helpers/index.ts @@ -0,0 +1,5 @@ +export * from './identity-helpers'; +export * from './file-helpers'; +export * from './credential-helpers'; +export * from './common-helpers'; +export * from './ceramic-helpers'; diff --git a/packages/snap/src/zkp/index.ts b/packages/snap/src/zkp/index.ts new file mode 100644 index 00000000..6c6f862d --- /dev/null +++ b/packages/snap/src/zkp/index.ts @@ -0,0 +1 @@ +export * from './handlers'; diff --git a/packages/snap/src/types/graphql/index.ts b/packages/snap/src/zkp/types/graphql/index.ts similarity index 100% rename from packages/snap/src/types/graphql/index.ts rename to packages/snap/src/zkp/types/graphql/index.ts diff --git a/packages/snap/src/zkp/types/index.ts b/packages/snap/src/zkp/types/index.ts new file mode 100644 index 00000000..acae838c --- /dev/null +++ b/packages/snap/src/zkp/types/index.ts @@ -0,0 +1 @@ +export * from './graphql'; diff --git a/yarn.lock b/yarn.lock index 6204fd93..d3a22e08 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5779,7 +5779,7 @@ __metadata: "@metamask/snaps-sdk": "npm:^2.0.0" "@metamask/snaps-utils": "npm:^6.0.0" "@rarimo/rarime-connector": "workspace:^" - "@typechain/ethers-v5": "npm:11.1.1" + "@rarimo/zkp-iden3": "workspace:^" "@types/intl": "npm:1.2.0" "@types/lodash": "npm:^4.14.202" "@types/uuid": "npm:9.0.2" @@ -5798,7 +5798,6 @@ __metadata: npm-commands: "npm:^1.2.1" rimraf: "npm:3.0.2" snarkjs: "npm:^0.7.2" - typechain: "npm:8.3.1" typescript: "npm:4.7.4" typia: "npm:4.1.3" uuid: "npm:9.0.0" @@ -5815,7 +5814,7 @@ __metadata: languageName: node linkType: hard -"@rarimo/zkp-iden3@workspace:packages/zkp-iden3": +"@rarimo/zkp-iden3@workspace:^, @rarimo/zkp-iden3@workspace:packages/zkp-iden3": version: 0.0.0-use.local resolution: "@rarimo/zkp-iden3@workspace:packages/zkp-iden3" dependencies: @@ -5959,9 +5958,9 @@ __metadata: linkType: hard "@scure/base@npm:^1.0.0, @scure/base@npm:^1.1.1, @scure/base@npm:^1.1.3, @scure/base@npm:~1.1.0, @scure/base@npm:~1.1.2, @scure/base@npm:~1.1.3, @scure/base@npm:~1.1.4": - version: 1.1.5 - resolution: "@scure/base@npm:1.1.5" - checksum: 10/543fa9991c6378b6a0d5ab7f1e27b30bb9c1e860d3ac81119b4213cfdf0ad7b61be004e06506e89de7ce0cec9391c17f5c082bb34c3b617a2ee6a04129f52481 + version: 1.1.6 + resolution: "@scure/base@npm:1.1.6" + checksum: 10/814fd1cce24f1e152751fabca2853d26aaa96ff8a9349c43d9aebc3b3d8ca88dd902966e1c289590a37f35d4c4436c6aedb1b386924b2909072045af4c3e9fe4 languageName: node linkType: hard