Skip to content

Subsidize adding an Ethereum compatible control key #2403

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

Merged
merged 15 commits into from
May 27, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 13 additions & 1 deletion common/primitives/src/msa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,19 @@ pub trait SchemaGrantValidator<BlockNumber> {
) -> DispatchResult;
}

/// RPC Response for getting getting MSA keys
/// A trait that allows checking whether adding a key may be subsidized
pub trait MsaKeyProvider {
/// the type to use for looking up keys in storage.
type AccountId;
/// Returns whether adding `new_key` to `msa_id` may be subsidized
fn key_eligible_for_subsidized_addition(
old_key: Self::AccountId,
new_key: Self::AccountId,
msa_id: MessageSourceId,
) -> bool;
}

/// RPC Response for getting MSA keys
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(TypeInfo, Debug, Clone, Decode, Encode, PartialEq, Default, MaxEncodedLen)]
pub struct KeyInfoResponse<AccountId> {
Expand Down
25 changes: 23 additions & 2 deletions common/primitives/src/signatures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ pub trait AccountAddressMapper<AccountId> {

/// reverses an accountId to it's 20 byte ethereum address
fn to_ethereum_address(account_id: AccountId) -> H160;

/// returns whether `account_id` converts to a valid Ethereum address
fn is_ethereum_address(account_id: &AccountId) -> bool;
}

/// converting raw address bytes to 32 bytes Ethereum compatible addresses
Expand Down Expand Up @@ -89,13 +92,17 @@ impl AccountAddressMapper<AccountId32> for EthereumAddressMapper {

fn to_ethereum_address(account_id: AccountId32) -> H160 {
let mut eth_address = [0u8; 20];
if account_id.as_slice()[20..] == *[0xEE; 12].as_slice() {
if Self::is_ethereum_address(&account_id) {
eth_address[..].copy_from_slice(&account_id.as_slice()[0..20]);
} else {
log::error!("Incompatible ethereum account id is provided {:?}", account_id);
}
eth_address.into()
}

fn is_ethereum_address(account_id: &AccountId32) -> bool {
account_id.as_slice()[20..] == *[0xEE; 12].as_slice()
}
}

/// Signature verify that can work with any known signature types.
Expand Down Expand Up @@ -414,7 +421,7 @@ mod tests {
signatures::{UnifiedSignature, UnifiedSigner},
};
use impl_serde::serialize::from_hex;
use sp_core::{ecdsa, Pair};
use sp_core::{ecdsa, sr25519, Pair};
use sp_runtime::{
traits::{IdentifyAccount, Verify},
AccountId32,
Expand Down Expand Up @@ -601,4 +608,18 @@ mod tests {
assert_eq!(account_id, AccountId32::new(expected_address.clone().try_into().unwrap()));
assert_eq!(bytes.to_vec(), expected_address);
}

#[test]
fn ethereum_address_mapper_is_ethereum_address_correctly_detects() {
let valid_eth_address =
from_hex("0x917B536617B0A42B2ABE85AC88788825F29F0B29eeeeeeeeeeeeeeeeeeeeeeee")
.expect("should be hex");
let valid_addr32 = AccountId32::new(valid_eth_address.clone().try_into().unwrap());

assert!(EthereumAddressMapper::is_ethereum_address(&valid_addr32));

let (pair, _) = sr25519::Pair::generate();
let random_addr32 = AccountId32::from(pair.public());
assert!(!EthereumAddressMapper::is_ethereum_address(&random_addr32));
}
}
12 changes: 1 addition & 11 deletions e2e/capacity/transactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,6 @@ describe('Capacity Transactions', function () {
assert.notEqual(schemaId, undefined, 'setup should populate schemaId');
});

function getCapacityFee(chainEvents: EventMap): bigint {
if (
chainEvents['capacity.CapacityWithdrawn'] &&
ExtrinsicHelper.api.events.capacity.CapacityWithdrawn.is(chainEvents['capacity.CapacityWithdrawn'])
) {
return chainEvents['capacity.CapacityWithdrawn'].data.amount.toBigInt();
}
return 0n;
}

describe('when capacity eligible transaction is from the msa pallet', function () {
let capacityKeys: KeyringPair;
let capacityProvider: u64;
Expand Down Expand Up @@ -142,7 +132,7 @@ describe('Capacity Transactions', function () {
assertEvent(eventMap, 'capacity.CapacityWithdrawn');
assertEvent(eventMap, 'msa.DelegationGranted');

const fee = getCapacityFee(eventMap);
const fee = ExtrinsicHelper.getCapacityFee(eventMap);
// assuming no other txns charged against capacity (b/c of async tests), this should be the maximum amount left.
const maximumExpectedRemaining = stakedForMsa / getTokenPerCapacity() - fee;

Expand Down
131 changes: 131 additions & 0 deletions e2e/msa/addKeyLowCost.ethereum.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { KeyringPair } from '@polkadot/keyring/types';
import { AddKeyData, Extrinsic, ExtrinsicHelper } from '../scaffolding/extrinsicHelpers';
import {
assertEvent,
CENTS,
createKeys,
createMsa,
createMsaAndProvider,
DOLLARS,
generateAddKeyPayload,
getEthereumKeyPairFromUnifiedAddress,
signPayloadSr25519,
stakeToProvider,
} from '../scaffolding/helpers';
import { getUnifiedAddress, getUnifiedPublicKey } from '../scaffolding/ethereum';
import assert from 'assert';
import { getFundingSource } from '../scaffolding/funding';
import { u64 } from '@polkadot/types';
import { MessageSourceId } from '@frequency-chain/api-augment/interfaces';
import { createAddKeyData, signEip712 } from '@frequency-chain/ethereum-utils';
import { u8aToHex } from '@polkadot/util';

const fundingSource = getFundingSource(import.meta.url);

describe('adding an Ethereum key for low cost', function () {
let providerKeys;
let providerMsaId;

before(async function () {
providerKeys = await createKeys('KeyAdder');
providerMsaId = await createMsaAndProvider(fundingSource, providerKeys, 'KeyAdder', 10n * CENTS);
await stakeToProvider(fundingSource, fundingSource, providerMsaId, 6n * DOLLARS);
});

// create a delegator MSA account with new keys,
// create a new Ethereum keypair,
// call generateAddKeyCallParamsUsingKeys,
// return the new keys, the resulting payload, and both signatures.
async function generateAddKeyCallParams() {
const ethereumKeyringPair = await createKeys('Ethereum', 'ethereum');
const [delegatorMsaId, delegatorKeys] = await createMsa(fundingSource, 10n * CENTS);
const { addKeyPayload, delegatorSig, newSig } = await generateAddKeyCallParamsUsingKeys(
delegatorKeys,
delegatorMsaId,
ethereumKeyringPair
);
return { delegatorKeys, addKeyPayload, delegatorSig, newSig };
}

// create AddKeyData using the provided keys.
// use the keys to sign the AddKeyData in an AddKey payload.
// return the new keys, the payload, and both signatures.
async function generateAddKeyCallParamsUsingKeys(
delegatorKeys: KeyringPair,
delegatorMsaId: u64,
ethereumKeyringPair: KeyringPair
) {
const addKeyPayload = await generateAddKeyPayload({});
addKeyPayload.msaId = delegatorMsaId;
addKeyPayload.newPublicKey = getUnifiedPublicKey(ethereumKeyringPair);

const srSignatureaddKeyData = ExtrinsicHelper.api.registry.createType('PalletMsaAddKeyData', addKeyPayload);
const delegatorSrSignature = signPayloadSr25519(delegatorKeys, srSignatureaddKeyData);

const ethereumSecretKey = u8aToHex(
getEthereumKeyPairFromUnifiedAddress(getUnifiedAddress(ethereumKeyringPair)).secretKey
);
const eip712AddKeyData = createAddKeyData(
addKeyPayload.msaId.toBigInt(),
u8aToHex(addKeyPayload.newPublicKey),
addKeyPayload.expiration
);
const ecdsaSignature = await signEip712(ethereumSecretKey, eip712AddKeyData);

return { addKeyPayload, delegatorSig: delegatorSrSignature, newSig: ecdsaSignature };
}

it('addPublicKeyToMsa costs less for capacity call with eligibility conditions', async function () {
// SET UP
const { delegatorKeys, addKeyPayload, delegatorSig, newSig } = await generateAddKeyCallParams();

// the extrinsic will be called by a provider with stake.
const addPublicKeyOp = new Extrinsic(
() =>
ExtrinsicHelper.api.tx.msa.addPublicKeyToMsa(
getUnifiedPublicKey(delegatorKeys),
delegatorSig,
newSig,
addKeyPayload
),
providerKeys,
ExtrinsicHelper.api.events.msa.PublicKeyAdded
);

// ACT pay with capacity using the provider.
const { eventMap } = await addPublicKeyOp.payWithCapacity();

// ASSERT it's a very small fee, but not free.
assertEvent(eventMap, 'msa.PublicKeyAdded');
const capacityFee = ExtrinsicHelper.getCapacityFee(eventMap);
assert(capacityFee > 0);
assert(capacityFee < 1_320_000n); // ~1.3 CENTS

// add another key; this should cost a lot more
const thirdKeyEth = await createKeys('Eth2', 'ethereum');
const delegatorMsaId: MessageSourceId = addKeyPayload.msaId || new u64(ExtrinsicHelper.api.registry, 0);
const newParams = await generateAddKeyCallParamsUsingKeys(delegatorKeys, delegatorMsaId, thirdKeyEth);

// again to be submitted by provider.
const addThirdKeyOp = new Extrinsic(
() =>
ExtrinsicHelper.api.tx.msa.addPublicKeyToMsa(
getUnifiedPublicKey(delegatorKeys),
newParams.delegatorSig,
newParams.newSig,
newParams.addKeyPayload
),
providerKeys,
ExtrinsicHelper.api.events.msa.PublicKeyAdded
);

// ACT pay with capacity to add a third key
const { eventMap: eventMap2 } = await addThirdKeyOp.payWithCapacity();
assertEvent(eventMap2, 'msa.PublicKeyAdded');
const thirdKeyCapacityFee = ExtrinsicHelper.getCapacityFee(eventMap2);
// 4260363n vs
// 1278109n
assert(thirdKeyCapacityFee > capacityFee);
assert(thirdKeyCapacityFee < 5n * CENTS);
});
});
6 changes: 4 additions & 2 deletions e2e/msa/msaTokens.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,10 @@ describe('MSAs Holding Tokens', function () {
describe('getEthereumAddressForMsaId', function () {
it('should return the correct address for a given MSA ID', async function () {
const expectedAddress = CHECKSUMMED_ETH_ADDR_1234.toLowerCase();
const { accountId, accountIdChecksummed } =
await ExtrinsicHelper.apiPromise.call.msaRuntimeApi.getEthereumAddressForMsaId(MSA_ID_1234);
const result: any = await ExtrinsicHelper.apiPromise.call.msaRuntimeApi.getEthereumAddressForMsaId(MSA_ID_1234);
const accountId = result?.accountId;
const accountIdChecksummed = result?.accountIdChecksummed;

assert.equal(accountId.toHex(), expectedAddress, `Expected address ${expectedAddress}, but got ${accountId}`);
assert.equal(
accountIdChecksummed.toString(),
Expand Down
Loading