Organize code (prettier)

This commit is contained in:
Nicola Benaglia 2025-05-16 23:54:59 +02:00
parent 55f8ea9843
commit b0274b4cb7
44 changed files with 3020 additions and 2795 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,175 +1,186 @@
// Qortal TX types // Qortal TX types
const TX_TYPES = { const TX_TYPES = {
1: "Genesis", 1: 'Genesis',
2: "Payment", 2: 'Payment',
3: "Name registration", 3: 'Name registration',
4: "Name update", 4: 'Name update',
5: "Sell name", 5: 'Sell name',
6: "Cancel sell name", 6: 'Cancel sell name',
7: "Buy name", 7: 'Buy name',
8: "Create poll", 8: 'Create poll',
9: "Vote in poll", 9: 'Vote in poll',
10: "Arbitrary", 10: 'Arbitrary',
11: "Issue asset", 11: 'Issue asset',
12: "Transfer asset", 12: 'Transfer asset',
13: "Create asset order", 13: 'Create asset order',
14: "Cancel asset order", 14: 'Cancel asset order',
15: "Multi-payment transaction", 15: 'Multi-payment transaction',
16: "Deploy AT", 16: 'Deploy AT',
17: "Message", 17: 'Message',
18: "Chat", 18: 'Chat',
19: "Publicize", 19: 'Publicize',
20: "Airdrop", 20: 'Airdrop',
21: "AT", 21: 'AT',
22: "Create group", 22: 'Create group',
23: "Update group", 23: 'Update group',
24: "Add group admin", 24: 'Add group admin',
25: "Remove group admin", 25: 'Remove group admin',
26: "Group ban", 26: 'Group ban',
27: "Cancel group ban", 27: 'Cancel group ban',
28: "Group kick", 28: 'Group kick',
29: "Group invite", 29: 'Group invite',
30: "Cancel group invite", 30: 'Cancel group invite',
31: "Join group", 31: 'Join group',
32: "Leave group", 32: 'Leave group',
33: "Group approval", 33: 'Group approval',
34: "Set group", 34: 'Set group',
35: "Update asset", 35: 'Update asset',
36: "Account flags", 36: 'Account flags',
37: "Enable forging", 37: 'Enable forging',
38: "Reward share", 38: 'Reward share',
39: "Account level", 39: 'Account level',
40: "Transfer privs", 40: 'Transfer privs',
41: "Presence" 41: 'Presence',
} };
// Qortal error codes // Qortal error codes
const ERROR_CODES = { const ERROR_CODES = {
1: "Valid OK", 1: 'Valid OK',
2: "Invalid address", 2: 'Invalid address',
3: "Negative amount", 3: 'Negative amount',
4: "Nagative fee", 4: 'Nagative fee',
5: "No balance", 5: 'No balance',
6: "Invalid reference", 6: 'Invalid reference',
7: "Invalid time length", 7: 'Invalid time length',
8: "Invalid value length", 8: 'Invalid value length',
9: "Name already registered", 9: 'Name already registered',
10: "Name does not exist", 10: 'Name does not exist',
11: "Invalid name owner", 11: 'Invalid name owner',
12: "Name already for sale", 12: 'Name already for sale',
13: "Name not for sale", 13: 'Name not for sale',
14: "Name buyer already owner", 14: 'Name buyer already owner',
15: "Invalid amount", 15: 'Invalid amount',
16: "Invalid seller", 16: 'Invalid seller',
17: "Name not lowercase", 17: 'Name not lowercase',
18: "Invalid description length", 18: 'Invalid description length',
19: "Invalid options length", 19: 'Invalid options length',
20: "Invalid option length", 20: 'Invalid option length',
21: "Duplicate option", 21: 'Duplicate option',
22: "Poll already created", 22: 'Poll already created',
23: "Poll already has votes", 23: 'Poll already has votes',
24: "Poll does not exist", 24: 'Poll does not exist',
25: "Option does not exist", 25: 'Option does not exist',
26: "Already voted for that option", 26: 'Already voted for that option',
27: "Invalid data length", 27: 'Invalid data length',
28: "Invalid quantity", 28: 'Invalid quantity',
29: "Asset does not exist", 29: 'Asset does not exist',
30: "Invalid return", 30: 'Invalid return',
31: "Have equals want", 31: 'Have equals want',
32: "Order does not exist", 32: 'Order does not exist',
33: "Invalid order creator", 33: 'Invalid order creator',
34: "Invalid payments length", 34: 'Invalid payments length',
35: "Negative price", 35: 'Negative price',
36: "Invalid creation bytes", 36: 'Invalid creation bytes',
37: "Invalid tags length", 37: 'Invalid tags length',
38: "Invalid type length", 38: 'Invalid type length',
39: "Invalid AT transaction", 39: 'Invalid AT transaction',
40: "Insufficient fee", 40: 'Insufficient fee',
41: "Asset does not match AT", 41: 'Asset does not match AT',
43: "Asset already exists", 43: 'Asset already exists',
44: "Missing creator", 44: 'Missing creator',
45: "Timestamp too old", 45: 'Timestamp too old',
46: "Timestamp too new", 46: 'Timestamp too new',
47: "Too many unconfirmed", 47: 'Too many unconfirmed',
48: "Group already exists", 48: 'Group already exists',
49: "Group does not exist", 49: 'Group does not exist',
50: "Invalid group owner", 50: 'Invalid group owner',
51: "Already group memeber", 51: 'Already group memeber',
52: "Group owner can not leave", 52: 'Group owner can not leave',
53: "Not group member", 53: 'Not group member',
54: "Already group admin", 54: 'Already group admin',
55: "Not group admin", 55: 'Not group admin',
56: "Invalid lifetime", 56: 'Invalid lifetime',
57: "Invite unknown", 57: 'Invite unknown',
58: "Ban exists", 58: 'Ban exists',
59: "Ban unknown", 59: 'Ban unknown',
60: "Banned from group", 60: 'Banned from group',
61: "Join request", 61: 'Join request',
62: "Invalid group approval threshold", 62: 'Invalid group approval threshold',
63: "Group ID mismatch", 63: 'Group ID mismatch',
64: "Invalid group ID", 64: 'Invalid group ID',
65: "Transaction unknown", 65: 'Transaction unknown',
66: "Transaction already confirmed", 66: 'Transaction already confirmed',
67: "Invalid TX group", 67: 'Invalid TX group',
68: "TX group ID mismatch", 68: 'TX group ID mismatch',
69: "Multiple names forbidden", 69: 'Multiple names forbidden',
70: "Invalid asset owner", 70: 'Invalid asset owner',
71: "AT is finished", 71: 'AT is finished',
72: "No flag permission", 72: 'No flag permission',
73: "Not minting accout", 73: 'Not minting accout',
77: "Invalid rewardshare percent", 77: 'Invalid rewardshare percent',
78: "Public key unknown", 78: 'Public key unknown',
79: "Invalid public key", 79: 'Invalid public key',
80: "AT unknown", 80: 'AT unknown',
81: "AT already exists", 81: 'AT already exists',
82: "Group approval not required", 82: 'Group approval not required',
83: "Group approval decided", 83: 'Group approval decided',
84: "Maximum reward shares", 84: 'Maximum reward shares',
85: "Transaction already exists", 85: 'Transaction already exists',
86: "No blockchain lock", 86: 'No blockchain lock',
87: "Order already closed", 87: 'Order already closed',
88: "Clock not synced", 88: 'Clock not synced',
89: "Asset not spendable", 89: 'Asset not spendable',
90: "Account can not reward share", 90: 'Account can not reward share',
91: "Self share exists", 91: 'Self share exists',
92: "Account already exists", 92: 'Account already exists',
93: "Invalid group block delay", 93: 'Invalid group block delay',
94: "Incorrect nonce", 94: 'Incorrect nonce',
95: "Ivalid timestamp signature", 95: 'Ivalid timestamp signature',
96: "Address blocked", 96: 'Address blocked',
97: "Name Blocked", 97: 'Name Blocked',
98: "Group approval required", 98: 'Group approval required',
99: "Account not transferable", 99: 'Account not transferable',
999: "Ivalid but ok", 999: 'Ivalid but ok',
1000: "Not yet released." 1000: 'Not yet released.',
} };
// Qortal 8 decimals // Qortal 8 decimals
const QORT_DECIMALS = 1e8 const QORT_DECIMALS = 1e8;
// Q for Qortal // Q for Qortal
const ADDRESS_VERSION = 58 const ADDRESS_VERSION = 58;
// Proxy for api calls // Proxy for api calls
const PROXY_URL = "/proxy/" const PROXY_URL = '/proxy/';
// Chat reference timestamp // Chat reference timestamp
const CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP = 1674316800000 const CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP = 1674316800000;
// Dynamic fee timestamp // Dynamic fee timestamp
const DYNAMIC_FEE_TIMESTAMP = 1692118800000 const DYNAMIC_FEE_TIMESTAMP = 1692118800000;
// Used as a salt for all Qora addresses. Salts used for storing your private keys in local storage will be randomly generated // Used as a salt for all Qora addresses. Salts used for storing your private keys in local storage will be randomly generated
const STATIC_SALT = new Uint8Array([54, 190, 201, 206, 65, 29, 123, 129, 147, 231, 180, 166, 171, 45, 95, 165, 78, 200, 208, 194, 44, 207, 221, 146, 45, 238, 68, 68, 69, 102, 62, 6]) const STATIC_SALT = new Uint8Array([
const BCRYPT_ROUNDS = 10 // Remember that the total work spent on key derivation is BCRYPT_ROUNDS * KDF_THREADS 54, 190, 201, 206, 65, 29, 123, 129, 147, 231, 180, 166, 171, 45, 95, 165, 78,
const BCRYPT_VERSION = "2a" 200, 208, 194, 44, 207, 221, 146, 45, 238, 68, 68, 69, 102, 62, 6,
const STATIC_BCRYPT_SALT = `$${BCRYPT_VERSION}$${BCRYPT_ROUNDS}$IxVE941tXVUD4cW0TNVm.O` ]);
const KDF_THREADS = 16 const BCRYPT_ROUNDS = 10; // Remember that the total work spent on key derivation is BCRYPT_ROUNDS * KDF_THREADS
const BCRYPT_VERSION = '2a';
const STATIC_BCRYPT_SALT = `$${BCRYPT_VERSION}$${BCRYPT_ROUNDS}$IxVE941tXVUD4cW0TNVm.O`;
const KDF_THREADS = 16;
export { TX_TYPES, ERROR_CODES, QORT_DECIMALS, PROXY_URL, STATIC_SALT, ADDRESS_VERSION, KDF_THREADS, STATIC_BCRYPT_SALT, CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP, DYNAMIC_FEE_TIMESTAMP } export {
TX_TYPES,
ERROR_CODES,
QORT_DECIMALS,
PROXY_URL,
STATIC_SALT,
ADDRESS_VERSION,
KDF_THREADS,
STATIC_BCRYPT_SALT,
CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP,
DYNAMIC_FEE_TIMESTAMP,
};

View File

@ -1,37 +1,35 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class AddGroupAdminTransaction extends TransactionBase { export default class AddGroupAdminTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 24 this.type = 24;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._rGroupIdBytes, this._recipient, this._feeBytes);
this._rGroupIdBytes, return params;
this._recipient, }
this._feeBytes
)
return params
}
} }

View File

@ -1,45 +1,48 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class BuyNameTransacion extends TransactionBase { export default class BuyNameTransacion extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 7 this.type = 7;
} }
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set name(name) { set name(name) {
this.nameText = name this.nameText = name;
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name) this._nameBytes = this.constructor.utils.stringtoUTF8Array(name);
this._nameLength = this.constructor.utils.int32ToBytes(this._nameBytes.length) this._nameLength = this.constructor.utils.int32ToBytes(
} this._nameBytes.length
);
}
set sellPrice(sellPrice) { set sellPrice(sellPrice) {
this._sellPrice = sellPrice * QORT_DECIMALS this._sellPrice = sellPrice * QORT_DECIMALS;
this._sellPriceBytes = this.constructor.utils.int64ToBytes(this._sellPrice) this._sellPriceBytes = this.constructor.utils.int64ToBytes(this._sellPrice);
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._nameLength, this._nameLength,
this._nameBytes, this._nameBytes,
this._sellPriceBytes, this._sellPriceBytes,
this._recipient, this._recipient,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -1,37 +1,35 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class CancelGroupBanTransaction extends TransactionBase { export default class CancelGroupBanTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 27 this.type = 27;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._rGroupIdBytes, this._recipient, this._feeBytes);
this._rGroupIdBytes, return params;
this._recipient, }
this._feeBytes
)
return params
}
} }

View File

@ -1,36 +1,33 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class CancelGroupInviteTransaction extends TransactionBase { export default class CancelGroupInviteTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 30 this.type = 30;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._rGroupIdBytes, this._recipient, this._feeBytes);
this._rGroupIdBytes, return params;
this._recipient, }
this._feeBytes
)
return params
}
} }

View File

@ -1,33 +1,29 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class CancelSellNameTransacion extends TransactionBase { export default class CancelSellNameTransacion extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 6 this.type = 6;
} }
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set name(name) { set name(name) {
this.nameText = name this.nameText = name;
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name) this._nameBytes = this.constructor.utils.stringtoUTF8Array(name);
this._nameLength = this.constructor.utils.int32ToBytes(this._nameBytes.length) this._nameLength = this.constructor.utils.int32ToBytes(
} this._nameBytes.length
);
}
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._nameLength, this._nameBytes, this._feeBytes);
this._nameLength, return params;
this._nameBytes, }
this._feeBytes
)
return params
}
} }

View File

