Skip to content

Commit

Permalink
fix: fixes provider bug (#100)
Browse files Browse the repository at this point in the history
* fix: provider bug

* fix: add ethereum param

* fix: some fixes and remove comments

* fix: fix tests

* fix: tests

Co-authored-by: martines3000 <domajnko.martin@gmail.com>
  • Loading branch information
andyv09 and martines3000 committed Feb 27, 2023
1 parent c6472b2 commit d89194d
Show file tree
Hide file tree
Showing 31 changed files with 549 additions and 182 deletions.
130 changes: 98 additions & 32 deletions packages/snap/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ <h1>Hello, Snaps!</h1>
<hr />
<input type="text" id="infura_token" placeholder="Infura token" />
<button class="changeInfuraToken">ChangeInfuraToken</button>
<button class="resolveDID">resolveDID</button>
<br />
<hr />
<button class="getVCStore">Get current VCStore</button>
Expand All @@ -77,38 +78,105 @@ <h1>Hello, Snaps!</h1>
type="text/javascript"
></script>
<script>
const snapId = `local:${window.location.href.substring(
0,
window.location.href.lastIndexOf('/')
)}`;
const snapId = `local:${window.location.href.substring(
0,
window.location.href.lastIndexOf('/')
)}`;

console.log(snapId);
console.log(snapId);

const placeholderVC = {
credentialSchema: {
id: 'https://beta.api.schemas.serto.id/v1/public/program-completion-certificate/1.0/json-schema.json',
type: 'JsonSchemaValidator2018',
},
credentialSubject: {
accomplishmentType: 'Developer Certificate',
learnerName: 'a',
achievement: 'Certified Solidity Developer 2',
courseProvider: 'UM FERI',
id: 'did:ethr:goerli:0x6A24687621cDD1C77Bb6aCbBEE910d0C517eB443',
},
issuer: {
id: 'did:ethr:goerli:0x0241abd662da06d0af2f0152a80bc037f65a7f901160cfe1eb35ef3f0c532a2a4d',
},
type: ['VerifiableCredential', 'ProgramCompletionCertificate'],
'@context': [
'https://www.w3.org/2018/credentials/v1',
'https://beta.api.schemas.serto.id/v1/public/program-completion-certificate/1.0/ld-context.json',
],
issuanceDate: '2022-06-13T12:08:10.000Z',
proof: {
type: 'JwtProof2020',
jwt: 'eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJKV1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chema: {
id: 'https://beta.api.schemas.serto.id/v1/public/program-completion-certificate/1.0/json-schema.json',
type: 'JsonSchemaValidator2018',
},
credentialSubject: {
accomplishmentType: 'Developer Certificate',
learnerName: 'a',
achievement: 'Certified Solidity Developer 2',
courseProvider: 'UM FERI',
id: 'did:ethr:goerli:0x6A24687621cDD1C77Bb6aCbBEE910d0C517eB443',
},
issuer: {
id: 'did:ethr:goerli:0x0241abd662da06d0af2f0152a80bc037f65a7f901160cfe1eb35ef3f0c532a2a4d',
},
type: ['VerifiableCredential', 'ProgramCompletionCertificate'],
'@context': [
'https://www.w3.org/2018/credentials/v1',
'https://beta.api.schemas.serto.id/v1/public/program-completion-certificate/1.0/ld-context.json',
],
issuanceDate: '2022-06-13T12:08:10.000Z',
proof: {
type: 'JwtProof2020',
jwt: 'eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJKV1QifQ.eyJ2YyI6eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImh0dHBzOi8vYmV0YS5hcGkuc2NoZW1hcy5zZXJ0by5pZC92MS9wdWJsaWMvcHJvZ3JhbS1jb21wbGV0aW9uLWNlcnRpZmljYXRlLzEuMC9sZC1jb250ZXh0Lmpzb24iXSwidHlwZSI6WyJWZXJpZmlhYmxlQ3JlZGVudGlhbCIsIlByb2dyYW1Db21wbGV0aW9uQ2VydGlmaWNhdGUiXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiYWNjb21wbGlzaG1lbnRUeXBlIjoiRGV2ZWxvcGVyIENlcnRpZmljYXRlIiwibmFtZSI6ImEiLCJhY2hpZXZlbWVudCI6IkNlcnRpZmllZCBTb2xpZGl0eSBEZXZlbG9wZXIgMiIsImNvdXJzZVByb3ZpZGVyIjoiVU0gRkVSSSJ9LCJjcmVkZW50aWFsU2NoZW1hIjp7ImlkIjoiaHR0cHM6Ly9iZXRhLmFwaS5zY2hlbWFzLnNlcnRvLmlkL3YxL3B1YmxpYy9wcm9ncmFtLWNvbXBsZXRpb24tY2VydGlmaWNhdGUvMS4wL2pzb24tc2NoZW1hLmpzb24iLCJ0eXBlIjoiSnNvblNjaGVtYVZhbGlkYXRvcjIwMTgifX0sInN1YiI6ImRpZDpldGhyOnJpbmtlYnk6MHg2QTI0Njg3NjIxY0REMUM3N0JiNmFDYkJFRTkxMGQwQzUxN2VCNDQzIiwibmJmIjoxNjUyNDQzNjkwLCJpc3MiOiJkaWQ6ZXRocjpyaW5rZWJ5OjB4MDI0MWFiZDY2MmRhMDZkMGFmMmYwMTUyYTgwYmMwMzdmNjVhN2Y5MDExNjBjZmUxZWIzNWVmM2YwYzUzMmEyYTRkIn0.Z4q7kn4vKdFI5QfAyQmqtWa0icAv91HqxSEwn-AMr4_bY3vfD_WeD3W9hgqf9tsUJPx2ru5gY3tLpAx04nk0RQ',
},
};

const connectButton = document.querySelector('button.connect');

const getVCBtn = document.querySelector('button.getVCs');

const saveBtn = document.querySelector('button.saveVC');
const saveCeramicBtn = document.querySelector('button.saveVCC');

const getVPBtn = document.querySelector('button.getVP');

const switchMethodBtn = document.querySelector('button.switchMethod');

const getDIDBtn = document.querySelector('button.getCurrentDid');
const getMethodBtn = document.querySelector('button.getCurrentMethod');
const getAvailableMethodsBtn = document.querySelector(
'button.getAvailableMethods'
);

const popups = document.querySelector('button.togglePopups');
const infura = document.querySelector('button.changeInfuraToken');
const resolveDID = document.querySelector('button.resolveDID');

const getVCStoreBtn = document.querySelector('button.getVCStore');
const toggleVCStoreBtn = document.querySelector('button.toggleVCStore');
const getavaiVCstoreBtn = document.querySelector(
'button.getAvailableVCStores'
);

$(document).ready(function () {
$('textarea#VC').text(JSON.stringify(placeholderVC));
});

connectButton.addEventListener('click', connect);

getVCBtn.addEventListener('click', getVCs);

saveBtn.addEventListener('click', saveVC);
saveCeramicBtn.addEventListener('click', saveVCC);

getVPBtn.addEventListener('click', getVp);

switchMethodBtn.addEventListener('click', switchMethod);

getDIDBtn.addEventListener('click', getDID);
getMethodBtn.addEventListener('click', getMethod);
getAvailableMethodsBtn.addEventListener('click', getAvailableMethods);

popups.addEventListener('click', togglePopups);
infura.addEventListener('click', changeInfuraToken);
resolveDID.addEventListener('click', resolveDIDDocument);

getVCStoreBtn.addEventListener('click', getVCStore);
toggleVCStoreBtn.addEventListener('click', toggleVCStore);
getavaiVCstoreBtn.addEventListener('click', getAvailableVCStores);

// here we get permissions to interact with and install the snap
async function connect() {
console.log('snap id', snapId);
const snaps = await window.ethereum.request({
method: 'wallet_getSnaps',
});
console.log('Installed snaps...', snaps);
await ethereum.request({
method: 'wallet_requestSnaps',
params: {
[snapId]: { version: 'latest' },
},
});
}
Expand Down Expand Up @@ -379,9 +447,7 @@ <h1>Hello, Snaps!</h1>

async function resolveDIDDocument() {
try {
const did = document
.getElementById('infura_token')
.value.toString();
const did = document.getElementById('infura_token').value.toString();
const response = await ethereum.request({
method: `wallet_snap_${snapId}`,
params: {
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/blockchain-lab-um/ssi-snap.git"
},
"source": {
"shasum": "akIVg99PokQc6vh8przmwk3FyuS169CX2C/ro3q9hSA=",
"shasum": "iN81K7o1jIYr3gRBcvZd3pEGPg8eDelIg+Hg+42vSp4=",
"location": {
"npm": {
"filePath": "dist/snap.js",
Expand Down
16 changes: 10 additions & 6 deletions packages/snap/src/did/key/keyDidResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,21 @@ import {
Resolvable,
} from 'did-resolver';
import { getCurrentAccount, getPublicKey } from '../../utils/snapUtils';
import { SnapsGlobalObject } from '@metamask/snaps-utils';
import { SnapsGlobalObject } from '@metamask/snaps-types';
import { getSnapState } from '../../utils/stateUtils';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const resolveSecp256k1 = async (
snap: SnapsGlobalObject,
account: string,
did: string
): Promise<DIDDocument> => {
const state = await getSnapState(snap);
const publicKey = await getPublicKey({ snap, state, account });
const publicKey = await getPublicKey({
snap,
state,
account,
ethereum,
});

// TODO: Change id ?
const didDocument: DIDDocument = {
Expand Down Expand Up @@ -63,7 +67,8 @@ export const resolveDidKey: DIDResolver = async (
): Promise<DIDResolutionResult> => {
try {
// FIXME: Update this part
const account = await getCurrentAccount(snap);

const account = await getCurrentAccount(ethereum);
if (!account) throw Error('User denied error');
// --------

Expand All @@ -89,8 +94,7 @@ export const resolveDidKey: DIDResolver = async (
didDocument: null,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
} catch (err: unknown) {
return {
didDocumentMetadata: {},
didResolutionMetadata: {
Expand Down
6 changes: 3 additions & 3 deletions packages/snap/src/did/pkh/pkhDidUtils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { SnapsGlobalObject } from '@metamask/snaps-types';
import { MetaMaskInpageProvider } from '@metamask/providers';
import { getCurrentNetwork } from '../../utils/snapUtils';

export async function getDidPkhIdentifier(
snap: SnapsGlobalObject,
ethereum: MetaMaskInpageProvider,
account: string
): Promise<string> {
const network = await getCurrentNetwork(snap);
const network = await getCurrentNetwork(ethereum);
if (network === '0x137') {
return 'eip155:137:' + account;
} else return 'eip155:1:' + account;
Expand Down
10 changes: 4 additions & 6 deletions packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,19 @@ import { deleteVC } from './rpc/vc/deleteVC';
import { resolveDID } from './rpc/did/resolveDID';

export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
let state = await getSnapStateUnchecked(snap);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument

if (state === null) state = await initSnapState(snap);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const account = await getCurrentAccount(snap);

const account = await getCurrentAccount(ethereum);

// FIXME: HANDLE NULL maybe throw ?
if (account === null) return;

const apiParams: ApiParams = {
state,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
snap,
ethereum,
account,
};

Expand All @@ -69,7 +68,6 @@ export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => {
);
apiParams.bip44CoinTypeNode = await getAddressKeyDeriver(apiParams);
return await createVP(apiParams, request.params);

case 'togglePopups':
return await togglePopups(apiParams);
case 'switchDIDMethod':
Expand Down
4 changes: 3 additions & 1 deletion packages/snap/src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {
SSISnapConfig,
SSIAccountConfig,
} from '@blockchain-lab-um/ssi-snap-types';
import { SnapsGlobalObject } from '@metamask/snaps-utils';
import { SnapsGlobalObject } from '@metamask/snaps-types';
import { BIP44CoinTypeNode } from '@metamask/key-tree';
import { MetaMaskInpageProvider } from '@metamask/providers';

export type SSISnapState = {
/**
Expand Down Expand Up @@ -73,6 +74,7 @@ export type SnapConfirmParams = {
export interface ApiParams {
state: SSISnapState;
snap: SnapsGlobalObject;
ethereum: MetaMaskInpageProvider;
account: string;
bip44CoinTypeNode?: BIP44CoinTypeNode;
}
4 changes: 2 additions & 2 deletions packages/snap/src/rpc/did/getDID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import { ApiParams } from '../../interfaces';
import { getCurrentDid } from '../../utils/didUtils';

export async function getDid(params: ApiParams): Promise<string> {
const { state, snap, account } = params;
return await getCurrentDid(snap, state, account);
const { state, ethereum, account } = params;
return await getCurrentDid(ethereum, state, account);
}
10 changes: 8 additions & 2 deletions packages/snap/src/rpc/did/switchMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export async function switchMethod(
params: ApiParams,
{ didMethod }: SwitchMethodRequestParams
): Promise<string> {
const { state, snap, account } = params;
const { state, snap, ethereum, account } = params;
const method = state.accountState[account].accountConfig.ssi.didMethod;
if (didMethod !== method) {
const promptObj = {
Expand All @@ -17,7 +17,13 @@ export async function switchMethod(
};

if (snapConfirm(snap, promptObj)) {
return await changeCurrentMethod(snap, state, account, didMethod);
return await changeCurrentMethod(
snap,
ethereum,
state,
account,
didMethod
);
}

return '';
Expand Down
1 change: 0 additions & 1 deletion packages/snap/src/rpc/snap/configure.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/restrict-plus-operands */
import { ApiParams } from '../../interfaces';
import {
togglePopups as updatePopups,
Expand Down
3 changes: 2 additions & 1 deletion packages/snap/src/rpc/vc/deleteVC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export async function deleteVC(
args: DeleteVCsRequestParams
): Promise<boolean[]> {
const { id, options } = args || {};
const { snap } = params;
const { snap, ethereum } = params;
const store = options?.store;
const promptObj = {
prompt: 'Delete VC',
Expand All @@ -19,6 +19,7 @@ export async function deleteVC(
if (snapConfirm(snap, promptObj)) {
return await veramoDeleteVC({
snap,
ethereum,
id,
store,
});
Expand Down
3 changes: 2 additions & 1 deletion packages/snap/src/rpc/vc/queryVCs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ export async function queryVCs(
): Promise<QueryVCsRequestResult[]> {
const { filter, options } = args || {};
const { store, returnStore = true } = options || {};
const { state, snap } = params;
const { state, snap, ethereum } = params;

const vcs = await veramoQueryVCs({
snap,
ethereum,
options: { store, returnStore },
filter, // TODO: Check if undefined is ok
});
Expand Down
10 changes: 3 additions & 7 deletions packages/snap/src/rpc/vc/saveVC.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import {
AvailableVCStores,
SaveVCRequestParams,
} from '@blockchain-lab-um/ssi-snap-types';
import { SaveVCRequestParams } from '@blockchain-lab-um/ssi-snap-types';
import { IDataManagerSaveResult } from '@blockchain-lab-um/veramo-vc-manager';
import { ApiParams } from '../../interfaces';
import { snapConfirm } from '../../utils/snapUtils';
import { veramoSaveVC } from '../../utils/veramoUtils';
import { getEnabledVCStores } from '../../utils/snapUtils';

export async function saveVC(
params: ApiParams,
{ verifiableCredential, options }: SaveVCRequestParams
): Promise<IDataManagerSaveResult[]> {
const { store = 'snap' } = options || {};
const { snap } = params;
const { snap, ethereum } = params;
const promptObj = {
prompt: 'Save VC',
description: `Would you like to save the following VC in ${
Expand All @@ -23,9 +19,9 @@ export async function saveVC(
};

if (snapConfirm(snap, promptObj)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await veramoSaveVC({
snap,
ethereum,
verifiableCredential,
store,
});
Expand Down
Loading

0 comments on commit d89194d

Please sign in to comment.