Skip to content

Commit

Permalink
Merge pull request #21 from Lamden/fix-datetime-and-timedelta
Browse files Browse the repository at this point in the history
timedelta and datetime send objects instead of lists
  • Loading branch information
JeffWScott authored Dec 18, 2020
2 parents 4019a31 + a9d2921 commit 4e66829
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 39 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const Lamden = require('lamden-js')

## Wallet Functions
### Create a Lamden Keypair
Creates a new wallet object.
- **verifying key (vk)**: public key
- **secret key (sk)**: private key
```javascript
let lamdenWallet = Lamden.wallet.new_wallet()

Expand All @@ -35,6 +38,7 @@ console.log(lamdenWallet)
```

### Get a public key (vk) from a private key (sk)
Takes the sk as an argument and returns the vk
```javascript
let sk = "69a8db3fb7196debc2711fad1fa1935918d09f5d8900d84c3288ea5237611c03"
let vk = wallet.get_vk(sk)
Expand All @@ -44,6 +48,7 @@ console.log(vk)
```

### Sign a message
Signs a string payload
```javascript
const stringBuffer = Buffer.from('message')
let messageBytes = new Uint8Array(stringBuffer);
Expand All @@ -56,6 +61,7 @@ console.log(signedMessage)
```

#### Verify signature
verify a payload
```javascript
let validSignature = wallet.verify(vk, messageBytes, signedMessage)

Expand Down
21 changes: 21 additions & 0 deletions con_values_testing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
yourState = Hash(default_value='')

@export
def test_values(UID: str, Str: str, Int: int, Float: float, Bool: bool, Dict: dict, List: list, ANY: Any, DateTime: datetime.datetime, TimeDelta: datetime.timedelta):
yourState[UID, 'Str'] = Str
assert isinstance(yourState[UID, 'Str'], str), 'Str should be of type str'
yourState[UID, 'Int'] = Int
assert isinstance(yourState[UID, 'Int'], int), 'Int should be of type int'
yourState[UID, 'Float'] = Float
#assert isinstance(yourState[UID, 'Float'], ContractingDecimal), type(yourState[UID, 'Float'])
yourState[UID, 'Bool'] = Bool
assert isinstance(yourState[UID, 'Bool'], bool), 'Bool should be of type bool'
yourState[UID, 'Dict'] = Dict
assert isinstance(yourState[UID, 'Dict'], dict), 'Dict should be of type dict'
yourState[UID, 'List'] = List
assert isinstance(yourState[UID, 'List'], list), 'List should be of type list'
yourState[UID, 'ANY'] = ANY
yourState[UID, 'DateTime'] = DateTime
assert isinstance(yourState[UID, 'DateTime'], datetime.datetime), 'DateTime should be of type DateTime'
yourState[UID, 'TimeDelta'] = TimeDelta
assert isinstance(yourState[UID, 'TimeDelta'], datetime.timedelta), 'TimeDelta should be of type TimeDelta'
32 changes: 16 additions & 16 deletions dist/lamden.js
Original file line number Diff line number Diff line change
Expand Up @@ -2392,10 +2392,10 @@ class EventEmitter {
}

/*
* bignumber.js v9.0.0
* bignumber.js v9.0.1
* A JavaScript library for arbitrary-precision arithmetic.
* https://github.com/MikeMcl/bignumber.js
* Copyright (c) 2019 Michael Mclaughlin <[email protected]>
* Copyright (c) 2020 Michael Mclaughlin <[email protected]>
* MIT Licensed.
*
* BigNumber.prototype methods | BigNumber methods
Expand Down Expand Up @@ -4787,7 +4787,7 @@ function clone(configObject) {
e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);

if (s == 1 / 0) {
n = '1e' + e;
n = '5e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
Expand Down Expand Up @@ -5355,21 +5355,21 @@ function Encoder (type, value) {
const encodeDateTime = (val) => {
val = !isDate(val) ? new Date(val) : val;
if (!isDate(val)) throwError(val);
return [
return {'__time__': [
val.getUTCFullYear(),
val.getUTCMonth(),
val.getUTCDate(),
val.getUTCHours(),
val.getUTCMinutes(),
val.getUTCSeconds(),
val.getUTCMilliseconds()
]
]}
};
const encodeTimeDelta = (val) => {
const time = isDate(val) ? val.getTime() : new Date(val).getTime();
const days = parseInt(time / 1000 / 60 / 60 / 24);
const seconds = (time - (days * 24 * 60 * 60 * 1000)) / 1000;
return [days, seconds]
return {'__delta__':[days, seconds]}
};

const encodeList = (val) => {
Expand Down Expand Up @@ -5404,7 +5404,7 @@ function Encoder (type, value) {

function parseObject (obj) {
const encode = (k, v) => {
if (k === "datetime" || k === "datetime.datetime") return Encoder("datetime.datetime", v)
if (k === "datetime" || k === "datetime.datetime" ) return Encoder("datetime.datetime", v)
if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v)
if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v)
return v
Expand Down Expand Up @@ -5905,7 +5905,7 @@ class TransactionBuilder extends Network {
//Set error if txSendResult doesn't exist
if (response === 'undefined' || validateTypes$2.isStringWithValue(response)){
this.txSendResult.errors = ['TypeError: Failed to fetch'];
}else{
}else {
if (response.error) this.txSendResult.errors = [response.error];
else this.txSendResult = response;
}
Expand All @@ -5925,31 +5925,31 @@ class TransactionBuilder extends Network {
if (typeof res === 'undefined'){
res = {};
res.error = 'TypeError: Failed to fetch';
}else{
}else {
if (typeof res === 'string') {
if (this.txCheckAttempts < this.txCheckLimit){
checkAgain = true;
}else{
}else {
this.txCheckResult.errors = [res];
}
}else{
}else {
if (res.error){
if (res.error === 'Transaction not found.'){
if (this.txCheckAttempts < this.txCheckLimit){
checkAgain = true;
}else{
}else {
this.txCheckResult.errors = [res.error, `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`];
}
}else{
}else {
this.txCheckResult.errors = [res.error];
}
}else{
}else {
this.txCheckResult = res;
}
}
}
if (checkAgain) timerId = setTimeout(checkTx.bind(this), 1000);
else{
else {
if (validateTypes$2.isNumber(this.txCheckResult.status)){
if (this.txCheckResult.status > 0){
if (!validateTypes$2.isArray(this.txCheckResult.errors)) this.txCheckResult.errors = [];
Expand All @@ -5968,7 +5968,7 @@ class TransactionBuilder extends Network {
if (validateTypes$2.isStringWithValue(result.hash) && validateTypes$2.isStringWithValue(result.success)){
this.txHash = result.hash;
this.setPendingBlockInfo();
}else{
}else {
this.setBlockResultInfo(result);
this.txBlockResult = result;
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lamden-js",
"version": "1.21.0",
"version": "1.3.0",
"description": "A javascript implementaion for creating wallets, submitting transactions and interacting with masternodes on the Lamden Blockchain.",
"main": "dist/lamden.js",
"scripts": {
Expand Down
8 changes: 4 additions & 4 deletions src/js/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,21 @@ function Encoder (type, value) {
const encodeDateTime = (val) => {
val = !isDate(val) ? new Date(val) : val
if (!isDate(val)) throwError(val)
return [
return {'__time__': [
val.getUTCFullYear(),
val.getUTCMonth(),
val.getUTCDate(),
val.getUTCHours(),
val.getUTCMinutes(),
val.getUTCSeconds(),
val.getUTCMilliseconds()
]
]}
}
const encodeTimeDelta = (val) => {
const time = isDate(val) ? val.getTime() : new Date(val).getTime()
const days = parseInt(time / 1000 / 60 / 60 / 24)
const seconds = (time - (days * 24 * 60 * 60 * 1000)) / 1000
return [days, seconds]
return {'__delta__':[days, seconds]}
}

const encodeList = (val) => {
Expand Down Expand Up @@ -117,7 +117,7 @@ function Encoder (type, value) {

function parseObject (obj) {
const encode = (k, v) => {
if (k === "datetime" || k === "datetime.datetime") return Encoder("datetime.datetime", v)
if (k === "datetime" || k === "datetime.datetime" ) return Encoder("datetime.datetime", v)
if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v)
if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v)
return v
Expand Down
28 changes: 14 additions & 14 deletions test/encoder-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ describe('Test Type Encoder', () => {
expect( JSON.stringify(Encoder('dict', '{"vk":"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7"}')) ).to.be( JSON.stringify({vk:"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7"}) )
})
it('encodes datetime and float inside a dict from a string', () => {
expect( JSON.stringify(Encoder('dict', {'datetime':new Date(dateString), 'float': 1.1})) ).to.be( '{"datetime":[2020,6,28,19,16,35,59],"float":{"__fixed__":"1.1"}}' )
expect( JSON.stringify(Encoder('dict', {'datetime':new Date(dateString), 'float': 1.1})) ).to.be( '{"datetime":{"__time__":[2020,6,28,19,16,35,59]},"float":{"__fixed__":"1.1"}}' )
})
it('replaces datetime object with value in dict', () => {
expect( JSON.stringify( Encoder('dict', {'DateTime':{'datetime':new Date(dateString)}})) ).to.be('{"DateTime":[2020,6,28,19,16,35,59]}');
expect( JSON.stringify( Encoder('dict', {'DateTime':{'datetime':new Date(dateString)}})) ).to.be('{"DateTime":{"__time__":[2020,6,28,19,16,35,59]}}');
})
it('replaces timedelta object with value in dict', () => {
expect( JSON.stringify( Encoder('dict', {'TimeDelta':{'timedelta':1000}})) ).to.be('{"TimeDelta":[0,1]}');
expect( JSON.stringify( Encoder('dict', {'TimeDelta':{'timedelta':1000}})) ).to.be('{"TimeDelta":{"__delta__":[0,1]}}');
})
it('fails to encode non-objects', () => {
expect(() => Encoder('dict', undefined)).to.throwError();
Expand All @@ -129,12 +129,12 @@ describe('Test Type Encoder', () => {
})
it('encodes fixed and datetime values in the list', () => {
expect( JSON.stringify(Encoder('list', [ 1.1, {'datetime':new Date(dateString)}] )) )
.to.be( '[{"__fixed__":"1.1"},[2020,6,28,19,16,35,59]]' )
.to.be( '[{"__fixed__":"1.1"},{"__time__":[2020,6,28,19,16,35,59]}]' )
})
it('encodes a list of all values and encodes accordingly', () => {
let testList = [1, 1.1, "string", {'datetime':new Date(dateString)}, {'timedelta':1000}, {'TimeDelta':{'timedelta':1000}}, true, [1.1]]
expect( JSON.stringify(Encoder('list', testList)) )
.to.be( '[1,{"__fixed__":"1.1"},"string",[2020,6,28,19,16,35,59],[0,1],{"TimeDelta":[0,1]},true,[{"__fixed__":"1.1"}]]' )
.to.be( '[1,{"__fixed__":"1.1"},"string",{"__time__":[2020,6,28,19,16,35,59]},{"__delta__":[0,1]},{"TimeDelta":{"__delta__":[0,1]}},true,[{"__fixed__":"1.1"}]]' )
})
it('fails to encode non-list', () => {
expect(() => Encoder('list', {})).to.throwError();
Expand All @@ -155,22 +155,22 @@ describe('Test Type Encoder', () => {

context('DateTime', () => {
it('Encodes a Date into a value list', () => {
expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString))) ).to.be(JSON.stringify([2020, 6, 28, 19, 16, 35, 59]))
expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString))) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]}))
})
it('Encodes a Date string into a value list', () => {
expect( JSON.stringify(Encoder('datetime.datetime', dateString)) ).to.be(JSON.stringify([2020, 6, 28, 19, 16, 35, 59]))
expect( JSON.stringify(Encoder('datetime.datetime', dateString)) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]}))
})
it('Encodes milliseconds into a value list', () => {
expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString).getTime())) ).to.be(JSON.stringify([2020, 6, 28, 19, 16, 35, 59]))
expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString).getTime())) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]}))
})
})

context('TimeDelta', () => {
it('Encodes a Date into days seconds', () => {
expect( JSON.stringify(Encoder('datetime.timedelta', new Date(millisecondsDelta))) ).to.be(JSON.stringify([5, 43200]))
expect( JSON.stringify(Encoder('datetime.timedelta', new Date(millisecondsDelta))) ).to.be(JSON.stringify({'__delta__':[5, 43200]}))
})
it('Encodes a millisenconds into days seconds', () => {
expect( JSON.stringify(Encoder('datetime.timedelta', millisecondsDelta)) ).to.be(JSON.stringify([5, 43200]))
expect( JSON.stringify(Encoder('datetime.timedelta', millisecondsDelta)) ).to.be(JSON.stringify({'__delta__':[5, 43200]}))
})
})

Expand Down Expand Up @@ -200,21 +200,21 @@ describe('Test Type Encoder', () => {
expect( encodedObj.includes('"bool":true') ).to.be(true)
})
it('encodes a datetime.datetime', () => {
expect( encodedObj.includes('"datetime.datetime":[2020,6,28,19,16,35,59]') ).to.be(true)
expect( encodedObj.includes('"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]}') ).to.be(true)
})
it('encodes an datetime.timdelta', () => {
expect( encodedObj.includes('"datetime.timedelta":[5,43200]') ).to.be(true)
expect( encodedObj.includes('"datetime.timedelta":{"__delta__":[5,43200]}') ).to.be(true)
})
it('encodes an list', () => {
expect(
encodedObj
.includes('"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":[2020,6,28,19,16,35,59],"TimeDelta":[5,43200]}]') )
.includes('"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}]') )
.to.be(true)
})
it('encodes a dict/object', () => {
expect(
encodedObj
.includes('"dict":{"integer":1,"float":{"__fixed__":"1.1"},"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":[2020,6,28,19,16,35,59],"TimeDelta":[5,43200]}],"str":"this is a string","bool":true,"datetime.datetime":[2020,6,28,19,16,35,59],"datetime.timedelta":[5,43200]}') )
.includes('"dict":{"integer":1,"float":{"__fixed__":"1.1"},"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}],"str":"this is a string","bool":true,"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]},"datetime.timedelta":{"__delta__":[5,43200]}}') )
.to.be(true)
})
})
Expand Down
6 changes: 3 additions & 3 deletions test/transactionBatcher-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ describe('Test TransactionBuilder class', () => {
})
context('TransactionBatcher.sendBatch()', () => {
it('can send a batch of successful transactions', async function () {
this.timeout(30000);
this.timeout(60000);
let txb = new Lamden.TransactionBatcher(networkInfo)
let response = await txb.getStartingNonce(senderWallet1.vk)

Expand All @@ -155,7 +155,7 @@ describe('Test TransactionBuilder class', () => {

context('TransactionBatcher.sendAllBatches()', () => {
it('Can send batches from all senders', async function () {
this.timeout(30000);
this.timeout(60000);
sleep(1500)
let txb = new Lamden.TransactionBatcher(networkInfo)
const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15)
Expand All @@ -169,7 +169,7 @@ describe('Test TransactionBuilder class', () => {
if (!txBuilder.txSendResult.hash) console.log(txBuilder.nonce + ": " + txBuilder.txSendResult.errors)
expect(typeof txBuilder.txSendResult.hash === 'string').to.be(true)
})
console.log(txb)

expect(txb.hasTransactions()).to.be(false)
})
it('Can process overflow', async function () {
Expand Down
3 changes: 2 additions & 1 deletion test/transactionBuilder-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ let kwargs = {

let valuesTxInfo = {
senderVk: senderWallet.vk,
contractName: 'con_values_testing',
contractName: 'con_values_testing_2',
methodName: 'test_values',
stampLimit: 100,
kwargs: {
Expand Down Expand Up @@ -284,6 +284,7 @@ describe('Test TransactionBuilder class', () => {

//Send Transaction
let response = await newTx.send(senderWallet.sk);

expect(response.success).to.be("Transaction successfully submitted to the network.")

//Check Transaction
Expand Down

0 comments on commit 4e66829

Please sign in to comment.