@ -1,148 +1,161 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS, TX_TYPES } from '../constants/constants' import { QORT_DECIMALS, TX_TYPES } from '../constants/constants';
import nacl from '../deps/nacl-fast' import nacl from '../deps/nacl-fast';
import Base58 from '../deps/Base58' import Base58 from '../deps/Base58';
import utils from '../utils/utils' import utils from '../utils/utils';
export default class ChatBase { export default class ChatBase {
static get utils() { static get utils() {
return utils return utils;
} }
static get nacl() { static get nacl() {
return nacl return nacl;
} }
static get Base58() { static get Base58() {
return Base58 return Base58;
} }
constructor() { constructor() {
this.fee = 0;
this.groupID = 0;
this.tests = [
() => {
if (!(this._type >= 1 && this._type in TX_TYPES)) {
return 'Invalid type: ' + this.type;
}
return true;
},
() => {
if (this._fee < 0) {
return 'Invalid fee: ' + this._fee / QORT_DECIMALS;
}
return true;
},
() => {
if (this._groupID < 0 || !Number.isInteger(this._groupID)) {
return 'Invalid groupID: ' + this._groupID;
}
return true;
},
() => {
if (!new Date(this._timestamp).getTime() > 0) {
return 'Invalid timestamp: ' + this._timestamp;
}
return true;
},
() => {
if (
!(
this._lastReference instanceof Uint8Array &&
this._lastReference.byteLength == 64
)
) {
return 'Invalid last reference: ' + this._lastReference;
}
return true;
},
() => {
if (!this._keyPair) {
return 'keyPair must be specified';
}
if (
!(
this._keyPair.publicKey instanceof Uint8Array &&
this._keyPair.publicKey.byteLength === 32
)
) {
return 'Invalid publicKey';
}
if (
!(
this._keyPair.privateKey instanceof Uint8Array &&
this._keyPair.privateKey.byteLength === 64
)
) {
return 'Invalid privateKey';
}
return true;
},
];
}
this.fee = 0 set keyPair(keyPair) {
this.groupID = 0 this._keyPair = keyPair;
this.tests = [ }
() => {
if (!(this._type >= 1 && this._type in TX_TYPES)) {
return 'Invalid type: ' + this.type
}
return true
},
() => {
if (this._fee < 0) {
return 'Invalid fee: ' + this._fee / QORT_DECIMALS
}
return true
},
() => {
if (this._groupID < 0 || !Number.isInteger(this._groupID)) {
return 'Invalid groupID: ' + this._groupID
}
return true
},
() => {
if (!(new Date(this._timestamp)).getTime() > 0) {
return 'Invalid timestamp: ' + this._timestamp
}
return true
},
() => {
if (!(this._lastReference instanceof Uint8Array && this._lastReference.byteLength == 64)) { set type(type) {
return 'Invalid last reference: ' + this._lastReference this.typeText = TX_TYPES[type];
} this._type = type;
return true this._typeBytes = this.constructor.utils.int32ToBytes(this._type);
}, }
() => {
if (!(this._keyPair)) {
return 'keyPair must be specified'
}
if (!(this._keyPair.publicKey instanceof Uint8Array && this._keyPair.publicKey.byteLength === 32)) {
return 'Invalid publicKey'
}
if (!(this._keyPair.privateKey instanceof Uint8Array && this._keyPair.privateKey.byteLength === 64)) {
return 'Invalid privateKey'
}
return true
}
]
}
set keyPair(keyPair) { set groupID(groupID) {
this._keyPair = keyPair this._groupID = groupID;
} this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID);
}
set type(type) { set timestamp(timestamp) {
this.typeText = TX_TYPES[type] this._timestamp = timestamp;
this._type = type this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp);
this._typeBytes = this.constructor.utils.int32ToBytes(this._type) }
}
set groupID(groupID) { set fee(fee) {
this._groupID = groupID this._fee = fee * QORT_DECIMALS;
this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set timestamp(timestamp) { set lastReference(lastReference) {
this._timestamp = timestamp this._lastReference =
this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp) lastReference instanceof Uint8Array
} ? lastReference
: this.constructor.Base58.decode(lastReference);
}
set fee(fee) { get params() {
this._fee = fee * QORT_DECIMALS return [
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._typeBytes,
} this._timestampBytes,
this._groupIDBytes,
this._lastReference,
this._keyPair.publicKey,
];
}
set lastReference(lastReference) { get chatBytes() {
const isValid = this.validParams();
if (!isValid.valid) {
throw new Error(isValid.message);
}
this._lastReference = lastReference instanceof Uint8Array ? lastReference : this.constructor.Base58.decode(lastReference) let result = new Uint8Array();
}
get params() { this.params.forEach((item) => {
return [ result = this.constructor.utils.appendBuffer(result, item);
this._typeBytes, });
this._timestampBytes,
this._groupIDBytes,
this._lastReference,
this._keyPair.publicKey
]
}
get chatBytes() { this._chatBytes = result;
const isValid = this.validParams()
if (!isValid.valid) {
throw new Error(isValid.message)
}
let result = new Uint8Array() return this._chatBytes;
}
this.params.forEach(item => { validParams() {
result = this.constructor.utils.appendBuffer(result, item) let finalResult = {
}) valid: true,
};
this._chatBytes = result this.tests.some((test) => {
const result = test();
return this._chatBytes if (result !== true) {
} finalResult = {
valid: false,
validParams() { message: result,
let finalResult = { };
valid: true return true;
} }
});
this.tests.some(test => {
const result = test()
if (result !== true) {
finalResult = {
valid: false,
message: result
}
return true
}
})
return finalResult
}
return finalResult;
}
} }

View File

@ -1,92 +1,126 @@
// @ts-nocheck // @ts-nocheck
import ChatBase from './ChatBase' import ChatBase from './ChatBase';
import nacl from '../deps/nacl-fast' import nacl from '../deps/nacl-fast';
import ed2curve from '../deps/ed2curve' import ed2curve from '../deps/ed2curve';
import { Sha256 } from 'asmcrypto.js' import { Sha256 } from 'asmcrypto.js';
import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../constants/constants' import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../constants/constants';
export default class ChatTransaction extends ChatBase { export default class ChatTransaction extends ChatBase {
constructor() { constructor() {
super() super();
this.type = 18 this.type = 18;
this.fee = 0 this.fee = 0;
} }
set recipientPublicKey(recipientPublicKey) { set recipientPublicKey(recipientPublicKey) {
this._base58RecipientPublicKey = recipientPublicKey instanceof Uint8Array ? this.constructor.Base58.encode(recipientPublicKey) : recipientPublicKey this._base58RecipientPublicKey =
this._recipientPublicKey = this.constructor.Base58.decode(this._base58RecipientPublicKey) recipientPublicKey instanceof Uint8Array
} ? this.constructor.Base58.encode(recipientPublicKey)
: recipientPublicKey;
this._recipientPublicKey = this.constructor.Base58.decode(
this._base58RecipientPublicKey
);
}
set proofOfWorkNonce(proofOfWorkNonce) { set proofOfWorkNonce(proofOfWorkNonce) {
this._proofOfWorkNonce = this.constructor.utils.int32ToBytes(proofOfWorkNonce) this._proofOfWorkNonce =
} this.constructor.utils.int32ToBytes(proofOfWorkNonce);
}
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this._hasReceipient = new Uint8Array(1) recipient instanceof Uint8Array
this._hasReceipient[0] = 1 ? recipient
} : this.constructor.Base58.decode(recipient);
this._hasReceipient = new Uint8Array(1);
this._hasReceipient[0] = 1;
}
set hasChatReference(hasChatReference) { set hasChatReference(hasChatReference) {
this._hasChatReference = new Uint8Array(1) this._hasChatReference = new Uint8Array(1);
this._hasChatReference[0] = hasChatReference this._hasChatReference[0] = hasChatReference;
} }
set chatReference(chatReference) { set chatReference(chatReference) {
this._chatReference = chatReference instanceof Uint8Array ? chatReference : this.constructor.Base58.decode(chatReference) this._chatReference =
} chatReference instanceof Uint8Array
? chatReference
: this.constructor.Base58.decode(chatReference);
}
set message(message) { set message(message) {
this.messageText = message; this.messageText = message;
this._message = this.constructor.utils.stringtoUTF8Array(message) this._message = this.constructor.utils.stringtoUTF8Array(message);
this._messageLength = this.constructor.utils.int32ToBytes(this._message.length) this._messageLength = this.constructor.utils.int32ToBytes(
} this._message.length
);
}
set isEncrypted(isEncrypted) { set isEncrypted(isEncrypted) {
this._isEncrypted = new Uint8Array(1) this._isEncrypted = new Uint8Array(1);
this._isEncrypted[0] = isEncrypted this._isEncrypted[0] = isEncrypted;
if (isEncrypted === 1) { if (isEncrypted === 1) {
const convertedPrivateKey = ed2curve.convertSecretKey(this._keyPair.privateKey) const convertedPrivateKey = ed2curve.convertSecretKey(
const convertedPublicKey = ed2curve.convertPublicKey(this._recipientPublicKey) this._keyPair.privateKey
const sharedSecret = new Uint8Array(32) );
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) const convertedPublicKey = ed2curve.convertPublicKey(
this._recipientPublicKey
);
const sharedSecret = new Uint8Array(32);
nacl.lowlevel.crypto_scalarmult(
sharedSecret,
convertedPrivateKey,
convertedPublicKey
);
this._chatEncryptionSeed = new Sha256().process(sharedSecret).finish().result this._chatEncryptionSeed = new Sha256()
this._encryptedMessage = nacl.secretbox(this._message, this._lastReference.slice(0, 24), this._chatEncryptionSeed) .process(sharedSecret)
} .finish().result;
this._encryptedMessage = nacl.secretbox(
this._message,
this._lastReference.slice(0, 24),
this._chatEncryptionSeed
);
}
this._myMessage = isEncrypted === 1 ? this._encryptedMessage : this._message this._myMessage =
this._myMessageLenth = isEncrypted === 1 ? this.constructor.utils.int32ToBytes(this._myMessage.length) : this._messageLength isEncrypted === 1 ? this._encryptedMessage : this._message;
} this._myMessageLenth =
isEncrypted === 1
? this.constructor.utils.int32ToBytes(this._myMessage.length)
: this._messageLength;
}
set isText(isText) { set isText(isText) {
this._isText = new Uint8Array(1) this._isText = new Uint8Array(1);
this._isText[0] = isText this._isText[0] = isText;
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._proofOfWorkNonce, this._proofOfWorkNonce,
this._hasReceipient, this._hasReceipient,
this._recipient, this._recipient,
this._myMessageLenth, this._myMessageLenth,
this._myMessage, this._myMessage,
this._isEncrypted, this._isEncrypted,
this._isText, this._isText,
this._feeBytes this._feeBytes
) );
// After the feature trigger timestamp we need to include chat reference // After the feature trigger timestamp we need to include chat reference
if (new Date(this._timestamp).getTime() >= CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP) { if (
params.push(this._hasChatReference) new Date(this._timestamp).getTime() >=
CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP
) {
params.push(this._hasChatReference);
if (this._hasChatReference[0] == 1) { if (this._hasChatReference[0] == 1) {
params.push(this._chatReference) params.push(this._chatReference);
} }
} }
return params return params;
} }
} }

View File

@ -1,64 +1,73 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class CreateGroupTransaction extends TransactionBase { export default class CreateGroupTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 22 this.type = 22;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set fee(fee) { set rGroupName(rGroupName) {
this._fee = fee * QORT_DECIMALS this._rGroupName = rGroupName;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._rGroupNameBytes = this.constructor.utils.stringtoUTF8Array(
} this._rGroupName
);
this._rGroupNameLength = this.constructor.utils.int32ToBytes(
this._rGroupNameBytes.length
);
}
set rGroupName(rGroupName) { set rGroupDesc(rGroupDesc) {
this._rGroupName = rGroupName this._rGroupDesc = rGroupDesc;
this._rGroupNameBytes = this.constructor.utils.stringtoUTF8Array(this._rGroupName) this._rGroupDescBytes = this.constructor.utils.stringtoUTF8Array(
this._rGroupNameLength = this.constructor.utils.int32ToBytes(this._rGroupNameBytes.length) this._rGroupDesc
} );
this._rGroupDescLength = this.constructor.utils.int32ToBytes(
this._rGroupDescBytes.length
);
}
set rGroupDesc(rGroupDesc) { set rGroupType(rGroupType) {
this._rGroupDesc = rGroupDesc this._rGroupType = new Uint8Array(1);
this._rGroupDescBytes = this.constructor.utils.stringtoUTF8Array(this._rGroupDesc) this._rGroupType[0] = rGroupType;
this._rGroupDescLength = this.constructor.utils.int32ToBytes(this._rGroupDescBytes.length) }
}
set rGroupType(rGroupType) { set rGroupApprovalThreshold(rGroupApprovalThreshold) {
this._rGroupType = new Uint8Array(1) this._rGroupApprovalThreshold = new Uint8Array(1);
this._rGroupType[0] = rGroupType this._rGroupApprovalThreshold[0] = rGroupApprovalThreshold;
} }
set rGroupApprovalThreshold(rGroupApprovalThreshold) { set rGroupMinimumBlockDelay(rGroupMinimumBlockDelay) {
this._rGroupApprovalThreshold = new Uint8Array(1) this._rGroupMinimumBlockDelayBytes = this.constructor.utils.int32ToBytes(
this._rGroupApprovalThreshold[0] = rGroupApprovalThreshold rGroupMinimumBlockDelay
} );
}
set rGroupMinimumBlockDelay(rGroupMinimumBlockDelay) { set rGroupMaximumBlockDelay(rGroupMaximumBlockDelay) {
this._rGroupMinimumBlockDelayBytes = this.constructor.utils.int32ToBytes(rGroupMinimumBlockDelay) this._rGroupMaximumBlockDelayBytes = this.constructor.utils.int32ToBytes(
} rGroupMaximumBlockDelay
);
}
set rGroupMaximumBlockDelay(rGroupMaximumBlockDelay) { get params() {
this._rGroupMaximumBlockDelayBytes = this.constructor.utils.int32ToBytes(rGroupMaximumBlockDelay) const params = super.params;
} params.push(
this._rGroupNameLength,
get params() { this._rGroupNameBytes,
const params = super.params this._rGroupDescLength,
params.push( this._rGroupDescBytes,
this._rGroupNameLength, this._rGroupType,
this._rGroupNameBytes, this._rGroupApprovalThreshold,
this._rGroupDescLength, this._rGroupMinimumBlockDelayBytes,
this._rGroupDescBytes, this._rGroupMaximumBlockDelayBytes,
this._rGroupType, this._feeBytes
this._rGroupApprovalThreshold, );
this._rGroupMinimumBlockDelayBytes, return params;
this._rGroupMaximumBlockDelayBytes, }
this._feeBytes
)
return params
}
} }

View File

@ -1,73 +1,84 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants' import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from './TransactionBase' import TransactionBase from './TransactionBase';
export default class CreatePollTransaction extends TransactionBase { export default class CreatePollTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 8 this.type = 8;
this._options = [] this._options = [];
} }
addOption(option) { addOption(option) {
const optionBytes = this.constructor.utils.stringtoUTF8Array(option) const optionBytes = this.constructor.utils.stringtoUTF8Array(option);
const optionLength = this.constructor.utils.int32ToBytes(optionBytes.length) const optionLength = this.constructor.utils.int32ToBytes(
this._options.push({ length: optionLength, bytes: optionBytes }) optionBytes.length
} );
this._options.push({ length: optionLength, bytes: optionBytes });
}
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set fee(fee) { set ownerAddress(ownerAddress) {
this._fee = fee * QORT_DECIMALS this._ownerAddress =
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) ownerAddress instanceof Uint8Array
} ? ownerAddress
: this.constructor.Base58.decode(ownerAddress);
}
set ownerAddress(ownerAddress) { set rPollName(rPollName) {
this._ownerAddress = ownerAddress instanceof Uint8Array ? ownerAddress : this.constructor.Base58.decode(ownerAddress) this._rPollName = rPollName;
} this._rPollNameBytes = this.constructor.utils.stringtoUTF8Array(
this._rPollName
);
this._rPollNameLength = this.constructor.utils.int32ToBytes(
this._rPollNameBytes.length
);
}
set rPollName(rPollName) { set rPollDesc(rPollDesc) {
this._rPollName = rPollName this._rPollDesc = rPollDesc;
this._rPollNameBytes = this.constructor.utils.stringtoUTF8Array(this._rPollName) this._rPollDescBytes = this.constructor.utils.stringtoUTF8Array(
this._rPollNameLength = this.constructor.utils.int32ToBytes(this._rPollNameBytes.length) this._rPollDesc
);
this._rPollDescLength = this.constructor.utils.int32ToBytes(
this._rPollDescBytes.length
);
}
} set rOptions(rOptions) {
const optionsArray = rOptions[0].split(', ').map((opt) => opt.trim());
this._pollOptions = optionsArray;
set rPollDesc(rPollDesc) { for (let i = 0; i < optionsArray.length; i++) {
this._rPollDesc = rPollDesc this.addOption(optionsArray[i]);
this._rPollDescBytes = this.constructor.utils.stringtoUTF8Array(this._rPollDesc) }
this._rPollDescLength = this.constructor.utils.int32ToBytes(this._rPollDescBytes.length)
}
set rOptions(rOptions) { this._rNumberOfOptionsBytes = this.constructor.utils.int32ToBytes(
const optionsArray = rOptions[0].split(', ').map(opt => opt.trim()) optionsArray.length
this._pollOptions = optionsArray );
}
for (let i = 0; i < optionsArray.length; i++) { get params() {
this.addOption(optionsArray[i]) const params = super.params;
} params.push(
this._ownerAddress,
this._rPollNameLength,
this._rPollNameBytes,
this._rPollDescLength,
this._rPollDescBytes,
this._rNumberOfOptionsBytes
);
this._rNumberOfOptionsBytes = this.constructor.utils.int32ToBytes(optionsArray.length) // Push the dynamic options
} for (let i = 0; i < this._options.length; i++) {
params.push(this._options[i].length, this._options[i].bytes);
}
params.push(this._feeBytes);
get params() { return params;
const params = super.params }
params.push(
this._ownerAddress,
this._rPollNameLength,
this._rPollNameBytes,
this._rPollDescLength,
this._rPollDescBytes,
this._rNumberOfOptionsBytes
)
// Push the dynamic options
for (let i = 0; i < this._options.length; i++) {
params.push(this._options[i].length, this._options[i].bytes)
}
params.push(this._feeBytes)
return params
}
} }

View File

@ -1,78 +1,90 @@
// @ts-nocheck // @ts-nocheck
import TransactionBase from './TransactionBase';
import TransactionBase from './TransactionBase' import { QORT_DECIMALS } from '../constants/constants';
import { QORT_DECIMALS } from '../constants/constants'
export default class DeployAtTransaction extends TransactionBase { export default class DeployAtTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 16 this.type = 16;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set rAmount(rAmount) {
this._rAmount = Math.round(rAmount * QORT_DECIMALS);
this._rAmountBytes = this.constructor.utils.int64ToBytes(this._rAmount);
}
set fee(fee) { set rName(rName) {
this._fee = fee * QORT_DECIMALS this._rName = rName;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._rNameBytes = this.constructor.utils.stringtoUTF8Array(
} this._rName.toLocaleLowerCase()
);
this._rNameLength = this.constructor.utils.int32ToBytes(
this._rNameBytes.length
);
}
set rAmount(rAmount) { set rDescription(rDescription) {
this._rAmount = Math.round(rAmount * QORT_DECIMALS) this._rDescription = rDescription;
this._rAmountBytes = this.constructor.utils.int64ToBytes(this._rAmount) this._rDescriptionBytes = this.constructor.utils.stringtoUTF8Array(
} this._rDescription.toLocaleLowerCase()
);
this._rDescriptionLength = this.constructor.utils.int32ToBytes(
this._rDescriptionBytes.length
);
}
set rName(rName) { set atType(atType) {
this._rName = rName this._atType = atType;
this._rNameBytes = this.constructor.utils.stringtoUTF8Array(this._rName.toLocaleLowerCase()) this._atTypeBytes = this.constructor.utils.stringtoUTF8Array(this._atType);
this._rNameLength = this.constructor.utils.int32ToBytes(this._rNameBytes.length) this._atTypeLength = this.constructor.utils.int32ToBytes(
} this._atTypeBytes.length
);
}
set rDescription(rDescription) { set rTags(rTags) {
this._rDescription = rDescription this._rTags = rTags;
this._rDescriptionBytes = this.constructor.utils.stringtoUTF8Array(this._rDescription.toLocaleLowerCase()) this._rTagsBytes = this.constructor.utils.stringtoUTF8Array(
this._rDescriptionLength = this.constructor.utils.int32ToBytes(this._rDescriptionBytes.length) this._rTags.toLocaleLowerCase()
} );
this._rTagsLength = this.constructor.utils.int32ToBytes(
this._rTagsBytes.length
);
}
set atType(atType) { set rCreationBytes(rCreationBytes) {
this._atType = atType const decode = this.constructor.Base58.decode(rCreationBytes);
this._atTypeBytes = this.constructor.utils.stringtoUTF8Array(this._atType) this._rCreationBytes = this.constructor.utils.stringtoUTF8Array(decode);
this._atTypeLength = this.constructor.utils.int32ToBytes(this._atTypeBytes.length) this._rCreationBytesLength = this.constructor.utils.int32ToBytes(
} this._rCreationBytes.length
);
}
set rTags(rTags) { set rAssetId(rAssetId) {
this._rTags = rTags this._rAssetId = this.constructor.utils.int64ToBytes(rAssetId);
this._rTagsBytes = this.constructor.utils.stringtoUTF8Array(this._rTags.toLocaleLowerCase()) }
this._rTagsLength = this.constructor.utils.int32ToBytes(this._rTagsBytes.length)
}
set rCreationBytes(rCreationBytes) { get params() {
const decode = this.constructor.Base58.decode(rCreationBytes) const params = super.params;
this._rCreationBytes = this.constructor.utils.stringtoUTF8Array(decode) params.push(
this._rCreationBytesLength = this.constructor.utils.int32ToBytes(this._rCreationBytes.length) this._rNameLength,
} this._rNameBytes,
this._rDescriptionLength,
set rAssetId(rAssetId) { this._rDescriptionBytes,
this._rAssetId = this.constructor.utils.int64ToBytes(rAssetId) this._atTypeLength,
} this._atTypeBytes,
this._rTagsLength,
get params() { this._rTagsBytes,
const params = super.params this._rCreationBytesLength,
params.push( this._rCreationBytes,
this._rNameLength, this._rAmountBytes,
this._rNameBytes, this._rAssetId,
this._rDescriptionLength, this._feeBytes
this._rDescriptionBytes, );
this._atTypeLength, return params;
this._atTypeBytes, }
this._rTagsLength,
this._rTagsBytes,
this._rCreationBytesLength,
this._rCreationBytes,
this._rAmountBytes,
this._rAssetId,
this._feeBytes
)
return params
}
} }

View File

@ -1,50 +1,56 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class GroupBanTransaction extends TransactionBase { export default class GroupBanTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 26 this.type = 26;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set rBanReason(rBanReason) { set rBanReason(rBanReason) {
this._rBanReason = rBanReason this._rBanReason = rBanReason;
this._rBanReasonBytes = this.constructor.utils.stringtoUTF8Array(this._rBanReason) this._rBanReasonBytes = this.constructor.utils.stringtoUTF8Array(
this._rBanReasonLength = this.constructor.utils.int32ToBytes(this._rBanReasonBytes.length) this._rBanReason
} );
this._rBanReasonLength = this.constructor.utils.int32ToBytes(
this._rBanReasonBytes.length
);
}
set rBanTime(rBanTime) { set rBanTime(rBanTime) {
this._rBanTime = rBanTime this._rBanTime = rBanTime;
this._rBanTimeBytes = this.constructor.utils.int32ToBytes(this._rBanTime) this._rBanTimeBytes = this.constructor.utils.int32ToBytes(this._rBanTime);
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._rGroupIdBytes, this._rGroupIdBytes,
this._recipient, this._recipient,
this._rBanReasonLength, this._rBanReasonLength,
this._rBanReasonBytes, this._rBanReasonBytes,
this._rBanTimeBytes, this._rBanTimeBytes,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -1,72 +1,79 @@
// @ts-nocheck // @ts-nocheck
import ChatBase from './ChatBase';
import ChatBase from './ChatBase' import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../constants/constants';
import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../constants/constants'
export default class GroupChatTransaction extends ChatBase { export default class GroupChatTransaction extends ChatBase {
constructor() { constructor() {
super(); super();
this.type = 18 this.type = 18;
this.fee = 0 this.fee = 0;
} }
set proofOfWorkNonce(proofOfWorkNonce) { set proofOfWorkNonce(proofOfWorkNonce) {
this._proofOfWorkNonce = this.constructor.utils.int32ToBytes(proofOfWorkNonce) this._proofOfWorkNonce =
} this.constructor.utils.int32ToBytes(proofOfWorkNonce);
}
set hasReceipient(hasReceipient) { set hasReceipient(hasReceipient) {
this._hasReceipient = new Uint8Array(1) this._hasReceipient = new Uint8Array(1);
this._hasReceipient[0] = hasReceipient this._hasReceipient[0] = hasReceipient;
} }
set message(message) { set message(message) {
this.messageText = message this.messageText = message;
this._message = this.constructor.utils.stringtoUTF8Array(message) this._message = this.constructor.utils.stringtoUTF8Array(message);
this._messageLength = this.constructor.utils.int32ToBytes(this._message.length) this._messageLength = this.constructor.utils.int32ToBytes(
} this._message.length
);
}
set hasChatReference(hasChatReference) { set hasChatReference(hasChatReference) {
this._hasChatReference = new Uint8Array(1) this._hasChatReference = new Uint8Array(1);
this._hasChatReference[0] = hasChatReference this._hasChatReference[0] = hasChatReference;
} }
set chatReference(chatReference) { set chatReference(chatReference) {
this._chatReference = chatReference instanceof Uint8Array ? chatReference : this.constructor.Base58.decode(chatReference) this._chatReference =
} chatReference instanceof Uint8Array
? chatReference
: this.constructor.Base58.decode(chatReference);
}
set isEncrypted(isEncrypted) { set isEncrypted(isEncrypted) {
this._isEncrypted = new Uint8Array(1) this._isEncrypted = new Uint8Array(1);
this._isEncrypted[0] = isEncrypted this._isEncrypted[0] = isEncrypted;
} }
set isText(isText) { set isText(isText) {
this._isText = new Uint8Array(1) this._isText = new Uint8Array(1);
this._isText[0] = isText this._isText[0] = isText;
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._proofOfWorkNonce, this._proofOfWorkNonce,
this._hasReceipient, this._hasReceipient,
this._messageLength, this._messageLength,
this._message, this._message,
this._isEncrypted, this._isEncrypted,
this._isText, this._isText,
this._feeBytes this._feeBytes
) );
// After the feature trigger timestamp we need to include chat reference // After the feature trigger timestamp we need to include chat reference
if (new Date(this._timestamp).getTime() >= CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP) { if (
params.push(this._hasChatReference) new Date(this._timestamp).getTime() >=
CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP
) {
params.push(this._hasChatReference);
if (this._hasChatReference[0] == 1) { if (this._hasChatReference[0] == 1) {
params.push(this._chatReference) params.push(this._chatReference);
} }
} }
return params return params;
} }
} }

View File

@ -1,42 +1,46 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class GroupInviteTransaction extends TransactionBase { export default class GroupInviteTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 29 this.type = 29;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set rInviteTime(rInviteTime) { set rInviteTime(rInviteTime) {
this._rInviteTime = rInviteTime this._rInviteTime = rInviteTime;
this._rInviteTimeBytes = this.constructor.utils.int32ToBytes(this._rInviteTime) this._rInviteTimeBytes = this.constructor.utils.int32ToBytes(
} this._rInviteTime
);
}
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._rGroupIdBytes, this._rGroupIdBytes,
this._recipient, this._recipient,
this._rInviteTimeBytes, this._rInviteTimeBytes,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -1,46 +1,50 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants';
import { QORT_DECIMALS } from "../constants/constants" import TransactionBase from './TransactionBase';
import TransactionBase from "./TransactionBase"
export default class GroupKickTransaction extends TransactionBase { export default class GroupKickTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 28 this.type = 28;
} }
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set rBanReason(rBanReason) { set rBanReason(rBanReason) {
this._rBanReason = rBanReason this._rBanReason = rBanReason;
this._rBanReasonBytes = this.constructor.utils.stringtoUTF8Array(this._rBanReason) this._rBanReasonBytes = this.constructor.utils.stringtoUTF8Array(
this._rBanReasonLength = this.constructor.utils.int32ToBytes(this._rBanReasonBytes.length) this._rBanReason
} );
this._rBanReasonLength = this.constructor.utils.int32ToBytes(
this._rBanReasonBytes.length
);
}
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
this.theRecipient = recipient recipient instanceof Uint8Array
} ? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._rGroupIdBytes, this._rGroupIdBytes,
this._recipient, this._recipient,
this._rBanReasonLength, this._rBanReasonLength,
this._rBanReasonBytes, this._rBanReasonBytes,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -1,38 +1,33 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class JoinGroupTransaction extends TransactionBase { export default class JoinGroupTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 31 this.type = 31;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set registrantAddress(registrantAddress) {
this._registrantAddress =
registrantAddress instanceof Uint8Array
? registrantAddress
: this.constructor.Base58.decode(registrantAddress);
}
set fee(fee) { set rGroupId(rGroupId) {
this._fee = fee * QORT_DECIMALS this._rGroupId = rGroupId;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
set registrantAddress(registrantAddress) { get params() {
this._registrantAddress = registrantAddress instanceof Uint8Array ? registrantAddress : this.constructor.Base58.decode(registrantAddress) const params = super.params;
} params.push(this._rGroupIdBytes, this._feeBytes);
return params;
set rGroupId(rGroupId) { }
this._rGroupId = rGroupId
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId)
}
get params() {
const params = super.params
params.push(
this._rGroupIdBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,35 +1,34 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class LeaveGroupTransaction extends TransactionBase { export default class LeaveGroupTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 32 this.type = 32;
} }
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set registrantAddress(registrantAddress) { set registrantAddress(registrantAddress) {
this._registrantAddress = registrantAddress instanceof Uint8Array ? registrantAddress : this.constructor.Base58.decode(registrantAddress) this._registrantAddress =
} registrantAddress instanceof Uint8Array
? registrantAddress
: this.constructor.Base58.decode(registrantAddress);
}
set rGroupId(rGroupId) { set rGroupId(rGroupId) {
this._rGroupId = rGroupId this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._rGroupIdBytes, this._feeBytes);
this._rGroupIdBytes, return params;
this._feeBytes }
)
return params
}
} }

