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
129 changes: 75 additions & 54 deletions packages/sdk/src/modules/unification/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,29 @@ import { ApiPromise } from '@polkadot/api';
import { decodeAddress } from '@polkadot/keyring';
import type { ISubmittableResult } from '@polkadot/types/types';

import { ChainIdError, CreateKeyBindError, ClaimAccountError, GenerateSignatureError } from '../../utils/errors';
import type { SDKMetadata } from '../../types';
import { ethers, Wallet } from "ethers";

interface ClaimAccountOptions {
substrateSeed: string,
ethPrivate: string
network: string;
substrateSeed: string;
ethPrivate: string;
}

interface ClaimAccountResult {
message: string;
evm: string;
substrate: string;
}

enum ChainID {
AGUNG = 9990,
KREST = 2241,
PEAQ = 3338,
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Create new enum type to define network in the claim account options


export class Unification extends Base {
constructor(
protected override readonly _api?: ApiPromise,
Expand All @@ -20,31 +35,29 @@ export class Unification extends Base {
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> {
/**
* Binds a SS58 Substrate wallet to a newly created H160 Ethereum wallet using the address unification pallet peaq provides.
* Make sure the H160 wallet is new and has no transactions.
*
* @param options ClaimAccountOptions - The options for binding the addresses.
* @returns CreateDidResult - Contains the block_hash of the executed transaction and unsubscribe() to terminate event listening.
*/
public async claimAccount(options: ClaimAccountOptions, statusCallback?: (result: ISubmittableResult) => void | Promise<void>): Promise<ClaimAccountResult> {
irediaes marked this conversation as resolved.
Show resolved Hide resolved
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 { network, substrateSeed, ethPrivate} = options;
if (!network) throw new Error("Error: No network provided.");
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 keyPair = 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 ethSignature = await this._createKeyBind(network, ss58Address, signer);

const attributeExtrinsic = api.tx?.['addressUnification']?.['claimAccount'](
evmAddress,
Expand All @@ -58,61 +71,69 @@ export class Unification extends Base {
statusCallback(result as unknown as ISubmittableResult);
});

console.log(eventData);

return `Successfully unified the evm address of ${evmAddress} to the substrate address of ${ss58Address}`;
return {
message: "Address Unification Successful.",
evm: `${evmAddress}`,
substrate: `${ss58Address}`
}
} catch (error) {
throw new Error(`${error}`);
throw new ClaimAccountError(`${error}`);
}
}


protected async _createKeyBind(ss58Address: string, signer: Wallet): Promise <string>{
protected async _createKeyBind(network: string, 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);

// derive chain id -> is there a better way to get chainId from api than than creating a mapping?
const chain = api.runtimeChain.toHuman();
const chainId = chainMap.get(chain);
console.log(chainId);
const chainId = await this._getChainId(network);

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

return signature;

} catch (error){
throw new Error(`${error}`);
throw new CreateKeyBindError(`${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),
}
);
try {
const api = this._getApi();
const blockHash = await api.rpc.chain.getBlockHash(0);

return await signer.signTypedData(
{
name: "Peaq EVM claim",
irediaes marked this conversation as resolved.
Show resolved Hide resolved
version: "1",
chainId: chainId,
salt: blockHash,
},
{
Transaction: [{ type: "bytes", name: "substrateAddress" }],
},
{
substrateAddress: decodeAddress(ss58Address),
}
);
} catch (error){
throw new GenerateSignatureError(`${error}`);
}
}

protected async _getChainId(network: string): Promise<number> {
Copy link
Member

Choose a reason for hiding this comment

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

The network param should be an enum type.

Copy link
Member

Choose a reason for hiding this comment

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

@jpgundrum Please fix this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I removed this function to only use the enum itself const chainId = ChainID[network.toUpperCase() as keyof typeof ChainID];

switch (network.toUpperCase()) {
irediaes marked this conversation as resolved.
Show resolved Hide resolved
case "AGUNG":
return ChainID.AGUNG;
case "KREST":
return ChainID.KREST;
case "PEAQ":
return ChainID.PEAQ;
}
throw new ChainIdError(`Network not found. Make sure you correctly set your network parameter to either agung, krest, or
peaq based on the base url set during SDK initialization.`)
}
}
61 changes: 45 additions & 16 deletions packages/sdk/src/modules/unification/unification.spec.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,60 @@
import { ApiPromise } from '@polkadot/api';
import { Keyring } from '@polkadot/keyring';
import { KeyringPair } from '@polkadot/keyring/types';
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;
const EVM_ADDRESS = process.env['EVM_ADDRESS'] as string;
const SUBSTRATE_ADDRESS = process.env['SUBSTRATE_ADDRESS'] as string;

describe('Unification', () => {

/**
* Performs tests when executing unification for SS58 to H160 addresses.
*
* To execute correctly make sure the EVM address on the network has no previous transactions.
*/
describe('Unification', () => {
let keyring: Keyring;
let user: KeyringPair;
let sdk: SDK;

beforeAll(async () => {
keyring = new Keyring({ type: 'sr25519' });
await cryptoWaitReady();
user = keyring.addFromUri(SEED);
sdk = await SDK.createInstance({baseUrl: BASE_URL, seed: SEED});
}, 40000);


/**
* Test suite for the executing expected operations.
*
* 1. Make sure setting an incorrect network name performs no transactions
* 2. Create a bind to an SS58 to H160 wallet
* 3. Error when a keybind has been created previously
*/
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});

it('incorrect network name', async () => {
await expect(sdk.unification.claimAccount({network: "random", substrateSeed: SEED, ethPrivate: ETH_PRIVATE}))
.rejects.toThrow(new Error(`CreateKeyBindError: ChainIdError: Network not found. Make sure you correctly set your network parameter to either agung, krest, or
peaq based on the base url set during SDK initialization.`));
}, 50000);
// works when I create an ETH wallet from scratch that has no previous transactions on the network
// and when you first setup an initial keybind... make sure the baseUrl that you initialize to matches the network you are claiming the account with
it('known ss58 to newly created known h160 bind', async () => {
const result = await sdk.unification.claimAccount({network: "agung", substrateSeed: SEED, ethPrivate: ETH_PRIVATE});
expect(result.message).toBe("Address Unification Successful.");
expect(result.evm).toBe(EVM_ADDRESS);
expect(result.substrate).toBe(SUBSTRATE_ADDRESS);
}, 80000);
it('Expect an error when a previous keybind has already been created', async () => {
await expect(sdk.unification.claimAccount({network: "agung", substrateSeed: SEED, ethPrivate: ETH_PRIVATE}))
.rejects.toThrow(new Error(`Error: AccountIdHasMapped for addressUnification.`));
}, 50000);

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

})
34 changes: 34 additions & 0 deletions packages/sdk/src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,38 @@ export class StorageSeedError extends StorageError {
this.name = 'StorageSeedError'; // Set the name property to the custom error type
Object.setPrototypeOf(this, new.target.prototype); // Restore the prototype chain
}
}


// Address Unification Errors
export class ChainIdError extends Error {
constructor(message: string) {
super(message);
this.name = 'ChainIdError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class CreateKeyBindError extends Error {
constructor(message: string) {
super(message);
this.name = 'CreateKeyBindError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class GenerateSignatureError extends Error {
constructor(message: string) {
super(message);
this.name = 'CreateKeyBindError';
Object.setPrototypeOf(this, new.target.prototype);
}
}

export class ClaimAccountError extends Error {
constructor(message: string) {
super(message);
this.name = 'CreateKeyBindError';
Object.setPrototypeOf(this, new.target.prototype);
}
}