Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wrappers to easily convert between ScVal and native types. #630

Merged
merged 22 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add janky workaround for browser checks
  • Loading branch information
Shaptic committed Jun 22, 2023
commit cd2acfce2b1221ff6ae285fe8ea3f1ae02385902
23 changes: 21 additions & 2 deletions src/smart.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class SmartParser {
return new ScInt(val).toScVal();

case 'object':
if (val instanceof xdr.ScVal) {
if (isScValish(val)) {
return val;
} else if (val === null) {
return xdr.ScVal.scvVoid();
Expand All @@ -111,7 +111,11 @@ export class SmartParser {
}
return xdr.ScVal.scvVec(val.map(this.toScVal));
} else if ((val.constructor?.name ?? '') !== 'Object') {
throw new TypeError(`cannot interpret ${val.constructor?.name} value as ScVal (${val})`)
throw new TypeError(
`cannot interpret ${
val.constructor?.name
} value as ScVal (${JSON.stringify(val)})`
);
} else {
return xdr.ScVal.scvMap(
Object.entries(val).map(([key, val], i) => {
Expand Down Expand Up @@ -201,3 +205,18 @@ export class SmartParser {
}
}
}

function isScValish(scv) {
// for whatever reason, this fails in browser contexts:
//
// let scv = xdr.ScVal.scvU32(1234);
// scv instanceof xdr.ScVal; // false!!!
//
// so we add a janky, duck-type way to 'best effort' check an ScVal
return scv instanceof xdr.ScVal || (
scv !== null &&
typeof scv.switch === 'function' &&
typeof scv.switch().name === 'string' &&
scv.switch().name.startsWith('scv')
);
}
10 changes: 5 additions & 5 deletions test/unit/smart_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ describe('parsing and building ScVals', function () {

// iterate for granular errors on failures
targetScv.value().forEach((entry, idx) => {
const actual = scv.value()[idx];
// console.log(`expected (${idx}):`, entry);
// console.log(`actual (${idx}):`, actual);
expect(entry).to.deep.equal(actual, `item ${idx} does not match`);
})
const actual = scv.value()[idx];
console.log(`expected (${idx}):`, entry);
console.log(`actual (${idx}):`, actual);
expect(entry).to.deep.equal(actual, `item ${idx} doesn't match`);
});

expect(scv.toXDR('base64')).to.deep.equal(targetScv.toXDR('base64'));
});
Expand Down