Consensys / starknet-snap

The MetaMask Snap for Starknet
https://snaps.consensys.net/starknet
Apache License 2.0
74 stars 26 forks source link

chore: add state management base class and shared lock #315

Closed stanleyyconsensys closed 1 month ago

stanleyyconsensys commented 1 month ago

This PR is to add state management base class SnapStateManager

it provides the functionally of update, get, set, withTransaction, commit, rollback

example use:

export type SnapState = {
  walletIds: string[];
  wallets: Wallets;
};

class MyState extends SnapStateManager<SnapState> {
      constructor() {
        super(true);
      }

     async updateWallet(wallet) {
         await this.update(async (state: SnapState) => {
                 const { id, address } = wallet.account;
                 if (
                    this.isAccountExist(state, id) ||
                    this.getAccountByAddress(state, address)
                  ) {
                    throw new Error(`Account address ${address} already exists`);
                  }
              state.wallets[id] = wallet;
        })
     }
}

// Test rollback
async function testRollback() {
    const mgt = new MyState()
    await mgt.withTransaction(async () => {
        await mgt.addWallet({
          account: keyringAccount,
        });
        // if this line fail, it will not update the state
        await this.#emitEvent(KeyringEvent.AccountCreated, {
          account: keyringAccount,
          accountNameSuggestion: this.getKeyringAccountNameSuggestion(options),
        });
    });
}
sonarcloud[bot] commented 1 month ago

Quality Gate Passed Quality Gate passed for 'consensys_starknet-snap-wallet-ui'

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarCloud

sonarcloud[bot] commented 1 month ago

Quality Gate Passed Quality Gate passed for 'consensys_starknet-snap-starknet-snap'

Issues
4 New issues
0 Accepted issues

Measures
0 Security Hotspots
4.3% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarCloud