Skip to content
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

solution: subscribe, show and edit erc20 allowances #1303

Merged
merged 2 commits into from
Aug 1, 2023
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"packages/*"
],
"resolutions": {
"@emeraldpay/api": "https://artifacts.emerald.cash/builds/emerald-api-js/2c423635/emeraldpay-api-v0.4.0-dev.tgz",
"@emeraldpay/api-node": "https://artifacts.emerald.cash/builds/emerald-api-js/2c423635/emeraldpay-api-node-v0.4.0-dev.tgz"
"@emeraldpay/api": "https://artifacts.emerald.cash/builds/emerald-api-js/ebb1aeb6/emeraldpay-api-v0.4.0-dev.tgz",
"@emeraldpay/api-node": "https://artifacts.emerald.cash/builds/emerald-api-js/ebb1aeb6/emeraldpay-api-node-v0.4.0-dev.tgz"
}
}
4 changes: 4 additions & 0 deletions packages/core/src/IpcCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export enum IpcCommands {
/** @deprecated */
BROADCAST_TX = 'broadcast-tx',

// Allowance service
ALLOWANCE_SET_TOKENS = 'allowance-set-tokens',
ALLOWANCE_SUBSCRIBE_ADDRESS = 'allowance-subscribe-address',

// Balance service
BALANCE_SET_TOKENS = 'balance-set-tokens',
BALANCE_SUBSCRIBE = 'balance-subscribe',
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/blockchains/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export { EthereumMessage, isStructuredMessage } from './ethereum';
export {
INFINITE_ALLOWANCE,
MAX_DISPLAY_ALLOWANCE,
InputDataDecoder,
Token,
TokenAmount,
Expand All @@ -8,6 +10,7 @@ export {
TokenRegistry,
decodeData,
isToken,
isWrappedToken,
tokenAbi,
wrapTokenAbi,
} from './tokens';
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/blockchains/tokens/allowance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import BigNumber from 'bignumber.js';

/**
* Highest possible value for allowance, calculated as 2^256-1
*/
export const INFINITE_ALLOWANCE = new BigNumber('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
/**
* Max display value before showing infinite symbol, calculated as 2^128
*/
export const MAX_DISPLAY_ALLOWANCE = new BigNumber('0x100000000000000000000000000000000');
3 changes: 2 additions & 1 deletion packages/core/src/blockchains/tokens/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { tokenAbi, wrapTokenAbi } from './abi';
export { INFINITE_ALLOWANCE, MAX_DISPLAY_ALLOWANCE } from './allowance';
export { InputDataDecoder, decodeData } from './decoder';
export { Token, TokenAmount, TokenData, TokenInstances, TokenRegistry, isToken } from './registry';
export { Token, TokenAmount, TokenData, TokenInstances, TokenRegistry, isToken, isWrappedToken } from './registry';
51 changes: 46 additions & 5 deletions packages/core/src/blockchains/tokens/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { BlockchainCode, blockchainIdToCode } from '../blockchains';

const TOKEN_TYPES = ['ERC20', 'ERC721', 'ERC1155'] as const;

const WRAPPED_TOKENS: Readonly<Partial<Record<BlockchainCode, string>>> = {
[BlockchainCode.ETH]: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
[BlockchainCode.ETC]: '0x1953cab0E5bFa6D4a9BaD6E05fD46C1CC6527a5a',
[BlockchainCode.Goerli]: '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6',
};

export interface TokenData {
address: string;
blockchain: number;
Expand All @@ -14,7 +20,6 @@ export interface TokenData {
stablecoin?: boolean;
symbol: string;
type: (typeof TOKEN_TYPES)[number];
wrapped?: boolean;
}

export function isToken(value: unknown): value is TokenData {
Expand All @@ -26,6 +31,10 @@ export function isToken(value: unknown): value is TokenData {
);
}

export function isWrappedToken(token: TokenData): boolean {
return token.address.toLowerCase() === WRAPPED_TOKENS[blockchainIdToCode(token.blockchain)]?.toLowerCase();
}

export class TokenAmount extends BigAmount {
readonly token: TokenData;

Expand All @@ -39,15 +48,42 @@ export class TokenAmount extends BigAmount {
return BigAmount.is(value) && 'token' in value && value.token != null && typeof value.token === 'object';
}

protected convert(amount: this): this {
return new TokenAmount(amount, this.units, this.token) as this;
}

protected copyWith(value: BigNumber): this {
return this.convert(super.copyWith(value));
}

plus(amount: this): this {
return new TokenAmount(super.plus(amount), amount.units, this.token) as this;
return this.convert(super.plus(amount));
}

minus(amount: this): this {
return this.convert(super.minus(amount));
}

multiply(amount: number | BigNumber): this {
return this.convert(super.multiply(amount));
}

divide(amount: number | BigNumber): this {
return this.convert(super.divide(amount));
}

max(amount: this): this {
return this.convert(super.max(amount));
}

min(amount: this): this {
return this.convert(super.min(amount));
}
}

export class Token implements TokenData {
private readonly _pinned?: boolean;
private readonly _stablecoin?: boolean;
private readonly _wrapped?: boolean;

readonly address: string;
readonly blockchain: number;
Expand All @@ -60,7 +96,6 @@ export class Token implements TokenData {
constructor(token: TokenData) {
this._pinned = token.pinned;
this._stablecoin = token.stablecoin;
this._wrapped = token.wrapped;

this.blockchain = token.blockchain;
this.decimals = token.decimals;
Expand All @@ -81,7 +116,7 @@ export class Token implements TokenData {
}

get wrapped(): boolean {
return this._wrapped ?? false;
return isWrappedToken(this);
}

getUnits(): Units {
Expand Down Expand Up @@ -169,6 +204,12 @@ export class TokenRegistry {
return instances.has(address.toLowerCase());
}

hasAnyToken(blockchain: BlockchainCode): boolean {
const instances = this.instances.get(blockchain);

return (instances?.size ?? 0) > 0;
}

getStablecoins(blockchain: BlockchainCode): Token[] {
const instances = this.instances.get(blockchain);

Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import * as workflow from './workflow';
export { blockchains, config, workflow, utils };

export {
INFINITE_ALLOWANCE,
MAX_DISPLAY_ALLOWANCE,
Blockchains,
BlockchainCode,
Coin,
Expand Down
179 changes: 179 additions & 0 deletions packages/core/src/workflow/create-tx/CreateErc20ApproveTx.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { Wei } from '@emeraldpay/bigamount-crypto';
import { BlockchainCode, INFINITE_ALLOWANCE, TokenData, TokenRegistry } from '../../blockchains';
import { DEFAULT_GAS_LIMIT_ERC20, EthereumTransactionType } from '../../transaction/ethereum';
import { ApproveTarget, CreateErc20ApproveTx } from './CreateErc20ApproveTx';
import { ValidationResult } from './types';

describe('CreateErc20ApproveTx', () => {
const wethTokenData: TokenData = {
name: 'Wrapped Ether',
blockchain: 10005,
address: '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6',
symbol: 'WETG',
decimals: 18,
type: 'ERC20',
};
const weenusTokenData: TokenData = {
name: 'Weenus',
blockchain: 10005,
address: '0xaFF4481D10270F50f203E0763e2597776068CBc5',
symbol: 'WEENUS',
decimals: 18,
type: 'ERC20',
stablecoin: true,
};

const tokenRegistry = new TokenRegistry([wethTokenData, weenusTokenData]);

const wethToken = tokenRegistry.byAddress(BlockchainCode.Goerli, '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6');
const weenusToken = tokenRegistry.byAddress(BlockchainCode.Goerli, '0xaFF4481D10270F50f203E0763e2597776068CBc5');

test('should create legacy approve tx', () => {
const tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(0),
type: EthereumTransactionType.LEGACY,
});

expect(tx.amount.number.toNumber()).toEqual(0);
expect(tx.gas).toBe(DEFAULT_GAS_LIMIT_ERC20);
expect(tx.gasPrice?.number.toNumber()).toEqual(0);
expect(tx.totalBalance.number.toNumber()).toEqual(0);
});

test('should create eip1559 approve tx', () => {
const tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(0),
type: EthereumTransactionType.EIP1559,
});

expect(tx.amount.number.toNumber()).toEqual(0);
expect(tx.gas).toEqual(DEFAULT_GAS_LIMIT_ERC20);
expect(tx.maxGasPrice?.number.toNumber()).toEqual(0);
expect(tx.priorityGasPrice?.number.toNumber()).toEqual(0);
expect(tx.totalBalance.number.toNumber()).toEqual(0);
});

test('should set target', () => {
let tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
target: ApproveTarget.MANUAL,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(1),
type: EthereumTransactionType.EIP1559,
});

expect(tx.amount.equals(wethToken.getAmount(0))).toBeTruthy();

const amount = wethToken.getAmount(3);

tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
target: ApproveTarget.MAX_AVAILABLE,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: amount,
type: EthereumTransactionType.EIP1559,
});

expect(tx.amount.equals(amount)).toBeTruthy();

tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
target: ApproveTarget.INFINITE,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(0),
type: EthereumTransactionType.EIP1559,
});

expect(tx.amount.number.eq(INFINITE_ALLOWANCE)).toBeTruthy();
});

test('should change amount and target', () => {
const amount = wethToken.getAmount(1);

const tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: amount,
type: EthereumTransactionType.EIP1559,
});

expect(tx.target).toEqual(ApproveTarget.MANUAL);

tx.target = ApproveTarget.MAX_AVAILABLE;

expect(tx.amount.equals(amount)).toBeTruthy();

tx.target = ApproveTarget.INFINITE;

expect(tx.amount.number.eq(INFINITE_ALLOWANCE)).toBeTruthy();

tx.amount = amount;

expect(tx.target).toEqual(ApproveTarget.MANUAL);
});