View File

@ -1,38 +1,36 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants' import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from './TransactionBase' import TransactionBase from './TransactionBase';
export default class PaymentTransaction extends TransactionBase { export default class PaymentTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 2 this.type = 2;
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
} recipient instanceof Uint8Array
? recipient
: this.constructor.Base58.decode(recipient);
}
set dialogto(dialogto) { set dialogto(dialogto) {
this._dialogto = dialogto this._dialogto = dialogto;
} }
set dialogamount(dialogamount) { set dialogamount(dialogamount) {
this._dialogamount = dialogamount this._dialogamount = dialogamount;
} }
set amount(amount) { set amount(amount) {
this._amount = Math.round(amount * QORT_DECIMALS) this._amount = Math.round(amount * QORT_DECIMALS);
this._amountBytes = this.constructor.utils.int64ToBytes(this._amount) this._amountBytes = this.constructor.utils.int64ToBytes(this._amount);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(this._recipient, this._amountBytes, this._feeBytes);
this._recipient, return params;
this._amountBytes, }
this._feeBytes
)
return params
}
} }

View File

@ -1,42 +1,44 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class RegisterNameTransaction extends TransactionBase { export default class RegisterNameTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 3 this.type = 3;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set fee(fee) { set name(name) {
this._fee = fee * QORT_DECIMALS this.nameText = name;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._nameBytes = this.constructor.utils.stringtoUTF8Array(name);
} this._nameLength = this.constructor.utils.int32ToBytes(
this._nameBytes.length
);
}
set name(name) { set value(value) {
this.nameText = name this.valueText =
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name) value.length === 0 ? 'Registered Name on the Qortal Chain' : value;
this._nameLength = this.constructor.utils.int32ToBytes(this._nameBytes.length) this._valueBytes = this.constructor.utils.stringtoUTF8Array(this.valueText);
} this._valueLength = this.constructor.utils.int32ToBytes(
this._valueBytes.length
);
}
set value(value) { get params() {
this.valueText = value.length === 0 ? "Registered Name on the Qortal Chain" : value const params = super.params;
this._valueBytes = this.constructor.utils.stringtoUTF8Array(this.valueText) params.push(
this._valueLength = this.constructor.utils.int32ToBytes(this._valueBytes.length) this._nameLength,
} this._nameBytes,
this._valueLength,
get params() { this._valueBytes,
const params = super.params this._feeBytes
params.push( );
this._nameLength, return params;
this._nameBytes, }
this._valueLength,
this._valueBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,38 +1,34 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class RemoveGroupAdminTransaction extends TransactionBase { export default class RemoveGroupAdminTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 25 this.type = 25;
} }
set rGroupId(rGroupId) {
this._rGroupId = rGroupId;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId);
}
set recipient(recipient) {
this._recipient =
recipient instanceof Uint8Array
? recipient
: this.constructor.Base58.decode(recipient);
this.theRecipient = recipient;
}
set rGroupId(rGroupId) { set fee(fee) {
this._rGroupId = rGroupId this._fee = fee * QORT_DECIMALS;
this._rGroupIdBytes = this.constructor.utils.int32ToBytes(this._rGroupId) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set recipient(recipient) { get params() {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) const params = super.params;
this.theRecipient = recipient params.push(this._rGroupIdBytes, this._recipient, this._feeBytes);
} return params;
}
set fee(fee) {
this._fee = fee * QORT_DECIMALS
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee)
}
get params() {
const params = super.params
params.push(
this._rGroupIdBytes,
this._recipient,
this._feeBytes
)
return params
}
} }

View File

