Skip to content

Commit

Permalink
[CA] Init AAProxy and AAService
Browse files Browse the repository at this point in the history
  • Loading branch information
S2kael committed Oct 25, 2024
1 parent b90250f commit f513216
Show file tree
Hide file tree
Showing 15 changed files with 1,728 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export default class KoniExtension {
// FIXME This looks very much like what we have in Tabs
private accountsSubscribe (id: string, port: chrome.runtime.Port): boolean {
const cb = createSubscription<'pri(accounts.subscribe)'>(id, port);
const accountSubject = this.#koniState.keyringService.accountSubject;
const accountSubject = this.#koniState.keyringService.pairSubject;
const subscription = accountSubject.subscribe((accounts: SubjectInfo): void =>
cb(transformAccounts(accounts))
);
Expand Down Expand Up @@ -504,7 +504,7 @@ export default class KoniExtension {
currentGenesisHash: currentAccount?.currentGenesisHash
};

const subscriptionAccounts = keyringService.accountSubject.subscribe((storedAccounts: SubjectInfo): void => {
const subscriptionAccounts = keyringService.pairSubject.subscribe((storedAccounts: SubjectInfo): void => {
const transformedAccounts = transformAccounts(storedAccounts);

responseData.accounts = transformedAccounts?.length ? [{ ...ACCOUNT_ALL_JSON }, ...transformedAccounts] : [];
Expand Down Expand Up @@ -1778,12 +1778,13 @@ export default class KoniExtension {
transferAmount.value
] = await getEVMTransactionObject(chainInfo, from, to, txVal, !!transferAll, evmApi);
}

const owner = getEthereumSmartAccountOwner(from);
const transferNativeAmount = isTransferNativeToken ? transferAmount.value : '0';

if (owner) {
const provider = await this.#koniState.settingService.getCASettings();
let caTransaction: QuoteResponse | UserOpBundle;
let caTransaction: QuoteResponse | UserOpBundle;

if (provider.caProvider === CAProvider.KLASTER) {
const klasterService = new KlasterService();
Expand All @@ -1796,6 +1797,7 @@ export default class KoniExtension {
gasLimit: BigInt((transaction.gas || 0).toString())
});
const txBatch = batchTx(_getEvmChainId(chainInfo) as number, [transferTx]);

caTransaction = await klasterService.buildTx(chainInfo, [txBatch]);
} else {
caTransaction = await ParticleAAHandler.createUserOperation(_getEvmChainId(chainInfo) || 1, owner, [transaction]);
Expand Down
10 changes: 8 additions & 2 deletions packages/extension-base/src/koni/background/handlers/State.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AccountRefMap, AddTokenRequestExternal, AmountData, APIItemState, ApiMa
import { AccountJson, RequestAuthorizeTab, RequestRpcSend, RequestRpcSubscribe, RequestRpcUnsubscribe, RequestSign, ResponseRpcListProviders, ResponseSigning } from '@subwallet/extension-base/background/types';
import { ALL_ACCOUNT_KEY, ALL_GENESIS_HASH, MANTA_PAY_BALANCE_INTERVAL, REMIND_EXPORT_ACCOUNT } from '@subwallet/extension-base/constants';
import { convertErrorFormat, generateValidationProcess, PayloadValidated, ValidateStepFunction, validationAuthMiddleware, validationAuthWCMiddleware, validationConnectMiddleware, validationEvmDataTransactionMiddleware, validationEvmSignMessageMiddleware } from '@subwallet/extension-base/core/logic-validation';
import { AccountAbstractionService } from '@subwallet/extension-base/services/account-abstraction-service/service';
import { BalanceService } from '@subwallet/extension-base/services/balance-service';
import { ServiceStatus } from '@subwallet/extension-base/services/base/types';
import BuyService from '@subwallet/extension-base/services/buy-service';
Expand Down Expand Up @@ -41,7 +42,7 @@ import { TransactionEventResponse } from '@subwallet/extension-base/services/tra
import WalletConnectService from '@subwallet/extension-base/services/wallet-connect-service';
import { SWStorage } from '@subwallet/extension-base/storage';
import AccountRefStore from '@subwallet/extension-base/stores/AccountRef';
import { BalanceItem, BalanceMap, EvmFeeInfo, StorageDataInterface } from '@subwallet/extension-base/types';
import { AAProvider, BalanceItem, BalanceMap, EvmFeeInfo, StorageDataInterface } from '@subwallet/extension-base/types';
import { isAccountAll, isManifestV3, stripUrl, targetIsWeb } from '@subwallet/extension-base/utils';
import { createPromiseHandler } from '@subwallet/extension-base/utils/promise';
import { MetadataDef, ProviderMeta } from '@subwallet/extension-inject/types';
Expand Down Expand Up @@ -150,6 +151,11 @@ export default class KoniState {
private waitStarting: Promise<void> | null = null;

constructor (providers: Providers = {}) {
AccountAbstractionService.createInstance({
providers: [AAProvider.KLASTER, AAProvider.PARTICLE],
providerConfig: {}
});

this.providers = providers;

this.eventService = new EventService();
Expand All @@ -159,7 +165,7 @@ export default class KoniState {
this.chainService = new ChainService(this.dbService, this.eventService);
this.subscanService = SubscanService.getInstance();
this.settingService = new SettingService();
this.keyringService = new KeyringService(this.eventService, this.settingService);
this.keyringService = new KeyringService(this);
this.requestService = new RequestService(this.chainService, this.settingService, this.keyringService);
this.priceService = new PriceService(this.dbService, this.eventService, this.chainService);
this.balanceService = new BalanceService(this);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2019-2022 @subwallet/extension-base authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { _ChainInfo } from '@subwallet/chain-list/types';
import { _getEvmChainId } from '@subwallet/extension-base/services/chain-service/utils';
import { AAProviderConfig } from '@subwallet/extension-base/types';
import { initKlaster, klasterNodeHost, loadBicoV2Account } from 'klaster-sdk';

export class KlasterService {
static chainTestnetMap: Record<number, boolean> = {};

static async getSmartAccount (ownerAddress: string, config: AAProviderConfig): Promise<string> {
const accountInitData = (() => {
const { name, version } = config;

if (version === '2.0.0' && name === 'BICONOMY') {
return loadBicoV2Account({
owner: ownerAddress as `0x${string}`
});
}

throw Error('Unsupported account abstraction provider');
})();

const klasterSdk = await initKlaster({
accountInitData,
nodeUrl: klasterNodeHost.default
});

return klasterSdk.account.getAddress(1) as string;
}

static updateChainMap (chainInfo: _ChainInfo) {
const chainId = _getEvmChainId(chainInfo) as number;

if (chainId in KlasterService.chainTestnetMap) {
return;
}

KlasterService.chainTestnetMap[chainId] = chainInfo.isTestnet;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright 2019-2022 @subwallet/extension-base authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { AccountContract, SmartAccount, SmartAccountConfig, Transaction, UserOp, UserOpBundle } from '@particle-network/aa';
import { SmartAccountData } from '@subwallet/extension-base/background/types';
import { AAProviderConfig } from '@subwallet/extension-base/types';
import { anyNumberToBN } from '@subwallet/extension-base/utils';
import { createMockParticleProvider } from '@subwallet/extension-base/utils/mock/provider/particle';
import { TransactionConfig } from 'web3-core';

export const ParticleContract: AccountContract = {
name: 'BICONOMY',
version: '2.0.0'
};

const defaultParticleConfig: SmartAccountConfig = {
projectId: '80d48082-7a98-41e0-8eb5-571e2e00cc7f',
clientKey: 'cSuNrTTMf0d2Vp3l9aaAyvGm2UzRjywnNK0duRHN',
appId: 'ca41cf00-9bac-4980-aef5-f521925f3de7',
aaOptions: {
accountContracts: { // 'BICONOMY', 'CYBERCONNECT', 'SIMPLE', 'LIGHT', 'XTERIO'
BICONOMY: [
{
version: '1.0.0',
chainIds: [1]
},
{
version: '2.0.0',
chainIds: [1, 11155111, 8453, 84532, 42161]
}
],
CYBERCONNECT: [
{
version: '1.0.0',
chainIds: [1]
}
],
SIMPLE: [
{
version: '1.0.0',
chainIds: [1]
}
]
}
}
};

export class ParticleAAHandler {
static getSmartAccount = async (owner: string, config: AAProviderConfig): Promise<string> => {
const provider = createMockParticleProvider(1, owner);

const smartAccount = new SmartAccount(provider, defaultParticleConfig);

smartAccount.setSmartAccountContract(config);

return smartAccount.getAddress();
};

static createUserOperation = async (chainId: number, account: SmartAccountData, _txList: TransactionConfig[]): Promise<UserOpBundle> => {
const provider = createMockParticleProvider(chainId, account.owner);

const smartAccount = new SmartAccount(provider, defaultParticleConfig);

smartAccount.setSmartAccountContract(account.provider || ParticleContract);

const txList: Transaction[] = [];

for (const _tx of _txList) {
const tx: Transaction = {
data: _tx.data,
value: anyNumberToBN(_tx.value).toString(),
to: _tx.to || '',
gasLimit: _tx.gas
};

txList.push(tx);
}

console.debug('quote', await smartAccount.getFeeQuotes(txList));

return await smartAccount.buildUserOperation({ tx: txList });
};

static sendSignedUserOperation = async (chainId: number, account: SmartAccountData, userOp: UserOp): Promise<string> => {
const provider = createMockParticleProvider(chainId, account.owner);

const smartAccount = new SmartAccount(provider, defaultParticleConfig);

smartAccount.setSmartAccountContract(account.provider || ParticleContract);

return await smartAccount.sendSignedUserOperation(userOp);
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2019-2022 @subwallet/extension-base authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { UserOpBundle } from '@particle-network/aa';
import { QuoteResponse } from 'klaster-sdk';
import { Observable, Subscribable } from 'rxjs';

enum AAAccountType {
EOA = 'eoa',
CONTRACT = 'contract'
}

/**
* Chain id
* - If negative, it means the chain id is not supported
* - If positive, it means the chain id is supported
* */
type ChainId = number;

interface AAAccount {
address: string;
provider?: string;
chainIds: ChainId[];
providerId: string;
type: AAAccountType;
owner?: string;
}

interface AAProxy {
id: string;
name: string;
accounts: AAAccount[];
}

interface RawTransactionConfig {
to: string;
gas: number | string;
value?: number | string;
data?: string;
chainId: number;
}

/**
* Balance info of a token on an address
* @property {string} address - Address
* @property {string} balance - Transferable balance
* @property {string} token.symbol - Token symbol
* @property {string} token.address - Token address
* @property {number} token.decimals - Token decimals
*/
export interface BalanceItem {
address: string;
balance: string;
token: {
symbol: string;
address: string;
decimals: number;
};
}

type AATransactionBundle = UserOpBundle | QuoteResponse;

export interface AccountAbstractionSDK {
/** Return a subscribable object to subscribe to the AAProxy map */
aaProxyObservable(): Observable<Record<string, AAProxy>>;
/** Return the AAProxy map */
getProxy(): Promise<Record<string, AAProxy>>;
/** Generate a new AAProxy from address */

generateAccount(address: string): Promise<AAProxy>;

/** Auto subscribe balance with chain and asset list from SW */
autoSubscribeBalance(proxyId: string): Subscribable<BalanceItem>;

/** Subscribe balance
* @param {string} proxyId - The proxy id
* @returns {Subscribable<number>} - The subscribable balance
* */
subscribeBalance(proxyId: string, ): Subscribable<BalanceItem>;

/**
* Generate `AATransactionBundle` from a list of `RawTransactionConfig`
* @param {string} sender - The sender address
* @param {RawTransactionConfig[]} txs - The list of `RawTransactionConfig`
* @returns
* bundles: A list of `AATransactionBundle` to sign
*
* - Note: `bundles` is an array because some AA provider only supports batch transaction on the same chain
*/
createTransaction(sender: string, txs: RawTransactionConfig[]): Promise<{
bundles: AATransactionBundle[];
signer: string;
}>;
}
Loading

0 comments on commit f513216

Please sign in to comment.