-
Notifications
You must be signed in to change notification settings - Fork 2
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
base: dev
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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, | ||
} | ||
|
||
|
||
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> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @jpgundrum Please fix this. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I removed this function to only use the enum itself |
||
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.`) | ||
} | ||
} |
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); | ||
}) | ||
}) |
There was a problem hiding this comment.
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