@ -1,46 +1,50 @@
// @ts-nocheck // @ts-nocheck
import { DYNAMIC_FEE_TIMESTAMP } from "../constants/constants" import { DYNAMIC_FEE_TIMESTAMP } from '../constants/constants';
import Base58 from "../deps/Base58" import Base58 from '../deps/Base58';
import publicKeyToAddress from "../utils/generateWallet/publicKeyToAddress" import publicKeyToAddress from '../utils/generateWallet/publicKeyToAddress';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class RemoveRewardShareTransaction extends TransactionBase { export default class RemoveRewardShareTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 38 this.type = 38;
} }
set rewardShareKeyPairPublicKey(rewardShareKeyPairPublicKey) {
this._rewardShareKeyPairPublicKey = Base58.decode(
rewardShareKeyPairPublicKey
);
}
set rewardShareKeyPairPublicKey(rewardShareKeyPairPublicKey) { set recipient(recipient) {
this._rewardShareKeyPairPublicKey = Base58.decode(rewardShareKeyPairPublicKey) const _address = publicKeyToAddress(this._keyPair.publicKey);
} this._recipient =
recipient instanceof Uint8Array
? recipient
: this.constructor.Base58.decode(recipient);
set recipient(recipient) { if (new Date(this._timestamp).getTime() >= DYNAMIC_FEE_TIMESTAMP) {
const _address = publicKeyToAddress(this._keyPair.publicKey) this.fee = _address === recipient ? 0 : 0.01;
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) } else {
this.fee = _address === recipient ? 0 : 0.001;
}
}
if (new Date(this._timestamp).getTime() >= DYNAMIC_FEE_TIMESTAMP) { set percentageShare(share) {
this.fee = _address === recipient ? 0 : 0.01 this._percentageShare = share * 100;
} else { this._percentageShareBytes = this.constructor.utils.int64ToBytes(
this.fee = _address === recipient ? 0 : 0.001 this._percentageShare
} );
} }
set percentageShare(share) { get params() {
this._percentageShare = share * 100 const params = super.params;
this._percentageShareBytes = this.constructor.utils.int64ToBytes(this._percentageShare) params.push(
} this._recipient,
this._rewardShareKeyPairPublicKey,
get params() { this._percentageShareBytes,
const params = super.params this._feeBytes
params.push( );
this._recipient, return params;
this._rewardShareKeyPairPublicKey, }
this._percentageShareBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,60 +1,86 @@
// @ts-nocheck // @ts-nocheck
import TransactionBase from './TransactionBase' import TransactionBase from './TransactionBase';
import { Sha256 } from 'asmcrypto.js';
import { Sha256 } from 'asmcrypto.js' import nacl from '../deps/nacl-fast';
import nacl from '../deps/nacl-fast' import ed2curve from '../deps/ed2curve';
import ed2curve from '../deps/ed2curve' import { DYNAMIC_FEE_TIMESTAMP } from '../constants/constants';
import { DYNAMIC_FEE_TIMESTAMP } from '../constants/constants' import publicKeyToAddress from '../utils/generateWallet/publicKeyToAddress';
import publicKeyToAddress from '../utils/generateWallet/publicKeyToAddress'
export default class RewardShareTransaction extends TransactionBase { export default class RewardShareTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 38 this.type = 38;
} }
set recipientPublicKey(recipientPublicKey) {
this._base58RecipientPublicKey =
recipientPublicKey instanceof Uint8Array
? this.constructor.Base58.encode(recipientPublicKey)
: recipientPublicKey;
this._recipientPublicKey = this.constructor.Base58.decode(
this._base58RecipientPublicKey
);
this.recipient = publicKeyToAddress(this._recipientPublicKey);
const convertedPrivateKey = ed2curve.convertSecretKey(
this._keyPair.privateKey
);
const convertedPublicKey = ed2curve.convertPublicKey(
this._recipientPublicKey
);
const sharedSecret = new Uint8Array(32);
set recipientPublicKey(recipientPublicKey) { nacl.lowlevel.crypto_scalarmult(
this._base58RecipientPublicKey = recipientPublicKey instanceof Uint8Array ? this.constructor.Base58.encode(recipientPublicKey) : recipientPublicKey sharedSecret,
this._recipientPublicKey = this.constructor.Base58.decode(this._base58RecipientPublicKey) convertedPrivateKey,
this.recipient = publicKeyToAddress(this._recipientPublicKey) convertedPublicKey
);
const convertedPrivateKey = ed2curve.convertSecretKey(this._keyPair.privateKey) this._rewardShareSeed = new Sha256().process(sharedSecret).finish().result;
const convertedPublicKey = ed2curve.convertPublicKey(this._recipientPublicKey) this._base58RewardShareSeed = this.constructor.Base58.encode(
const sharedSecret = new Uint8Array(32) this._rewardShareSeed
);
this._rewardShareKeyPair = nacl.sign.keyPair.fromSeed(
this._rewardShareSeed
);
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) if (new Date(this._timestamp).getTime() >= DYNAMIC_FEE_TIMESTAMP) {
this.fee =
recipientPublicKey ===
this.constructor.Base58.encode(this._keyPair.publicKey)
? 0
: 0.01;
} else {
this.fee =
recipientPublicKey ===
this.constructor.Base58.encode(this._keyPair.publicKey)
? 0
: 0.001;
}
}
this._rewardShareSeed = new Sha256().process(sharedSecret).finish().result set recipient(recipient) {
this._base58RewardShareSeed = this.constructor.Base58.encode(this._rewardShareSeed) this._recipient =
this._rewardShareKeyPair = nacl.sign.keyPair.fromSeed(this._rewardShareSeed) recipient instanceof Uint8Array
? recipient
: this.constructor.Base58.decode(recipient);
}
if (new Date(this._timestamp).getTime() >= DYNAMIC_FEE_TIMESTAMP) { set percentageShare(share) {
this.fee = (recipientPublicKey === this.constructor.Base58.encode(this._keyPair.publicKey) ? 0 : 0.01) this._percentageShare = share * 100;
} else { this._percentageShareBytes = this.constructor.utils.int64ToBytes(
this.fee = (recipientPublicKey === this.constructor.Base58.encode(this._keyPair.publicKey) ? 0 : 0.001) this._percentageShare
} );
} }
set recipient(recipient) { get params() {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) const params = super.params;
} params.push(
this._recipient,
set percentageShare(share) { this._rewardShareKeyPair.publicKey,
this._percentageShare = share * 100 this._percentageShareBytes,
this._percentageShareBytes = this.constructor.utils.int64ToBytes(this._percentageShare) this._feeBytes
} );
return params;
get params() { }
const params = super.params
params.push(
this._recipient,
this._rewardShareKeyPair.publicKey,
this._percentageShareBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,40 +1,40 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class SellNameTransacion extends TransactionBase { export default class SellNameTransacion extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 5 this.type = 5;
} }
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set name(name) { set name(name) {
this.nameText = name this.nameText = name;
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name) this._nameBytes = this.constructor.utils.stringtoUTF8Array(name);
this._nameLength = this.constructor.utils.int32ToBytes(this._nameBytes.length) this._nameLength = this.constructor.utils.int32ToBytes(
} this._nameBytes.length
);
}
set sellPrice(sellPrice) { set sellPrice(sellPrice) {
this.showSellPrice = sellPrice this.showSellPrice = sellPrice;
this._sellPrice = sellPrice * QORT_DECIMALS this._sellPrice = sellPrice * QORT_DECIMALS;
this._sellPriceBytes = this.constructor.utils.int64ToBytes(this._sellPrice) this._sellPriceBytes = this.constructor.utils.int64ToBytes(this._sellPrice);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._nameLength, this._nameLength,
this._nameBytes, this._nameBytes,
this._sellPriceBytes, this._sellPriceBytes,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -7,59 +7,59 @@
*/ */
export default class TradeBotCreateRequest { export default class TradeBotCreateRequest {
constructor() { constructor() {
// ... // ...
} }
createTransaction(txnReq) { createTransaction(txnReq) {
this.creatorPublicKey(txnReq.creatorPublicKey) this.creatorPublicKey(txnReq.creatorPublicKey);
this.qortAmount(txnReq.qortAmount) this.qortAmount(txnReq.qortAmount);
this.fundingQortAmount(txnReq.fundingQortAmount) this.fundingQortAmount(txnReq.fundingQortAmount);
this.foreignBlockchain(txnReq.foreignBlockchain) this.foreignBlockchain(txnReq.foreignBlockchain);
this.foreignAmount(txnReq.foreignAmount) this.foreignAmount(txnReq.foreignAmount);
this.tradeTimeout(txnReq.tradeTimeout) this.tradeTimeout(txnReq.tradeTimeout);
this.receivingAddress(txnReq.receivingAddress) this.receivingAddress(txnReq.receivingAddress);
return this.txnRequest() return this.txnRequest();
} }
creatorPublicKey(creatorPublicKey) { creatorPublicKey(creatorPublicKey) {
this._creatorPublicKey = creatorPublicKey this._creatorPublicKey = creatorPublicKey;
} }
qortAmount(qortAmount) { qortAmount(qortAmount) {
this._qortAmount = qortAmount this._qortAmount = qortAmount;
} }
fundingQortAmount(fundingQortAmount) { fundingQortAmount(fundingQortAmount) {
this._fundingQortAmount = fundingQortAmount this._fundingQortAmount = fundingQortAmount;
} }
foreignBlockchain(foreignBlockchain) { foreignBlockchain(foreignBlockchain) {
this._foreignBlockchain = foreignBlockchain this._foreignBlockchain = foreignBlockchain;
} }
foreignAmount(foreignAmount) { foreignAmount(foreignAmount) {
this._foreignAmount = foreignAmount this._foreignAmount = foreignAmount;
} }
tradeTimeout(tradeTimeout) { tradeTimeout(tradeTimeout) {
this._tradeTimeout = tradeTimeout this._tradeTimeout = tradeTimeout;
} }
receivingAddress(receivingAddress) { receivingAddress(receivingAddress) {
this._receivingAddress = receivingAddress this._receivingAddress = receivingAddress;
} }
txnRequest() { txnRequest() {
return { return {
creatorPublicKey: this._creatorPublicKey, creatorPublicKey: this._creatorPublicKey,
qortAmount: this._qortAmount, qortAmount: this._qortAmount,
fundingQortAmount: this._fundingQortAmount, fundingQortAmount: this._fundingQortAmount,
foreignBlockchain: this._foreignBlockchain, foreignBlockchain: this._foreignBlockchain,
foreignAmount: this._foreignAmount, foreignAmount: this._foreignAmount,
tradeTimeout: this._tradeTimeout, tradeTimeout: this._tradeTimeout,
receivingAddress: this._receivingAddress receivingAddress: this._receivingAddress,
} };
} }
} }

View File

@ -7,29 +7,29 @@
*/ */
export default class DeleteTradeOffer { export default class DeleteTradeOffer {
constructor() { constructor() {
// ... // ...
} }
createTransaction(txnReq) { createTransaction(txnReq) {
this.creatorPublicKey(txnReq.creatorPublicKey) this.creatorPublicKey(txnReq.creatorPublicKey);
this.atAddress(txnReq.atAddress) this.atAddress(txnReq.atAddress);
return this.txnRequest() return this.txnRequest();
} }
creatorPublicKey(creatorPublicKey) { creatorPublicKey(creatorPublicKey) {
this._creatorPublicKey = creatorPublicKey this._creatorPublicKey = creatorPublicKey;
} }
atAddress(atAddress) { atAddress(atAddress) {
this._atAddress = atAddress this._atAddress = atAddress;
} }
txnRequest() { txnRequest() {
return { return {
creatorPublicKey: this._creatorPublicKey, creatorPublicKey: this._creatorPublicKey,
atAddress: this._atAddress atAddress: this._atAddress,
} };
} }
} }

View File

@ -7,36 +7,35 @@
*/ */
export class TradeBotRespondMultipleRequest { export class TradeBotRespondMultipleRequest {
constructor() { constructor() {
// ... // ...
} }
createTransaction(txnReq) { createTransaction(txnReq) {
this.addresses(txnReq.addresses) this.addresses(txnReq.addresses);
this.foreignKey(txnReq.foreignKey) this.foreignKey(txnReq.foreignKey);
this.receivingAddress(txnReq.receivingAddress) this.receivingAddress(txnReq.receivingAddress);
return this.txnRequest() return this.txnRequest();
} }
addresses(addresses) { addresses(addresses) {
this._addresses = addresses this._addresses = addresses;
} }
foreignKey(foreignKey) { foreignKey(foreignKey) {
this._foreignKey = foreignKey this._foreignKey = foreignKey;
} }
receivingAddress(receivingAddress) { receivingAddress(receivingAddress) {
this._receivingAddress = receivingAddress this._receivingAddress = receivingAddress;
} }
txnRequest() { txnRequest() {
return { return {
addresses: this._addresses, addresses: this._addresses,
foreignKey: this._foreignKey, foreignKey: this._foreignKey,
receivingAddress: this._receivingAddress receivingAddress: this._receivingAddress,
} };
} }
} }

View File

@ -7,35 +7,35 @@
*/ */
export default class TradeBotRespondRequest { export default class TradeBotRespondRequest {
constructor() { constructor() {
// ... // ...
} }
createTransaction(txnReq) { createTransaction(txnReq) {
this.atAddress(txnReq.atAddress) this.atAddress(txnReq.atAddress);
this.foreignKey(txnReq.foreignKey) this.foreignKey(txnReq.foreignKey);
this.receivingAddress(txnReq.receivingAddress) this.receivingAddress(txnReq.receivingAddress);
return this.txnRequest() return this.txnRequest();
} }
atAddress(atAddress) { atAddress(atAddress) {
this._atAddress = atAddress this._atAddress = atAddress;
} }
foreignKey(foreignKey) { foreignKey(foreignKey) {
this._foreignKey = foreignKey this._foreignKey = foreignKey;
} }
receivingAddress(receivingAddress) { receivingAddress(receivingAddress) {
this._receivingAddress = receivingAddress this._receivingAddress = receivingAddress;
} }
txnRequest() { txnRequest() {
return { return {
atAddress: this._atAddress, atAddress: this._atAddress,
foreignKey: this._foreignKey, foreignKey: this._foreignKey,
receivingAddress: this._receivingAddress receivingAddress: this._receivingAddress,
} };
} }
} }

View File

@ -1,165 +1,188 @@
// @ts-nocheck // @ts-nocheck
import nacl from '../deps/nacl-fast' import nacl from '../deps/nacl-fast';
import Base58 from '../deps/Base58' import Base58 from '../deps/Base58';
import utils from '../utils/utils' import utils from '../utils/utils';
import { QORT_DECIMALS, TX_TYPES } from '../constants/constants.js' import { QORT_DECIMALS, TX_TYPES } from '../constants/constants.js';
export default class TransactionBase { export default class TransactionBase {
static get utils() { static get utils() {
return utils return utils;
} }
static get nacl() { static get nacl() {
return nacl return nacl;
} }
static get Base58() { static get Base58() {
return Base58 return Base58;
} }
constructor() { constructor() {
this.fee = 0 this.fee = 0;
this.groupID = 0 this.groupID = 0;
this.timestamp = Date.now() this.timestamp = Date.now();
this.tests = [ this.tests = [
() => { () => {
if (!(this._type >= 1 && this._type in TX_TYPES)) { if (!(this._type >= 1 && this._type in TX_TYPES)) {
return 'Invalid type: ' + this.type return 'Invalid type: ' + this.type;
} }
return true return true;
}, },
() => { () => {
if (this._fee < 0) { if (this._fee < 0) {
return 'Invalid fee: ' + this._fee / QORT_DECIMALS return 'Invalid fee: ' + this._fee / QORT_DECIMALS;
} }
return true return true;
}, },
() => { () => {
if (this._groupID < 0 || !Number.isInteger(this._groupID)) { if (this._groupID < 0 || !Number.isInteger(this._groupID)) {
return 'Invalid groupID: ' + this._groupID return 'Invalid groupID: ' + this._groupID;
} }
return true return true;
}, },
() => { () => {
if (!(new Date(this._timestamp)).getTime() > 0) { if (!new Date(this._timestamp).getTime() > 0) {
return 'Invalid timestamp: ' + this._timestamp return 'Invalid timestamp: ' + this._timestamp;
} }
return true return true;
}, },
() => { () => {
if (!(this._lastReference instanceof Uint8Array && this._lastReference.byteLength == 64)) { if (
if (this._lastReference == 0) { !(
return 'Invalid last reference. Please ensure that you have at least 0.001 QORT for the transaction fee.' this._lastReference instanceof Uint8Array &&
} this._lastReference.byteLength == 64
return 'Invalid last reference: ' + this._lastReference )
} ) {
return true if (this._lastReference == 0) {
}, return 'Invalid last reference. Please ensure that you have at least 0.001 QORT for the transaction fee.';
() => { }
if (!(this._keyPair)) { return 'Invalid last reference: ' + this._lastReference;
return 'keyPair must be specified' }
} return true;
if (!(this._keyPair.publicKey instanceof Uint8Array && this._keyPair.publicKey.byteLength === 32)) { },
return 'Invalid publicKey' () => {
} if (!this._keyPair) {
if (!(this._keyPair.privateKey instanceof Uint8Array && this._keyPair.privateKey.byteLength === 64)) { return 'keyPair must be specified';
return 'Invalid privateKey' }
} if (
return true !(
} this._keyPair.publicKey instanceof Uint8Array &&
] this._keyPair.publicKey.byteLength === 32
} )
) {
return 'Invalid publicKey';
}
if (
!(
this._keyPair.privateKey instanceof Uint8Array &&
this._keyPair.privateKey.byteLength === 64
)
) {
return 'Invalid privateKey';
}
return true;
},
];
}
set keyPair(keyPair) { set keyPair(keyPair) {
this._keyPair = keyPair this._keyPair = keyPair;
} }
set type(type) { set type(type) {
this.typeText = TX_TYPES[type] this.typeText = TX_TYPES[type];
this._type = type this._type = type;
this._typeBytes = this.constructor.utils.int32ToBytes(this._type) this._typeBytes = this.constructor.utils.int32ToBytes(this._type);
} }
set groupID(groupID) { set groupID(groupID) {
this._groupID = groupID this._groupID = groupID;
this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID) this._groupIDBytes = this.constructor.utils.int32ToBytes(this._groupID);
} }
set timestamp(timestamp) { set timestamp(timestamp) {
this._timestamp = timestamp this._timestamp = timestamp;
this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp) this._timestampBytes = this.constructor.utils.int64ToBytes(this._timestamp);
} }
set fee(fee) { set fee(fee) {
this._fee = fee * QORT_DECIMALS this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
} }
set lastReference(lastReference) { set lastReference(lastReference) {
this._lastReference = lastReference instanceof Uint8Array ? lastReference : this.constructor.Base58.decode(lastReference) this._lastReference =
} lastReference instanceof Uint8Array
? lastReference
: this.constructor.Base58.decode(lastReference);
}
get params() { get params() {
return [ return [
this._typeBytes, this._typeBytes,
this._timestampBytes, this._timestampBytes,
this._groupIDBytes, this._groupIDBytes,
this._lastReference, this._lastReference,
this._keyPair.publicKey this._keyPair.publicKey,
] ];
} }
get signedBytes() { get signedBytes() {
if (!this._signedBytes) { if (!this._signedBytes) {
this.sign() this.sign();
} }
return this._signedBytes return this._signedBytes;
} }
validParams() { validParams() {
let finalResult = { let finalResult = {
valid: true valid: true,
} };
this.tests.some(test => { this.tests.some((test) => {
const result = test() const result = test();
if (result !== true) { if (result !== true) {
finalResult = { finalResult = {
valid: false, valid: false,
message: result message: result,
} };
return true // exists the loop return true; // exists the loop
} }
}) });
return finalResult return finalResult;
} }
generateBase() { generateBase() {
const isValid = this.validParams() const isValid = this.validParams();
if (!isValid.valid) { if (!isValid.valid) {
throw new Error(isValid.message) throw new Error(isValid.message);
} }
let result = new Uint8Array() let result = new Uint8Array();
this.params.forEach(item => { this.params.forEach((item) => {
result = this.constructor.utils.appendBuffer(result, item) result = this.constructor.utils.appendBuffer(result, item);
}) });
this._base = result this._base = result;
return result return result;
} }
sign() { sign() {
if (!this._keyPair) { if (!this._keyPair) {
throw new Error('keyPair not defined') throw new Error('keyPair not defined');
} }
if (!this._base) { if (!this._base) {
this.generateBase() this.generateBase();
} }
this._signature = this.constructor.nacl.sign.detached(this._base, this._keyPair.privateKey) this._signature = this.constructor.nacl.sign.detached(
this._base,
this._keyPair.privateKey
);
this._signedBytes = this.constructor.utils.appendBuffer(this._base, this._signature) this._signedBytes = this.constructor.utils.appendBuffer(
this._base,
this._signature
);
return this._signature return this._signature;
} }
} }