test('should change token', () => {
const amount = wethToken.getAmount(1);

const tx = new CreateErc20ApproveTx({
amount,
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: amount,
type: EthereumTransactionType.EIP1559,
});

const weenusAmount = weenusToken.getAmount(1);

tx.setToken(weenusToken, new Wei(0), weenusAmount, true);

expect(tx.token.symbol).toEqual(weenusToken.symbol);
expect(tx.amount.number.eq(weenusAmount.number)).toBeTruthy();
expect(tx.totalTokenBalance.equals(weenusAmount)).toBeTruthy();
});

test('should validate tx', () => {
const tx = new CreateErc20ApproveTx({
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(0),
type: EthereumTransactionType.EIP1559,
});

expect(tx.validate()).toEqual(ValidationResult.NO_FROM);

tx.approveBy = '0xe62c6f33a58d7f49e6b782aab931450e53d01f12';

expect(tx.validate()).toEqual(ValidationResult.NO_TO);

tx.allowFor = '0x3f54eb67fea225d0a21263f1a7cb456e342cb1e8';

expect(tx.validate()).toEqual(ValidationResult.OK);
});

test('should build tx', () => {
const tx = new CreateErc20ApproveTx({
approveBy: '0xe62c6f33a58d7f49e6b782aab931450e53d01f12',
allowFor: '0x3f54eb67fea225d0a21263f1a7cb456e342cb1e8',
blockchain: BlockchainCode.Goerli,
token: wethTokenData,
totalBalance: new Wei(0),
totalTokenBalance: wethToken.getAmount(0),
type: EthereumTransactionType.EIP1559,
});

expect(tx.build().data.length).toBeGreaterThan(2);
});
});
Loading
Loading