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 2 commits
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
139 changes: 139 additions & 0 deletions packages/sdk/src/modules/unification/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { Base } from '../base';
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 {
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,
protected readonly _metadata?: SDKMetadata,

) {
super();
}

/**
* 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 { 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._getKeyPair(substrateSeed);
const ss58Address = keyPair.address;

const signer = new ethers.Wallet(ethPrivate);
const evmAddress = signer.address;

const ethSignature = await this._createKeyBind(network, ss58Address, signer);

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);
});

return {
message: "Address Unification Successful.",
evm: `${evmAddress}`,
substrate: `${ss58Address}`
}
} catch (error) {
throw new ClaimAccountError(`${error}`);
}
}

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

const chainId = await this._getChainId(network);

const signature = await this._generateSignature(
signer,
ss58Address,
chainId.toString()
);

return signature;

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

protected async _generateSignature(signer: Wallet, ss58Address: string, chainId: string) {
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.`)
}
}
60 changes: 60 additions & 0 deletions packages/sdk/src/modules/unification/unification.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
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;


/**
* 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', () => {
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);
})
})
Loading