View File

@ -1,35 +1,37 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants' import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from './TransactionBase' import TransactionBase from './TransactionBase';
export default class TransferAssetTransaction extends TransactionBase { export default class TransferAssetTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 12 this.type = 12;
} }
set recipient(recipient) { set recipient(recipient) {
this._recipient = recipient instanceof Uint8Array ? recipient : this.constructor.Base58.decode(recipient) this._recipient =
recipient instanceof Uint8Array
? recipient
: this.constructor.Base58.decode(recipient);
} }
set amount(amount) { set amount(amount) {
this._amount = Math.round(amount * QORT_DECIMALS) this._amount = Math.round(amount * QORT_DECIMALS);
this._amountBytes = this.constructor.utils.int64ToBytes(this._amount) this._amountBytes = this.constructor.utils.int64ToBytes(this._amount);
} }
set assetId(assetId) { set assetId(assetId) {
this._assetId = this.constructor.utils.int64ToBytes(assetId) this._assetId = this.constructor.utils.int64ToBytes(assetId);
} }
get params() { get params() {
const params = super.params const params = super.params;
params.push( params.push(
this._recipient, this._recipient,
this._assetId, this._assetId,
this._amountBytes, this._amountBytes,
this._feeBytes this._feeBytes
) );
return params return params;
} }
} }

View File

