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

feat(misc): final preview4 changes #2290

Merged
merged 7 commits into from
Jan 20, 2021
Merged
Show file tree
Hide file tree
Changes from 6 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
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ export const exchangeABI: ABI = {
{
claim: false,
constant: false,
name: 'depositNEP5',
name: 'depositNEP17',
parameters: [
{
forwardedValue: false,
Expand Down Expand Up @@ -330,7 +330,7 @@ export const exchangeABI: ABI = {
{
claim: false,
constant: false,
name: 'withdrawNEP5',
name: 'withdrawNEP17',
parameters: [
{
forwardedValue: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export interface ExchangeSmartContract<TClient extends Client = Client> extends
options?: TransactionOptions & GetOptions,
) => Promise<InvokeReceipt<boolean, ExchangeEvent> & { readonly transaction: InvocationTransaction }>;
};
readonly depositNEP5: {
readonly depositNEP17: {
(from: AddressString, assetID: AddressString, amount: BigNumber, options?: TransactionOptions): Promise<
TransactionResult<InvokeReceipt<undefined, ExchangeEvent>, InvocationTransaction>
>;
Expand Down Expand Up @@ -171,7 +171,7 @@ export interface ExchangeSmartContract<TClient extends Client = Client> extends
options?: TransactionOptions & GetOptions,
) => Promise<InvokeReceipt<undefined, ExchangeEvent> & { readonly transaction: InvocationTransaction }>;
};
readonly withdrawNEP5: {
readonly withdrawNEP17: {
(from: AddressString, assetID: AddressString, amount: BigNumber, options?: TransactionOptions): Promise<
TransactionResult<InvokeReceipt<undefined, ExchangeEvent>, InvocationTransaction>
>;
Expand All @@ -198,7 +198,7 @@ export interface ExchangeMigrationSmartContract {
owner?: AddressString | Promise<AddressString>,
options?: TransactionOptions & GetOptions,
) => Promise<InvokeReceipt<boolean, ExchangeEvent> & { readonly transaction: InvocationTransaction }>;
readonly depositNEP5: (
readonly depositNEP17: (
from: AddressString | Promise<AddressString>,
assetID: AddressString | Promise<AddressString>,
amount: BigNumber | Promise<BigNumber>,
Expand Down Expand Up @@ -247,7 +247,7 @@ export interface ExchangeMigrationSmartContract {
feeAddress: AddressString | Promise<AddressString>,
options?: TransactionOptions & GetOptions,
) => Promise<InvokeReceipt<undefined, ExchangeEvent> & { readonly transaction: InvocationTransaction }>;
readonly withdrawNEP5: (
readonly withdrawNEP17: (
from: AddressString | Promise<AddressString>,
assetID: AddressString | Promise<AddressString>,
amount: BigNumber | Promise<BigNumber>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const notifyFilled = createEventNotifier<Address, Hash256, Fixed8, Address, Fixe
'amountToTake',
);

interface NEP5 {
interface NEP17 {
readonly transfer: (from: Address, to: Address, amount: Fixed8) => boolean;
}

Expand Down Expand Up @@ -81,22 +81,22 @@ export class Exchange extends SmartContract {
return this.offers.get(offerHash);
}

public depositNEP5(from: Address, assetID: Address, amount: Fixed8): void {
public depositNEP17(from: Address, assetID: Address, amount: Fixed8): void {
if (!Address.isCaller(from)) throw new Error('Caller was not the sender!');
if (amount < 1) throw new Error('Amount must be greater than 0!');

this.transferNEP5(from, this.address, assetID, amount);
this.transferNEP17(from, this.address, assetID, amount);
this.balances.set([from, assetID], this.balanceOf(from, assetID) + amount);
notifyDeposited(from, assetID, amount);
}

public withdrawNEP5(from: Address, assetID: Address, amount: Fixed8): void {
public withdrawNEP17(from: Address, assetID: Address, amount: Fixed8): void {
if (amount < 0) throw new Error(`Amount must be greater than 0: ${amount}`);
const balance = this.balanceOf(from, assetID);
if (balance < amount) throw new Error(`Not enough Balance to withdraw ${amount}!`);
if (!Address.isCaller(from)) throw new Error('Caller is not authorized to withdraw funds!');

this.transferNEP5(this.address, from, assetID, amount);
this.transferNEP17(this.address, from, assetID, amount);
this.balances.set([from, assetID], this.balanceOf(from, assetID) - amount);
notifyWithdrawn(from, assetID, amount);
}
Expand Down Expand Up @@ -309,9 +309,9 @@ export class Exchange extends SmartContract {
return crypto.hash256(offerBuffer);
}

private transferNEP5(from: Address, to: Address, assetID: Address, amount: Fixed8): void {
const nep5Asset = SmartContract.for<NEP5>(assetID);
if (!nep5Asset.transfer(from, to, amount)) {
private transferNEP17(from: Address, to: Address, assetID: Address, amount: Fixed8): void {
const nep17Asset = SmartContract.for<NEP17>(assetID);
if (!nep17Asset.transfer(from, to, amount)) {
throw new Error('Failed to transfer NEP-5 tokens!');
}
}
Expand Down
18 changes: 9 additions & 9 deletions packages/neo-one-cli/src/__e2e__/cmd/buildExchange.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const checkBalances = async ({
expect(tokensDeposited.toString()).toEqual(expected.tokensOnExchange);
};

const depositNEP5 = async ({
const depositNEP17 = async ({
token,
tokenAssetID,
exchange,
Expand Down Expand Up @@ -97,7 +97,7 @@ const depositNEP5 = async ({
expect(approveDepositReceipt.result.value).toEqual(true);

const [exchangeDepositReceipt] = await Promise.all([
exchange.depositNEP5.confirmed(from.address, tokenAssetID, amount, { from }),
exchange.depositNEP17.confirmed(from.address, tokenAssetID, amount, { from }),
developerClient.runConsensusNow(),
]);
expect(exchangeDepositReceipt.result.state).toEqual('HALT');
Expand All @@ -107,7 +107,7 @@ const depositNEP5 = async ({
await checkBalances({ token, tokenAssetID, from, exchange, exchangeAddress, expected });
};

const withdrawNEP5 = async ({
const withdrawNEP17 = async ({
token,
tokenAssetID,
exchange,
Expand All @@ -127,7 +127,7 @@ const withdrawNEP5 = async ({
readonly developerClient: DeveloperClient;
}) => {
const [exchangeWithdrawalReceipt] = await Promise.all([
exchange.withdrawNEP5.confirmed(from.address, tokenAssetID, amount, { from }),
exchange.withdrawNEP17.confirmed(from.address, tokenAssetID, amount, { from }),
developerClient.runConsensusNow(),
]);
expect(exchangeWithdrawalReceipt.result.state).toEqual('HALT');
Expand All @@ -137,7 +137,7 @@ const withdrawNEP5 = async ({
await checkBalances({ token, tokenAssetID, from, exchange, exchangeAddress, expected });
};

const verifyNEP5NEP5Exchange = async ({
const verifyNEP17NEP17Exchange = async ({
token,
tokenAssetID,
coin,
Expand All @@ -158,7 +158,7 @@ const verifyNEP5NEP5Exchange = async ({
readonly toAccountID: UserAccountID;
readonly developerClient: DeveloperClient;
}) => {
await depositNEP5({
await depositNEP17({
token,
tokenAssetID,
exchange,
Expand All @@ -169,7 +169,7 @@ const verifyNEP5NEP5Exchange = async ({
developerClient,
});

await withdrawNEP5({
await withdrawNEP17({
token,
tokenAssetID,
exchange,
Expand All @@ -187,7 +187,7 @@ const verifyNEP5NEP5Exchange = async ({
);
expect(coinTransferReceipt.result.value).toEqual(true);

await depositNEP5({
await depositNEP17({
token: coin,
tokenAssetID: coinAssetID,
exchange,
Expand Down Expand Up @@ -300,7 +300,7 @@ const verifyExchangeContractTesting = async (codegenPath: string) => {
const coinAssetID = coin.definition.networks[masterAccountID.network].address;
const exchangeAddress = exchange.definition.networks[masterAccountID.network].address;

await verifyNEP5NEP5Exchange({
await verifyNEP17NEP17Exchange({
token,
tokenAssetID,
coin,
Expand Down
8 changes: 6 additions & 2 deletions packages/neo-one-client-common/src/ScriptBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class ScriptBuilder extends BaseScriptBuilder {
super();

this.pushParamCallbacks = {
undefined: () => this.emitPush(Buffer.alloc(0, 0)),
undefined: () => this.emitOp('PUSHNULL'),
array: (param) => this.emitPushArray(param),
map: (param) => this.emitPushMap(param),
uInt160: (param) => this.emitPushUInt160(common.asUInt160(param)),
Expand Down Expand Up @@ -49,10 +49,14 @@ export class ScriptBuilder extends BaseScriptBuilder {
}

public emitPushArray(params: readonly ScriptBuilderParam[]): this {
if (params.length === 0) {
return this.emitOp('NEWARRAY0');
}

this.emitPushParams(...params);
this.emitPushParam(params.length);

return params.length !== 0 ? this.emitOp('PACK') : this.emitOp('NEWARRAY');
return this.emitOp('PACK');
}

// tslint:disable-next-line readonly-array
Expand Down
12 changes: 9 additions & 3 deletions packages/neo-one-client-common/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,15 +221,21 @@ const TEN_THOUSAND_FIXED8 = fixed8FromDecimal(10000);
const ONE_HUNDRED_MILLION_FIXED8 = fixed8FromDecimal(100000000);

const nativeScriptHashes = {
GAS: '0x668e0c1f9d7b70a99dd9e06eadd4c784d641afbc',
NEO: '0xde5f57d430d3dece511cf975a8d37848cb9e0525',
Policy: '0xce06595079cd69583126dbfd1d2e25cca74cffe9',
Management: '0xcd97b70d82d69adfcd9165374109419fade8d6ab',
NEO: '0x0a46e2e37c9987f570b4af253fb77e7eef0f72b6',
GAS: '0xa6a6c15dcdc9b997dac448b6926522d22efeedfb',
Policy: '0xdde31084c0fdbebc7f5ed5f53a38905305ccee14',
Oracle: '0xb1c37d5847c2ae36bdde31d0cc833a7ad9667f8f',
Designation: '0xc0073f4c7069bf38995780c9da065f9b3949ea7a',
};

const nativeHashes = {
Management: hexToUInt160(nativeScriptHashes.Management),
GAS: hexToUInt160(nativeScriptHashes.GAS),
NEO: hexToUInt160(nativeScriptHashes.NEO),
Policy: hexToUInt160(nativeScriptHashes.Policy),
Oracle: hexToUInt160(nativeScriptHashes.Oracle),
Designation: hexToUInt160(nativeScriptHashes.Designation),
};

export const common = {
Expand Down
10 changes: 10 additions & 0 deletions packages/neo-one-client-common/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,15 @@ const createPrivateKey = (): PrivateKey => common.bufferToPrivateKey(randomBytes

const toScriptHash = hash160;

const getContractHash = (sender: UInt160, script: Buffer) => {
const builder = new ScriptBuilder();
builder.emitOp('ABORT');
builder.emitPushUInt160(sender);
builder.emitPush(script);

return toScriptHash(builder.build());
};

// Takes various formats and converts to standard ECPoint
const toECPoint = (publicKey: Buffer): ECPoint => toECPointFromKeyPair(ec().keyFromPublic(publicKey));

Expand Down Expand Up @@ -891,6 +900,7 @@ export const crypto = {
verify,
privateKeyToPublicKey,
toScriptHash,
getContractHash,
toECPoint,
createKeyPair,
scriptHashToAddress,
Expand Down
7 changes: 6 additions & 1 deletion packages/neo-one-client-common/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,12 @@ export const InvalidAttributeTypeJSONError = makeErrorWithCode(
);
export const InvalidAttributeTypeError = makeErrorWithCode(
'INVALID_ATTRIBUTE_TYPE',
(transactionAttributeType: number) => `Expected transaction type, found: ${transactionAttributeType.toString(16)}`,
(transactionAttributeType: number) =>
`Expected transaction attribute type, found: ${transactionAttributeType.toString(16)}`,
);
export const InvalidOracleResponseCodeError = makeErrorWithCode(
'INVALID_ORACLE_RESPONSE_CODE',
(value: number) => `Expected oracle response code, found: ${value.toString()}`,
);
export const InvalidAttributeUsageError = makeErrorWithCode(
'INVALID_ATTRIBUTE_USAGE',
Expand Down
2 changes: 1 addition & 1 deletion packages/neo-one-client-common/src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export * from './StorageFlagsModel';
export * from './WitnessModel';
export * from './WitnessScopeModel';
export * from './transaction';
export * from './nep5';
export * from './nep17';
export * from './types';
export * from './vm';
export * from './trigger';
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import { BinaryWriter } from '../../BinaryWriter';
import { UInt160 } from '../../common';
import { createSerializeWire, SerializableWire, SerializeWire } from '../Serializable';

export interface Nep5BalanceKeyModelAdd {
export interface Nep17BalanceKeyModelAdd {
readonly userScriptHash: UInt160;
readonly assetScriptHash: UInt160;
}

export class Nep5BalanceKeyModel implements SerializableWire {
export class Nep17BalanceKeyModel implements SerializableWire {
public readonly userScriptHash: UInt160;
public readonly assetScriptHash: UInt160;
public readonly serializeWire: SerializeWire = createSerializeWire(this.serializeWireBase.bind(this));

public constructor({ userScriptHash, assetScriptHash }: Nep5BalanceKeyModelAdd) {
public constructor({ userScriptHash, assetScriptHash }: Nep17BalanceKeyModelAdd) {
this.userScriptHash = userScriptHash;
this.assetScriptHash = assetScriptHash;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { BinaryWriter } from '../../BinaryWriter';
import { createSerializeWire, SerializableWire, SerializeWire } from '../Serializable';

export interface Nep5BalanceModelAdd {
export interface Nep17BalanceModelAdd {
readonly balanceBuffer: Buffer;
readonly lastUpdatedBlock: number;
}

export class Nep5BalanceModel implements SerializableWire {
export class Nep17BalanceModel implements SerializableWire {
public readonly balanceInternal: Buffer;
public readonly lastUpdatedBlock: number;
public readonly serializeWire: SerializeWire = createSerializeWire(this.serializeWireBase.bind(this));

public constructor({ balanceBuffer, lastUpdatedBlock }: Nep5BalanceModelAdd) {
public constructor({ balanceBuffer, lastUpdatedBlock }: Nep17BalanceModelAdd) {
this.balanceInternal = balanceBuffer;
this.lastUpdatedBlock = lastUpdatedBlock;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { BinaryWriter } from '../../BinaryWriter';
import { UInt160 } from '../../common';
import { createSerializeWire, SerializableWire, SerializeWire } from '../Serializable';

export interface Nep5TransferKeyModelAdd {
export interface Nep17TransferKeyModelAdd {
readonly userScriptHash: UInt160;
readonly timestampMS: BN;
readonly assetScriptHash: UInt160;
readonly blockTransferNotificationIndex: number;
}

export class Nep5TransferKeyModel implements SerializableWire {
export class Nep17TransferKeyModel implements SerializableWire {
public readonly userScriptHash: UInt160;
public readonly timestampMS: BN;
public readonly assetScriptHash: UInt160;
Expand All @@ -22,7 +22,7 @@ export class Nep5TransferKeyModel implements SerializableWire {
timestampMS,
assetScriptHash,
blockTransferNotificationIndex,
}: Nep5TransferKeyModelAdd) {
}: Nep17TransferKeyModelAdd) {
this.userScriptHash = userScriptHash;
this.timestampMS = timestampMS;
this.assetScriptHash = assetScriptHash;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ import { BinaryWriter } from '../../BinaryWriter';
import { UInt160, UInt256 } from '../../common';
import { createSerializeWire, SerializableWire, SerializeWire } from '../Serializable';

export interface Nep5TransferModelAdd {
export interface Nep17TransferModelAdd {
readonly userScriptHash: UInt160;
readonly blockIndex: number;
readonly txHash: UInt256;
readonly amountBuffer: Buffer;
}

export class Nep5TransferModel implements SerializableWire {
export class Nep17TransferModel implements SerializableWire {
public readonly userScriptHash: UInt160;
public readonly blockIndex: number;
public readonly txHash: UInt256;
public readonly amountInternal: Buffer;
public readonly serializeWire: SerializeWire = createSerializeWire(this.serializeWireBase.bind(this));

public constructor({ userScriptHash, blockIndex, txHash, amountBuffer }: Nep5TransferModelAdd) {
public constructor({ userScriptHash, blockIndex, txHash, amountBuffer }: Nep17TransferModelAdd) {
this.userScriptHash = userScriptHash;
this.blockIndex = blockIndex;
this.txHash = txHash;
Expand Down
4 changes: 4 additions & 0 deletions packages/neo-one-client-common/src/models/nep17/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './Nep17BalanceModel';
export * from './Nep17TransferModel';
export * from './Nep17TransferKeyModel';
export * from './Nep17BalanceKeyModel';
4 changes: 0 additions & 4 deletions packages/neo-one-client-common/src/models/nep5/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ export class TransactionModel<
this.networkFee = networkFee;
}

public getAttributes<T extends TAttribute>(isAttr: (attr: TAttribute) => attr is T): readonly T[] {
return this.attributes.filter(isAttr);
}

public getAttribute<T extends TAttribute>(isAttr: (attr: TAttribute) => attr is T): T | undefined {
return this.getAttributes(isAttr)[0];
}

public getScriptHashesForVerifying(): readonly UInt160[] {
return this.signers.map((signer) => signer.account);
}
Expand Down
Loading