Skip to content

Commit

Permalink
CancelDelegation Fix (#356)
Browse files Browse the repository at this point in the history
* Updated "cancelDelegations = &wc|to?". Removed Delegation CONTRACT_ADDRESS in signature

* Update comments/variable names
  • Loading branch information
acedward authored Apr 29, 2024
1 parent df30db4 commit c0e242c
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 28 deletions.
48 changes: 30 additions & 18 deletions packages/engine/paima-sm/src/delegate-wallet.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import Web3 from 'web3';
import type { PoolClient } from 'pg';

import { PaimaParser } from '@paima/concise';
import { ENV, doLog } from '@paima/utils';
import type { IVerify } from '@paima/crypto';
import { CryptoManager } from '@paima/crypto';
import type { IGetAddressFromAddressResult } from '@paima/db';
import {
addressCache,
deleteDelegationTo,
deleteDelegationsFrom,
enableManualCache,
getAddressFromAddress,
getDelegation,
Expand All @@ -32,7 +31,7 @@ type ParsedDelegateWalletCommand =
command: 'migrate';
args: { from: string; to: string; from_signature: string; to_signature: string };
}
| { command: 'cancelDelegations'; args: { to_signature: string } };
| { command: 'cancelDelegations'; args: { to: string } };

// Delegate Wallet manages cache cleanup.
enableManualCache();
Expand All @@ -47,7 +46,7 @@ export class DelegateWallet {
private static readonly delegationGrammar = `
delegate = &wd|from?|to?|from_signature|to_signature
migrate = &wm|from?|to?|from_signature|to_signature
cancelDelegations = &wc|to_signature
cancelDelegations = &wc|to?
`;

private static readonly parserCommands = {
Expand All @@ -64,7 +63,7 @@ export class DelegateWallet {
to_signature: PaimaParser.NCharsParser(0, 1024),
},
cancelDelegations: {
to_signature: PaimaParser.NCharsParser(0, 1024),
to: PaimaParser.OptionalParser('', PaimaParser.WalletAddress()),
},
};

Expand All @@ -77,9 +76,7 @@ export class DelegateWallet {

/* Generate Plaintext Message */
private generateMessage(internalMessage: string = ''): string {
return `${DelegateWallet.DELEGATE_WALLET_PREFIX}${
DelegateWallet.SEP
}${internalMessage.toLocaleLowerCase()}${DelegateWallet.SEP}${ENV.CONTRACT_ADDRESS}`;
return `${DelegateWallet.DELEGATE_WALLET_PREFIX}${DelegateWallet.SEP}${internalMessage.toLocaleLowerCase()}`;
}

private validateSender(to: string, from: string, realAddress: string): void {
Expand Down Expand Up @@ -255,11 +252,26 @@ export class DelegateWallet {
}

// Cancel Delegations.
// Delete all delegations from where TO=to
private async cmdCancelDelegations(to: string): Promise<void> {
const [toAddress] = await getAddressFromAddress.run({ address: to }, this.DBConn);
if (!toAddress) throw new Error('Invalid Address');
await deleteDelegationTo.run({ to_id: toAddress.id }, this.DBConn);
// if "to" is provided, delete delegations for "from" -> "to"
// if "to" is not provided, delete all delegations for "from" -> *
private async cmdCancelDelegations(from: string, to: string): Promise<void> {
const [fromAddress] = await getAddressFromAddress.run({ address: from }, this.DBConn);
if (!fromAddress) throw new Error('Invalid Address');

if (to) {
const [toAddress] = await getAddressFromAddress.run({ address: to }, this.DBConn);
if (!toAddress) throw new Error('Invalid Address');

await deleteDelegationTo.run(
{
to_id: toAddress.id,
from_id: fromAddress.id,
},
this.DBConn
);
} else {
await deleteDelegationsFrom.run({ from_id: fromAddress.id }, this.DBConn);
}

addressCache.clear();
}
Expand Down Expand Up @@ -313,11 +325,11 @@ export class DelegateWallet {
return true;
}
case 'cancelDelegations': {
const to = realAddress;
const { to_signature } = parsed.args;
await this.verifySignature(to, this.generateMessage(), to_signature);
await this.cmdCancelDelegations(to.toLocaleLowerCase());
doLog(`Cancel Delegate 'to' ${to.substring(0, 8)}...`);
const { to } = parsed.args;
await this.cmdCancelDelegations(userAddress.toLocaleLowerCase(), to.toLocaleLowerCase());
doLog(
`Cancel Delegate ${userAddress.substring(0, 8)}... -> ${to ? to.substring(0, 8) + '...' : '*'}`
);
return true;
}
default:
Expand Down
2 changes: 1 addition & 1 deletion packages/engine/paima-sm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ async function processUserInputs(
//
// delegate = &wd|from?|to?|from_signature|to_signature
// migrate = &wm|from?|to?|from_signature|to_signature
// cancelDelegate = &wc|to_signature
// cancelDelegate = &wc|to?
const delegateWallet = new DelegateWallet(DBConn);
if (inputData.inputData.startsWith(DelegateWallet.INTERNAL_COMMAND_PREFIX)) {
const status = await delegateWallet.process(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ export const deleteDelegationsFrom = new PreparedQuery<IDeleteDelegationsFromPar

/** 'DeleteDelegationTo' parameters type */
export interface IDeleteDelegationToParams {
from_id: number;
to_id: number;
}

Expand All @@ -332,13 +333,14 @@ export interface IDeleteDelegationToQuery {
result: IDeleteDelegationToResult;
}

const deleteDelegationToIR: any = {"usedParamSet":{"to_id":true},"params":[{"name":"to_id","required":true,"transform":{"type":"scalar"},"locs":[{"a":38,"b":44}]}],"statement":"DELETE FROM delegations\nWHERE to_id = :to_id!"};
const deleteDelegationToIR: any = {"usedParamSet":{"to_id":true,"from_id":true},"params":[{"name":"to_id","required":true,"transform":{"type":"scalar"},"locs":[{"a":38,"b":44}]},{"name":"from_id","required":true,"transform":{"type":"scalar"},"locs":[{"a":60,"b":68}]}],"statement":"DELETE FROM delegations\nWHERE to_id = :to_id!\nand from_id = :from_id!"};

/**
* Query generated from SQL:
* ```
* DELETE FROM delegations
* WHERE to_id = :to_id!
* and from_id = :from_id!
* ```
*/
export const deleteDelegationTo = new PreparedQuery<IDeleteDelegationToParams,IDeleteDelegationToResult>(deleteDelegationToIR);
Expand Down
3 changes: 2 additions & 1 deletion packages/node-sdk/paima-db/src/sql/wallet-delegation.sql
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ WHERE from_id = :from_id!;

/* @name deleteDelegationTo */
DELETE FROM delegations
WHERE to_id = :to_id!;
WHERE to_id = :to_id!
and from_id = :from_id!;

/* @name deleteAddress */
DELETE FROM addresses
Expand Down
12 changes: 5 additions & 7 deletions packages/paima-sdk/paima-mw-core/src/delegate-wallet/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* delegate = &wd|from?|to?|from_signature|to_signature
* migrate = &wm|from?|to?|from_signature|to_signature
* cancelDelegations = &wc|to_signature
* cancelDelegations = &wc|to?
*/

import { builder } from '@paima/concise';
Expand Down Expand Up @@ -78,14 +78,14 @@ export async function walletConnectMigrate(
}

export async function walletConnectCancelDelegations(
to_signature: string
to: string | null
): Promise<SuccessfulResult<PostDataResponse> | FailedResult> {
const errorFxn = buildEndpointErrorFxn('delegate-wallet-cancel');

// walletConnect = &wc|to_signature
// walletConnect = &wc|to?
const conciseBuilder = builder.initialize();
conciseBuilder.setPrefix('&wc');
conciseBuilder.addValue({ value: to_signature });
conciseBuilder.addValue({ value: to ?? '' });
try {
const result = await postConciseData(conciseBuilder.build(), errorFxn);
if (!result.success) {
Expand All @@ -104,9 +104,7 @@ export class WalletConnectHelper {
private static readonly SEP = ':';

public buildMessageToSign(subMessage: string): string {
return `${WalletConnectHelper.DELEGATE_WALLET_PREFIX}${
WalletConnectHelper.SEP
}${subMessage.toLocaleLowerCase()}${WalletConnectHelper.SEP}${ENV.CONTRACT_ADDRESS}`;
return `${WalletConnectHelper.DELEGATE_WALLET_PREFIX}${WalletConnectHelper.SEP}${subMessage.toLocaleLowerCase()}`;
}

private getProvider(walletType: AddressType): IProvider<unknown> {
Expand Down

0 comments on commit c0e242c

Please sign in to comment.