@ -1,62 +1,64 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants';
import { QORT_DECIMALS } from "../constants/constants"; import TransactionBase from './TransactionBase';
import TransactionBase from "./TransactionBase";
export default class UpdateGroupTransaction extends TransactionBase { export default class UpdateGroupTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 23 this.type = 23;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set newOwner(newOwner) {
this._newOwner =
newOwner instanceof Uint8Array
? newOwner
: this.constructor.Base58.decode(newOwner);
}
set newIsOpen(newIsOpen) {
this._rGroupType = new Uint8Array(1);
this._rGroupType[0] = newIsOpen;
}
set newDescription(newDescription) {
this._rGroupDescBytes = this.constructor.utils.stringtoUTF8Array(
newDescription.toLocaleLowerCase()
);
this._rGroupDescLength = this.constructor.utils.int32ToBytes(
this._rGroupDescBytes.length
);
}
set newApprovalThreshold(newApprovalThreshold) {
this._rGroupApprovalThreshold = new Uint8Array(1);
this._rGroupApprovalThreshold[0] = newApprovalThreshold;
}
set newMinimumBlockDelay(newMinimumBlockDelay) {
this._rGroupMinimumBlockDelayBytes =
this.constructor.utils.int32ToBytes(newMinimumBlockDelay);
}
set newMaximumBlockDelay(newMaximumBlockDelay) {
this._rGroupMaximumBlockDelayBytes =
this.constructor.utils.int32ToBytes(newMaximumBlockDelay);
}
set _groupId(_groupId) {
this._groupBytes = this.constructor.utils.int32ToBytes(_groupId);
set fee(fee) { }
this._fee = fee * QORT_DECIMALS get params() {
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) const params = super.params;
} params.push(
set newOwner(newOwner) { this._groupBytes,
this._newOwner = newOwner instanceof Uint8Array ? newOwner : this.constructor.Base58.decode(newOwner) this._newOwner,
} this._rGroupDescLength,
set newIsOpen(newIsOpen) { this._rGroupDescBytes,
this._rGroupType,
this._rGroupType = new Uint8Array(1) this._rGroupApprovalThreshold,
this._rGroupType[0] = newIsOpen this._rGroupMinimumBlockDelayBytes,
} this._rGroupMaximumBlockDelayBytes,
set newDescription(newDescription) { this._feeBytes
this._rGroupDescBytes = this.constructor.utils.stringtoUTF8Array(newDescription.toLocaleLowerCase()) );
this._rGroupDescLength = this.constructor.utils.int32ToBytes(this._rGroupDescBytes.length) return params;
} }
set newApprovalThreshold(newApprovalThreshold) {
this._rGroupApprovalThreshold = new Uint8Array(1)
this._rGroupApprovalThreshold[0] = newApprovalThreshold;
}
set newMinimumBlockDelay(newMinimumBlockDelay) {
this._rGroupMinimumBlockDelayBytes = this.constructor.utils.int32ToBytes(newMinimumBlockDelay)
}
set newMaximumBlockDelay(newMaximumBlockDelay) {
this._rGroupMaximumBlockDelayBytes = this.constructor.utils.int32ToBytes(newMaximumBlockDelay)
}
set _groupId(_groupId){
this._groupBytes = this.constructor.utils.int32ToBytes(_groupId)
}
get params() {
const params = super.params
params.push(
this._groupBytes,
this._newOwner,
this._rGroupDescLength,
this._rGroupDescBytes,
this._rGroupType,
this._rGroupApprovalThreshold,
this._rGroupMinimumBlockDelayBytes,
this._rGroupMaximumBlockDelayBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,51 +1,56 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from "../constants/constants" import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from "./TransactionBase" import TransactionBase from './TransactionBase';
export default class UpdateNameTransaction extends TransactionBase { export default class UpdateNameTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 4 this.type = 4;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set name(name) {
this.nameText = name;
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name);
this._nameLength = this.constructor.utils.int32ToBytes(
this._nameBytes.length
);
}
set fee(fee) { set newName(newName) {
this._fee = fee * QORT_DECIMALS this.newNameText = newName;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._newNameBytes = this.constructor.utils.stringtoUTF8Array(newName);
} this._newNameLength = this.constructor.utils.int32ToBytes(
this._newNameBytes.length
);
}
set name(name) { set newData(newData) {
this.nameText = name this.newDataText =
this._nameBytes = this.constructor.utils.stringtoUTF8Array(name) newData.length === 0 ? 'Registered Name on the Qortal Chain' : newData;
this._nameLength = this.constructor.utils.int32ToBytes(this._nameBytes.length) this._newDataBytes = this.constructor.utils.stringtoUTF8Array(
} this.newDataText
);
this._newDataLength = this.constructor.utils.int32ToBytes(
this._newDataBytes.length
);
}
set newName(newName) { get params() {
this.newNameText = newName const params = super.params;
this._newNameBytes = this.constructor.utils.stringtoUTF8Array(newName) params.push(
this._newNameLength = this.constructor.utils.int32ToBytes(this._newNameBytes.length) this._nameLength,
} this._nameBytes,
this._newNameLength,
set newData(newData) { this._newNameBytes,
this.newDataText = newData.length === 0 ? "Registered Name on the Qortal Chain" : newData this._newDataLength,
this._newDataBytes = this.constructor.utils.stringtoUTF8Array(this.newDataText) this._newDataBytes,
this._newDataLength = this.constructor.utils.int32ToBytes(this._newDataBytes.length) this._feeBytes
} );
return params;
get params() { }
const params = super.params
params.push(
this._nameLength,
this._nameBytes,
this._newNameLength,
this._newNameBytes,
this._newDataLength,
this._newDataBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,38 +1,42 @@
// @ts-nocheck // @ts-nocheck
import { QORT_DECIMALS } from '../constants/constants' import { QORT_DECIMALS } from '../constants/constants';
import TransactionBase from './TransactionBase' import TransactionBase from './TransactionBase';
export default class VoteOnPollTransaction extends TransactionBase { export default class VoteOnPollTransaction extends TransactionBase {
constructor() { constructor() {
super() super();
this.type = 9 this.type = 9;
} }
set fee(fee) {
this._fee = fee * QORT_DECIMALS;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee);
}
set fee(fee) { set rPollName(rPollName) {
this._fee = fee * QORT_DECIMALS this._rPollName = rPollName;
this._feeBytes = this.constructor.utils.int64ToBytes(this._fee) this._rPollNameBytes = this.constructor.utils.stringtoUTF8Array(
} this._rPollName
);
this._rPollNameLength = this.constructor.utils.int32ToBytes(
this._rPollNameBytes.length
);
}
set rPollName(rPollName) { set rOptionIndex(rOptionIndex) {
this._rPollName = rPollName this._rOptionIndex = rOptionIndex;
this._rPollNameBytes = this.constructor.utils.stringtoUTF8Array(this._rPollName) this._rOptionIndexBytes = this.constructor.utils.int32ToBytes(
this._rPollNameLength = this.constructor.utils.int32ToBytes(this._rPollNameBytes.length) this._rOptionIndex
} );
}
set rOptionIndex(rOptionIndex) { get params() {
this._rOptionIndex = rOptionIndex const params = super.params;
this._rOptionIndexBytes = this.constructor.utils.int32ToBytes(this._rOptionIndex) params.push(
} this._rPollNameLength,
this._rPollNameBytes,
get params() { this._rOptionIndexBytes,
const params = super.params this._feeBytes
params.push( );
this._rPollNameLength, return params;
this._rPollNameBytes, }
this._rOptionIndexBytes,
this._feeBytes
)
return params
}
} }

View File

@ -1,39 +1,40 @@
// @ts-nocheck // @ts-nocheck
import nacl from '../deps/nacl-fast' import nacl from '../deps/nacl-fast';
import utils from '../utils/utils' import utils from '../utils/utils';
export const signChat = (chatBytes, nonce, keyPair) => { export const signChat = (chatBytes, nonce, keyPair) => {
if (!chatBytes) { if (!chatBytes) {
throw new Error('Chat Bytes not defined') throw new Error('Chat Bytes not defined');
} }
if (!nonce) { if (!nonce) {
throw new Error('Nonce not defined') throw new Error('Nonce not defined');
} }
if (!keyPair) { if (!keyPair) {
throw new Error('keyPair not defined') throw new Error('keyPair not defined');
} }
const _nonce = utils.int32ToBytes(nonce) const _nonce = utils.int32ToBytes(nonce);
if (chatBytes.length === undefined) { if (chatBytes.length === undefined) {
const _chatBytesBuffer = Object.keys(chatBytes).map(function (key) { return chatBytes[key]; }) const _chatBytesBuffer = Object.keys(chatBytes).map(function (key) {
return chatBytes[key];
});
const chatBytesBuffer = new Uint8Array(_chatBytesBuffer) const chatBytesBuffer = new Uint8Array(_chatBytesBuffer);
chatBytesBuffer.set(_nonce, 112) chatBytesBuffer.set(_nonce, 112);
const signature = nacl.sign.detached(chatBytesBuffer, keyPair.privateKey) const signature = nacl.sign.detached(chatBytesBuffer, keyPair.privateKey);
return utils.appendBuffer(chatBytesBuffer, signature) return utils.appendBuffer(chatBytesBuffer, signature);
} else { } else {
const chatBytesBuffer = new Uint8Array(chatBytes) const chatBytesBuffer = new Uint8Array(chatBytes);
chatBytesBuffer.set(_nonce, 112) chatBytesBuffer.set(_nonce, 112);
const signature = nacl.sign.detached(chatBytesBuffer, keyPair.privateKey) const signature = nacl.sign.detached(chatBytesBuffer, keyPair.privateKey);
return utils.appendBuffer(chatBytesBuffer, signature)
}
}
return utils.appendBuffer(chatBytesBuffer, signature);
}
};

View File

@ -1,30 +1,31 @@
// @ts-nocheck // @ts-nocheck
import nacl from '../deps/nacl-fast';
import nacl from '../deps/nacl-fast' import Base58 from '../deps/Base58';
import Base58 from '../deps/Base58' import utils from '../utils/utils';
import utils from '../utils/utils'
const signTradeBotTransaction = async (unsignedTxn, keyPair) => { const signTradeBotTransaction = async (unsignedTxn, keyPair) => {
if (!unsignedTxn) { if (!unsignedTxn) {
throw new Error('Unsigned Transaction Bytes not defined') throw new Error('Unsigned Transaction Bytes not defined');
} }
if (!keyPair) { if (!keyPair) {
throw new Error('keyPair not defined') throw new Error('keyPair not defined');
} }
const txnBuffer = Base58.decode(unsignedTxn) const txnBuffer = Base58.decode(unsignedTxn);
if (keyPair.privateKey.length === undefined) { if (keyPair.privateKey.length === undefined) {
const _privateKey = Object.keys(keyPair.privateKey).map(function (key) { return keyPair.privateKey[key] }) const _privateKey = Object.keys(keyPair.privateKey).map(function (key) {
const privateKey = new Uint8Array(_privateKey) return keyPair.privateKey[key];
const signature = nacl.sign.detached(txnBuffer, privateKey) });
return utils.appendBuffer(txnBuffer, signature) const privateKey = new Uint8Array(_privateKey);
} else { const signature = nacl.sign.detached(txnBuffer, privateKey);
const signature = nacl.sign.detached(txnBuffer, keyPair.privateKey) return utils.appendBuffer(txnBuffer, signature);
return utils.appendBuffer(txnBuffer, signature) } else {
} const signature = nacl.sign.detached(txnBuffer, keyPair.privateKey);
} return utils.appendBuffer(txnBuffer, signature);
}
};
export default signTradeBotTransaction export default signTradeBotTransaction;

View File

@ -1,68 +1,65 @@
// @ts-nocheck // @ts-nocheck
import PaymentTransaction from './PaymentTransaction.js' import PaymentTransaction from './PaymentTransaction.js';
import ChatTransaction from './ChatTransaction.js' import ChatTransaction from './ChatTransaction.js';
import GroupChatTransaction from './GroupChatTransaction.js' import GroupChatTransaction from './GroupChatTransaction.js';
import GroupInviteTransaction from './GroupInviteTransaction.js' import GroupInviteTransaction from './GroupInviteTransaction.js';
import CancelGroupInviteTransaction from './CancelGroupInviteTransaction.js' import CancelGroupInviteTransaction from './CancelGroupInviteTransaction.js';
import GroupKickTransaction from './GroupKickTransaction.js' import GroupKickTransaction from './GroupKickTransaction.js';
import GroupBanTransaction from './GroupBanTransaction.js' import GroupBanTransaction from './GroupBanTransaction.js';
import CancelGroupBanTransaction from './CancelGroupBanTransaction.js' import CancelGroupBanTransaction from './CancelGroupBanTransaction.js';
import CreateGroupTransaction from './CreateGroupTransaction.js' import CreateGroupTransaction from './CreateGroupTransaction.js';
import LeaveGroupTransaction from './LeaveGroupTransaction.js' import LeaveGroupTransaction from './LeaveGroupTransaction.js';
import JoinGroupTransaction from './JoinGroupTransaction.js' import JoinGroupTransaction from './JoinGroupTransaction.js';
import AddGroupAdminTransaction from './AddGroupAdminTransaction.js' import AddGroupAdminTransaction from './AddGroupAdminTransaction.js';
import RemoveGroupAdminTransaction from './RemoveGroupAdminTransaction.js' import RemoveGroupAdminTransaction from './RemoveGroupAdminTransaction.js';
import RegisterNameTransaction from './RegisterNameTransaction.js' import RegisterNameTransaction from './RegisterNameTransaction.js';
import VoteOnPollTransaction from './VoteOnPollTransaction.js' import VoteOnPollTransaction from './VoteOnPollTransaction.js';
import CreatePollTransaction from './CreatePollTransaction.js' import CreatePollTransaction from './CreatePollTransaction.js';
import DeployAtTransaction from './DeployAtTransaction.js' import DeployAtTransaction from './DeployAtTransaction.js';
import RewardShareTransaction from './RewardShareTransaction.js' import RewardShareTransaction from './RewardShareTransaction.js';
import RemoveRewardShareTransaction from './RemoveRewardShareTransaction.js' import RemoveRewardShareTransaction from './RemoveRewardShareTransaction.js';
import UpdateNameTransaction from './UpdateNameTransaction.js' import UpdateNameTransaction from './UpdateNameTransaction.js';
import UpdateGroupTransaction from './UpdateGroupTransaction.js' import UpdateGroupTransaction from './UpdateGroupTransaction.js';
import SellNameTransacion from './SellNameTransacion.js' import SellNameTransacion from './SellNameTransacion.js';
import CancelSellNameTransacion from './CancelSellNameTransacion.js' import CancelSellNameTransacion from './CancelSellNameTransacion.js';
import BuyNameTransacion from './BuyNameTransacion.js' import BuyNameTransacion from './BuyNameTransacion.js';
import TransferAssetTransaction from './TransferAssetTransaction.js' import TransferAssetTransaction from './TransferAssetTransaction.js';
export const transactionTypes = { export const transactionTypes = {
2: PaymentTransaction, 2: PaymentTransaction,
3: RegisterNameTransaction, 3: RegisterNameTransaction,
4: UpdateNameTransaction, 4: UpdateNameTransaction,
5: SellNameTransacion, 5: SellNameTransacion,
6: CancelSellNameTransacion, 6: CancelSellNameTransacion,
7: BuyNameTransacion, 7: BuyNameTransacion,
8: CreatePollTransaction, 8: CreatePollTransaction,
9: VoteOnPollTransaction, 9: VoteOnPollTransaction,
12: TransferAssetTransaction, 12: TransferAssetTransaction,
16: DeployAtTransaction, 16: DeployAtTransaction,
18: ChatTransaction, 18: ChatTransaction,
181: GroupChatTransaction, 181: GroupChatTransaction,
22: CreateGroupTransaction, 22: CreateGroupTransaction,
23: UpdateGroupTransaction, 23: UpdateGroupTransaction,
24: AddGroupAdminTransaction, 24: AddGroupAdminTransaction,
25: RemoveGroupAdminTransaction, 25: RemoveGroupAdminTransaction,
26: GroupBanTransaction, 26: GroupBanTransaction,
27: CancelGroupBanTransaction, 27: CancelGroupBanTransaction,
28: GroupKickTransaction, 28: GroupKickTransaction,
29: GroupInviteTransaction, 29: GroupInviteTransaction,
30: CancelGroupInviteTransaction, 30: CancelGroupInviteTransaction,
31: JoinGroupTransaction, 31: JoinGroupTransaction,
32: LeaveGroupTransaction, 32: LeaveGroupTransaction,
38: RewardShareTransaction, 38: RewardShareTransaction,
381: RemoveRewardShareTransaction 381: RemoveRewardShareTransaction,
} };
export const createTransaction = (type, keyPair, params) => { export const createTransaction = (type, keyPair, params) => {
const tx = new transactionTypes[type]() const tx = new transactionTypes[type]();
tx.keyPair = keyPair tx.keyPair = keyPair;
Object.keys(params).forEach(param => { Object.keys(params).forEach((param) => {
tx[param] = params[param];
});
tx[param] = params[param] return tx;
}) };
return tx
}

View File

@ -17,7 +17,6 @@ export function decodeIfEncoded(input) {
export const isValidBase64 = (str: string): boolean => { export const isValidBase64 = (str: string): boolean => {
if (typeof str !== 'string' || str.length % 4 !== 0) return false; if (typeof str !== 'string' || str.length % 4 !== 0) return false;
const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/; const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
return base64Regex.test(str); return base64Regex.test(str);
}; };

View File

@ -5,119 +5,123 @@ import { doInitWorkers, kdf } from '../../deps/kdf';
import PhraseWallet from './phrase-wallet'; import PhraseWallet from './phrase-wallet';
import * as WORDLISTS from './wordlists'; import * as WORDLISTS from './wordlists';
import FileSaver from 'file-saver'; import FileSaver from 'file-saver';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem'; import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { mimeToExtensionMap } from '../memeTypes'; import { mimeToExtensionMap } from '../memeTypes';
export function generateRandomSentence(template = 'adverb verb noun adjective noun adverb verb noun adjective noun adjective verbed adjective noun', maxWordLength = 0, capitalize = true) {
const partsOfSpeechMap = {
'noun': 'nouns',
'adverb': 'adverbs',
'adv': 'adverbs',
'verb': 'verbs',
'interjection': 'interjections',
'adjective': 'adjectives',
'adj': 'adjectives',
'verbed': 'verbed'
};
let _wordlists = WORDLISTS; export function generateRandomSentence(
template = 'adverb verb noun adjective noun adverb verb noun adjective noun adjective verbed adjective noun',
function _RNG(entropy) { maxWordLength = 0,
if (entropy > 1074) { capitalize = true
throw new Error('Javascript can not handle that much entropy!'); ) {
} const partsOfSpeechMap = {
let randNum = 0; noun: 'nouns',
const crypto = window.crypto || window.msCrypto; adverb: 'adverbs',
adv: 'adverbs',
if (crypto) { verb: 'verbs',
const entropy256 = Math.ceil(entropy / 8); interjection: 'interjections',
let buffer = new Uint8Array(entropy256); adjective: 'adjectives',
crypto.getRandomValues(buffer); adj: 'adjectives',
randNum = buffer.reduce((num, value) => num * 256 + value, 0) / Math.pow(256, entropy256); verbed: 'verbed',
} else {
console.warn('Secure RNG not found. Using Math.random');
randNum = Math.random();
}
return randNum;
}
function _capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getWord(partOfSpeech) {
let words = _wordlists[partsOfSpeechMap[partOfSpeech]];
if (maxWordLength) {
words = words.filter(word => word.length <= maxWordLength);
}
const requiredEntropy = Math.log(words.length) / Math.log(2);
const index = Math.floor(_RNG(requiredEntropy) * words.length);
return words[index];
}
function parse(template) {
return template.split(/\s+/).map(token => {
const match = token.match(/^(\w+)(.*)$/);
if (!match) return token; // No match, return original token
const [ , partOfSpeech, rest ] = match;
if (partsOfSpeechMap[partOfSpeech]) {
let word = getWord(partOfSpeech);
if (capitalize && token === token[0].toUpperCase() + token.slice(1).toLowerCase()) {
word = _capitalize(word);
}
return word + rest;
}
return token;
}).join(' ');
}
return parse(template);
}
export const createAccount = async(generatedSeedPhrase)=> {
if(!generatedSeedPhrase) throw new Error('No generated seed-phrase')
const threads = doInitWorkers(crypto.kdfThreads)
const seed = await kdf(generatedSeedPhrase, void 0, threads)
const wallet = new PhraseWallet(seed, walletVersion)
return wallet
}
const hasExtension = (filename) => {
return filename.includes(".") && filename.split(".").pop().length > 0;
}; };
export const saveFileToDisk = async (data, qortAddress) => { let _wordlists = WORDLISTS;
const dataString = JSON.stringify(data); function _RNG(entropy) {
const blob = new Blob([dataString], { type: 'application/json' }); if (entropy > 1074) {
const fileName = "qortal_backup_" + qortAddress + ".json"; throw new Error('Javascript can not handle that much entropy!');
}
let randNum = 0;
const crypto = window.crypto || window.msCrypto;
await FileSaver.saveAs(blob, fileName); if (crypto) {
const entropy256 = Math.ceil(entropy / 8);
let buffer = new Uint8Array(entropy256);
crypto.getRandomValues(buffer);
randNum =
buffer.reduce((num, value) => num * 256 + value, 0) /
Math.pow(256, entropy256);
} else {
console.warn('Secure RNG not found. Using Math.random');
randNum = Math.random();
}
return randNum;
}
function _capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getWord(partOfSpeech) {
let words = _wordlists[partsOfSpeechMap[partOfSpeech]];
if (maxWordLength) {
words = words.filter((word) => word.length <= maxWordLength);
}
const requiredEntropy = Math.log(words.length) / Math.log(2);
const index = Math.floor(_RNG(requiredEntropy) * words.length);
return words[index];
}
function parse(template) {
return template
.split(/\s+/)
.map((token) => {
const match = token.match(/^(\w+)(.*)$/);
if (!match) return token; // No match, return original token
const [, partOfSpeech, rest] = match;
if (partsOfSpeechMap[partOfSpeech]) {
let word = getWord(partOfSpeech);
if (
capitalize &&
token === token[0].toUpperCase() + token.slice(1).toLowerCase()
) {
word = _capitalize(word);
}
return word + rest;
}
return token;
})
.join(' ');
}
return parse(template);
} }
export const createAccount = async (generatedSeedPhrase) => {
if (!generatedSeedPhrase) throw new Error('No generated seed-phrase');
const threads = doInitWorkers(crypto.kdfThreads);
const seed = await kdf(generatedSeedPhrase, void 0, threads);
const wallet = new PhraseWallet(seed, walletVersion);
return wallet;
};
const hasExtension = (filename) => {
return filename.includes('.') && filename.split('.').pop().length > 0;
};
export const saveFileToDisk = async (data, qortAddress) => {
const dataString = JSON.stringify(data);
const blob = new Blob([dataString], { type: 'application/json' });
const fileName = 'qortal_backup_' + qortAddress + '.json';
await FileSaver.saveAs(blob, fileName);
};
export const saveFileToDiskGeneric = async (blob, filename) => { export const saveFileToDiskGeneric = async (blob, filename) => {
const timestamp = new Date() const timestamp = new Date().toISOString().replace(/:/g, '-'); // Safe timestamp for filenames
.toISOString()
.replace(/:/g, "-"); // Safe timestamp for filenames
const fileExtension = mimeToExtensionMap[blob.type] const fileExtension = mimeToExtensionMap[blob.type];
let fileName = filename || "qortal_file_" + timestamp + "." + fileExtension; let fileName = filename || 'qortal_file_' + timestamp + '.' + fileExtension;
fileName = hasExtension(fileName) ? fileName : fileName + "." + fileExtension; fileName = hasExtension(fileName) ? fileName : fileName + '.' + fileExtension;
await FileSaver.saveAs(blob, fileName); await FileSaver.saveAs(blob, fileName);
};
}
export const saveSeedPhraseToDisk = async (data) => { export const saveSeedPhraseToDisk = async (data) => {
const blob = new Blob([data], { type: 'text/plain;charset=utf-8' });
const fileName = 'qortal_seedphrase.txt';
const blob = new Blob([data], { type: 'text/plain;charset=utf-8' }) await FileSaver.saveAs(blob, fileName);
const fileName = "qortal_seedphrase.txt" };
await FileSaver.saveAs(blob, fileName);
}

View File

@ -1,31 +1,37 @@
// @ts-nocheck // @ts-nocheck
import {AES_CBC, HmacSha512} from 'asmcrypto.js' import { AES_CBC, HmacSha512 } from 'asmcrypto.js';
import Base58 from '../../deps/Base58';
import { doInitWorkers, kdf } from '../../deps/kdf.js';
import { crypto as cryptoVals } from '../../constants/decryptWallet.js';
import Base58 from '../../deps/Base58' const getRandomValues = crypto
import { doInitWorkers, kdf } from '../../deps/kdf.js' ? crypto.getRandomValues.bind(crypto)
import { crypto as cryptoVals } from '../../constants/decryptWallet.js' : msCrypto.getRandomValues.bind(msCrypto);
const getRandomValues = crypto ? crypto.getRandomValues.bind(crypto) : msCrypto.getRandomValues.bind(msCrypto)
export const generateSaveWalletData = async (wallet, password, kdfThreads) => { export const generateSaveWalletData = async (wallet, password, kdfThreads) => {
const threads = doInitWorkers(cryptoVals.kdfThreads) const threads = doInitWorkers(cryptoVals.kdfThreads);
let iv = new Uint8Array(16) let iv = new Uint8Array(16);
getRandomValues(iv) getRandomValues(iv);
let salt = new Uint8Array(32) let salt = new Uint8Array(32);
getRandomValues(salt) getRandomValues(salt);
const key = await kdf(password, salt, threads) const key = await kdf(password, salt, threads);
const encryptionKey = key.slice(0, 32) const encryptionKey = key.slice(0, 32);
const macKey = key.slice(32, 63) const macKey = key.slice(32, 63);
const encryptedSeed = AES_CBC.encrypt(wallet._byteSeed, encryptionKey, false, iv) const encryptedSeed = AES_CBC.encrypt(
const mac = new HmacSha512(macKey).process(encryptedSeed).finish().result wallet._byteSeed,
return { encryptionKey,
address0: wallet._addresses[0].address, false,
encryptedSeed: Base58.encode(encryptedSeed), iv
salt: Base58.encode(salt), );
iv: Base58.encode(iv), const mac = new HmacSha512(macKey).process(encryptedSeed).finish().result;
version: wallet._walletVersion, return {
mac: Base58.encode(mac), address0: wallet._addresses[0].address,
kdfThreads encryptedSeed: Base58.encode(encryptedSeed),
} salt: Base58.encode(salt),
} iv: Base58.encode(iv),
version: wallet._walletVersion,
mac: Base58.encode(mac),
kdfThreads,
};
};

View File

@ -2,36 +2,36 @@
// @ts-nocheck // @ts-nocheck
export const EXCEPTIONS = { export const EXCEPTIONS = {
'are': 'were', are: 'were',
'eat': 'ate', eat: 'ate',
'go': 'went', go: 'went',
'have': 'had', have: 'had',
'inherit': 'inherited', inherit: 'inherited',
'is': 'was', is: 'was',
'run': 'ran', run: 'ran',
'sit': 'sat', sit: 'sat',
'visit': 'visited' visit: 'visited',
} };
export const getPastTense = (verb, exceptions = EXCEPTIONS) => { export const getPastTense = (verb, exceptions = EXCEPTIONS) => {
if (exceptions[verb]) { if (exceptions[verb]) {
return exceptions[verb] return exceptions[verb];
} }
if ((/e$/i).test(verb)) { if (/e$/i.test(verb)) {
return verb + 'd' return verb + 'd';
} }
if ((/[aeiou]c$/i).test(verb)) { if (/[aeiou]c$/i.test(verb)) {
return verb + 'ked' return verb + 'ked';
} }
// for american english only // for american english only
if ((/el$/i).test(verb)) { if (/el$/i.test(verb)) {
return verb + 'ed' return verb + 'ed';
} }
if ((/[aeio][aeiou][dlmnprst]$/).test(verb)) { if (/[aeio][aeiou][dlmnprst]$/.test(verb)) {
return verb + 'ed' return verb + 'ed';
} }
if ((/[aeiou][bdglmnprst]$/i).test(verb)) { if (/[aeiou][bdglmnprst]$/i.test(verb)) {
return verb.replace(/(.+[aeiou])([bdglmnprst])/, '$1$2$2ed') return verb.replace(/(.+[aeiou])([bdglmnprst])/, '$1$2$2ed');
} }
return verb + 'ed' return verb + 'ed';
} };

View File

@ -1,12 +1,12 @@
export function convertQortalLinks(inputHtml: string) { export function convertQortalLinks(inputHtml: string) {
// Regular expression to match 'qortal://...' URLs. // Regular expression to match 'qortal://...' URLs.
// This will stop at the first whitespace, comma, or HTML tag // This will stop at the first whitespace, comma, or HTML tag
var regex = /(qortal:\/\/[^\s,<]+)/g; var regex = /(qortal:\/\/[^\s,<]+)/g;
// Replace matches in inputHtml with formatted anchor tag // Replace matches in inputHtml with formatted anchor tag
var outputHtml = inputHtml.replace(regex, function (match) { var outputHtml = inputHtml.replace(regex, function (match) {
return `<a href="${match}" class="qortal-link">${match}</a>`; return `<a href="${match}" class="qortal-link">${match}</a>`;
}); });
return outputHtml; return outputHtml;
} }

View File

@ -1,173 +1,182 @@
// Author: irontiga <irontiga@gmail.com> // Author: irontiga <irontiga@gmail.com>
import { html, LitElement, css } from 'lit' import { html, LitElement, css } from 'lit';
import * as WORDLISTS from './wordList' import * as WORDLISTS from './wordList';
class RandomSentenceGenerator extends LitElement { class RandomSentenceGenerator extends LitElement {
static get properties() { static get properties() {
return { return {
template: { type: String, attribute: 'template' }, template: { type: String, attribute: 'template' },
parsedString: { type: String }, parsedString: { type: String },
fetchedWordlistCount: { type: Number, value: 0 }, fetchedWordlistCount: { type: Number, value: 0 },
capitalize: { type: Boolean }, capitalize: { type: Boolean },
partsOfSpeechMap: { type: Object }, partsOfSpeechMap: { type: Object },
templateEntropy: { type: Number, reflect: true, attribute: 'template-entropy' }, templateEntropy: {
maxWordLength: { type: Number, attribute: 'max-word-length' } type: Number,
} reflect: true,
} attribute: 'template-entropy',
},
maxWordLength: { type: Number, attribute: 'max-word-length' },
};
}
constructor() { constructor() {
super() super();
this.template = 'adjective noun verb adverb.' this.template = 'adjective noun verb adverb.';
this.maxWordLength = 0 this.maxWordLength = 0;
this.parsedString = '' this.parsedString = '';
this.fetchedWordlistCount = 0 this.fetchedWordlistCount = 0;
this.capitalize = true this.capitalize = true;
this.partsOfSpeechMap = { this.partsOfSpeechMap = {
'noun': 'nouns', noun: 'nouns',
'adverb': 'adverbs', adverb: 'adverbs',
'adv': 'adverbs', adv: 'adverbs',
'verb': 'verbs', verb: 'verbs',
'interjection': 'interjections', interjection: 'interjections',
'adjective': 'adjectives', adjective: 'adjectives',
'adj': 'adjectives', adj: 'adjectives',
'verbed': 'verbed' verbed: 'verbed',
} };
this.partsOfSpeech = Object.keys(this.partsOfSpeechMap) this.partsOfSpeech = Object.keys(this.partsOfSpeechMap);
this._wordlists = WORDLISTS this._wordlists = WORDLISTS;
} }
static styles = css` static styles = css`
div { div {
text-align: center; text-align: center;
width: 100%; width: 100%;
background-color: #1f2023; background-color: #1f2023;
border-radius: 5px; border-radius: 5px;
padding: 10px; padding: 10px;
} }
`; `;
render() { render() {
return html` return html` <div>${this.parsedString}</div> `;
<div>${this.parsedString}</div> }
`
}
firstUpdated() {
// ...
}
updated(changedProperties) {
let regen = false;
firstUpdated() { if (changedProperties.has('template')) {
// ... regen = true;
} }
updated(changedProperties) { if (changedProperties.has('maxWordLength')) {
let regen = false console.dir(this.maxWordLength);
if (changedProperties.has('template')) { if (this.maxWordLength) {
regen = true const wl = { ...this._wordlists };
}
if (changedProperties.has('maxWordLength')) { for (const partOfSpeech in this._wordlists) {
console.dir(this.maxWordLength) if (Array.isArray(this._wordlists[partOfSpeech])) {
wl[partOfSpeech] = this._wordlists[partOfSpeech].filter(
(word) => word.length <= this.maxWordLength
);
}
}
if (this.maxWordLength) { this._wordlists = wl;
const wl = { ...this._wordlists } }
for (const partOfSpeech in this._wordlists) { regen = true;
if (Array.isArray(this._wordlists[partOfSpeech])) { }
wl[partOfSpeech] = this._wordlists[partOfSpeech].filter(word => word.length <= this.maxWordLength)
}
}
this._wordlists = wl if (regen) this.generate();
} }
regen = true _RNG(entropy) {
} if (entropy > 1074) {
throw new Error('Javascript can not handle that much entropy!');
}
if (regen) this.generate() let randNum = 0;
}
_RNG(entropy) { const crypto = window.crypto || window.msCrypto;
if (entropy > 1074) {
throw new Error('Javascript can not handle that much entropy!')
}
let randNum = 0 if (crypto) {
const entropy256 = Math.ceil(entropy / 8);
const crypto = window.crypto || window.msCrypto let buffer = new Uint8Array(entropy256);
if (crypto) { crypto.getRandomValues(buffer);
const entropy256 = Math.ceil(entropy / 8)
let buffer = new Uint8Array(entropy256) randNum =
buffer.reduce((num, value) => {
return num * value;
}, 1) / Math.pow(256, entropy256);
} else {
console.warn('Secure RNG not found. Using Math.random');
crypto.getRandomValues(buffer) randNum = Math.random();
}
randNum = buffer.reduce((num, value) => { return randNum;
return num * value }
}, 1) / Math.pow(256, entropy256)
} else {
console.warn('Secure RNG not found. Using Math.random')
randNum = Math.random() setRNG(fn) {
} this._RNG = fn;
}
return randNum _captitalize(str) {
} return str.charAt(0).toUpperCase() + str.slice(1);
}
setRNG(fn) { getWord(partOfSpeech) {
this._RNG = fn const words = this._wordlists[this.partsOfSpeechMap[partOfSpeech]];
} const requiredEntropy = Math.log(words.length) / Math.log(2);
const index = this._RNG(requiredEntropy) * words.length;
_captitalize(str) { return {
return str.charAt(0).toUpperCase() + str.slice(1) word: words[Math.round(index)],
} entropy: words.length,
};
}
getWord(partOfSpeech) { generate() {
const words = this._wordlists[this.partsOfSpeechMap[partOfSpeech]] this.parsedString = this.parse(this.template);
const requiredEntropy = Math.log(words.length) / Math.log(2) }
const index = this._RNG(requiredEntropy) * words.length
return { parse(template) {
word: words[Math.round(index)], const split = template.split(/[\s]/g);
entropy: words.length
}
}
generate() { let entropy = 1;
this.parsedString = this.parse(this.template)
}
parse(template) { const final = split.map((word) => {
const split = template.split(/[\s]/g) const lower = word.toLowerCase();
let entropy = 1 this.partsOfSpeech.some((partOfSpeech) => {
const partOfSpeechIndex = lower.indexOf(partOfSpeech); // Check it exists
const nextChar = word.charAt(partOfSpeech.length);
const final = split.map(word => { if (
const lower = word.toLowerCase() partOfSpeechIndex === 0 &&
!(nextChar && nextChar.match(/[a-zA-Z]/g) != null)
) {
const replacement = this.getWord(partOfSpeech);
word = replacement.word + word.slice(partOfSpeech.length); // Append the rest of the "word" (punctuation)
entropy = entropy * replacement.entropy;
this.partsOfSpeech.some(partOfSpeech => { return true;
const partOfSpeechIndex = lower.indexOf(partOfSpeech) // Check it exists }
const nextChar = word.charAt(partOfSpeech.length) });
if (partOfSpeechIndex === 0 && !(nextChar && (nextChar.match(/[a-zA-Z]/g) != null))) { return word;
const replacement = this.getWord(partOfSpeech) });
word = replacement.word + word.slice(partOfSpeech.length) // Append the rest of the "word" (punctuation)
entropy = entropy * replacement.entropy
return true this.templateEntropy = Math.floor(Math.log(entropy) / Math.log(8));
}
})
return word return final.join(' ');
}) }
this.templateEntropy = Math.floor(Math.log(entropy) / Math.log(8))
return final.join(' ')
}
} }
window.customElements.define('random-sentence-generator', RandomSentenceGenerator) window.customElements.define(
'random-sentence-generator',
RandomSentenceGenerator
);
export default RandomSentenceGenerator export default RandomSentenceGenerator;

View File

@ -1,40 +1,40 @@
export const EXCEPTIONS = { export const EXCEPTIONS = {
'are': 'were', are: 'were',
'eat': 'ate', eat: 'ate',
'go': 'went', go: 'went',
'have': 'had', have: 'had',
'inherit': 'inherited', inherit: 'inherited',
'is': 'was', is: 'was',
'run': 'ran', run: 'ran',
'sit': 'sat', sit: 'sat',
'visit': 'visited' visit: 'visited',
} };
export const getPastTense = (verb, exceptions = EXCEPTIONS) => { export const getPastTense = (verb, exceptions = EXCEPTIONS) => {
if (exceptions[verb]) { if (exceptions[verb]) {
return exceptions[verb] return exceptions[verb];
} }
if ((/e$/i).test(verb)) { if (/e$/i.test(verb)) {
return verb + 'd' return verb + 'd';
} }
if ((/[aeiou]c$/i).test(verb)) { if (/[aeiou]c$/i.test(verb)) {
return verb + 'ked' return verb + 'ked';
} }
// for american english only // for american english only
if ((/el$/i).test(verb)) { if (/el$/i.test(verb)) {
return verb + 'ed' return verb + 'ed';
} }
if ((/[aeio][aeiou][dlmnprst]$/).test(verb)) { if (/[aeio][aeiou][dlmnprst]$/.test(verb)) {
return verb + 'ed' return verb + 'ed';
} }
if ((/[aeiou][bdglmnprst]$/i).test(verb)) { if (/[aeiou][bdglmnprst]$/i.test(verb)) {
return verb.replace(/(.+[aeiou])([bdglmnprst])/, '$1$2$2ed') return verb.replace(/(.+[aeiou])([bdglmnprst])/, '$1$2$2ed');
} }
return verb + 'ed' return verb + 'ed';
} };

View File

@ -4,6 +4,7 @@ import Base58 from '../deps/Base58';
export const validateAddress = (address) => { export const validateAddress = (address) => {
let isAddress = false; let isAddress = false;
try { try {
const decodePubKey = Base58.decode(address); const decodePubKey = Base58.decode(address);