Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/1208492315807986 Address unification in SDK #32

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"repository": "https://github.com/peaqnetwork/peaq-js.git",
"dependencies": {
"@polkadot/api": "12.4.2",
"ethers": "^6.13.3",
"peaq-did-proto-js": "^2.1.0",
"uuid": "^9.0.0"
},
Expand Down
3 changes: 3 additions & 0 deletions packages/sdk/src/modules/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Options, SDKMetadata } from '../../types';

import { Base } from '../base';
import { GenerateDidOptions, GenerateDidResult, Did } from '../did';
import { Unification } from "../unification";
import { RBAC } from "../rbac";
import { Storage } from "../storage";

Expand All @@ -20,6 +21,7 @@ export class Main extends Base {
private _metadata: SDKMetadata;

public did: Did;
public unification: Unification;
public rbac: RBAC;
public storage: Storage;

Expand All @@ -30,6 +32,7 @@ export class Main extends Base {
this._metadata = {};

this.did = new Did(this._api, this._metadata);
this.unification = new Unification(this._api, this._metadata);
this.rbac = new RBAC(this._api, this._metadata);
this.storage = new Storage(this._api, this._metadata);
}
Expand Down
118 changes: 118 additions & 0 deletions packages/sdk/src/modules/unification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { Base } from '../base';
import { ApiPromise } from '@polkadot/api';
import { decodeAddress } from '@polkadot/keyring';
import type { ISubmittableResult } from '@polkadot/types/types';

import type { SDKMetadata } from '../../types';
import { ethers, Wallet } from "ethers";

interface ClaimAccountOptions {
substrateSeed: string,
ethPrivate: string
}

export class Unification extends Base {
constructor(
protected override readonly _api?: ApiPromise,
protected readonly _metadata?: SDKMetadata,

) {
super();
}

// TODO just return the ethereum address?
// How does the user know what their mnenonmic phrase and private key are...
// - Can we safely return??

public async claimAccount(options: ClaimAccountOptions, statusCallback?: (result: ISubmittableResult) => void | Promise<void>): Promise<string> {
Copy link
Contributor Author

@jpgundrum jpgundrum Oct 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently only offering address unification for newly created eth wallets which are mapped to a SS58 address.

try {
const api = this._getApi();

const { substrateSeed, ethPrivate} = options;
if (!substrateSeed) {
throw new Error("Error: No substrate private key provided.");
}
if (!ethPrivate) {
throw new Error("Error: No ethereum private key provided.");
}

const keyPair = this._metadata?.pair || this._getKeyPair(substrateSeed);
const ss58Address = keyPair.address;

// create wallet from ETH private key
const signer = new ethers.Wallet(ethPrivate);
const evmAddress = signer.address;

const ethSignature = await this._createKeyBind(ss58Address, signer);
// console.log(ethSignature);

const attributeExtrinsic = api.tx?.['addressUnification']?.['claimAccount'](
evmAddress,
ethSignature
);

const nonce = await this._getNonce(keyPair.address);
const eventData = await this._newSignTx({nonce, address: keyPair, extrinsics: attributeExtrinsic});
const unsubscribe = await attributeExtrinsic.send((result) => {
statusCallback &&
statusCallback(result as unknown as ISubmittableResult);
});

console.log(eventData);

return `Successfully unified the evm address of ${evmAddress} to the substrate address of ${ss58Address}`;
irediaes marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
throw new Error(`${error}`);
}
}


protected async _createKeyBind(ss58Address: string, signer: Wallet): Promise <string>{
try {
const api = this._getApi();

// Case where we connect a previously known ethereum wallet to their current substrate address
const chainMap = new Map();
chainMap.set("Agung-parachain", 9990);
chainMap.set("krest-network", 2241);
chainMap.set("peaq-network", 3338);
jpgundrum marked this conversation as resolved.
Show resolved Hide resolved

// derive chain id -> is there a better way to get chainId from api than than creating a mapping?
jpgundrum marked this conversation as resolved.
Show resolved Hide resolved
const chain = api.runtimeChain.toHuman();
const chainId = chainMap.get(chain);
console.log(chainId);

const signature = await this._generateSignature(
signer,
ss58Address,
chainId
);
console.log("Generated signature:", signature);
return signature;

} catch (error){
throw new Error(`${error}`);
}
}

protected async _generateSignature(signer: Wallet, ss58Address: string, chainId: string) {
const api = this._getApi();
const blockHash = await api.rpc.chain.getBlockHash(0);

return await signer.signTypedData(
{
name: "Peaq EVM claim",
version: "1",
chainId: chainId,
salt: blockHash,
},
{
Transaction: [{ type: "bytes", name: "substrateAddress" }],
},
{
substrateAddress: decodeAddress(ss58Address),
}
);
}

}
31 changes: 31 additions & 0 deletions packages/sdk/src/modules/unification/unification.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ApiPromise } from '@polkadot/api';
import { Keyring } from '@polkadot/keyring';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { Main as SDK } from '../main';

import dotenv from 'dotenv';
dotenv.config(); // Load variables from .env file
const SEED = process.env['SEED'] as string;
const ETH_PRIVATE = process.env['ETH_PRIVATE'] as string;
const BASE_URL = process.env['BASE_URL'] as string;

describe('Unification', () => {

describe('create binds', () => {
// works when I create an ETH wallet from sktrach that has no previous transactions

// first test with with new ss58 (still know seed phrase) and generates a new h160
it('known ss58 to known h160 bind', async () => {
const keyring = new Keyring({ type: 'sr25519' });
await cryptoWaitReady();
const user = keyring.addFromUri(SEED);
const sdk = await SDK.createInstance({baseUrl: BASE_URL, seed: SEED});

await sdk.unification.claimAccount({substrateSeed: SEED, ethPrivate: ETH_PRIVATE});

}, 50000);

// TODO 2nd test with with an old ss58 (has transactions) and binds a previously created H160 (has transaction)
})

})