near / near-sdk-as

Tools for building NEAR smart contracts in AssemblyScript
https://near.github.io/near-sdk-as/
Other
115 stars 44 forks source link

Promise handling tweaks #505

Open mehtaphysical opened 3 years ago

mehtaphysical commented 3 years ago

Right now promise handling works well, but can be a bit confusing to people just starting out. I think it would be nice to make some tweaks to improve the learning curve and get the syntax a bit more in line with the rust sdk. I was thinking something like this:

 class Nothing {}

export function start(): BatchPromise {
 return BatchPromise.create('SOME_CONTRACT_ID', [
 Action.functionCall<Nothing>('someMethod', {}, u128.Zero, 30000000000000)
 ])
 .then(myCallback());
 }

@callback
 export function myCallback(): string {
 switch(ContractPromise.getResults()<span class="error">[0]</span>.status) 

 { case PromiseStatus.Successful: return "success!" case PromiseStatus.Failed: return "failed!" default: return "unknown" } 

}

To accomplish the above:

I have a little proof of concept for this right now, but I'm not sure this syntax is perfect yet and would love to discuss how to improve this.

In any case, I am happy to work on this improvement and make a PR.

willemneal commented 3 years ago

Looks good to me! I've been wondering about adding something similar to the external contract interface in the rust sdk.


@externalContract
interface OtherContract {
...
}

Where the interface would become a namespace and each method would return a promise.

The issue I've had with a lot of these ideas is that they tend not to play well with TS.

However, since TS allows decorators your example in TS we could define it in the as_types.d.ts file such that it will alter the function's type so that the IDE will be happy and still help to type check any arguments passed. If this works, then perhaps it would just mean adding each function independently instead of an interface.

mehtaphysical commented 3 years ago

That's a really good point @willemneal, about getting these things to play well with TS. I've been experimenting, and decorators are not allowed on functions like in my proof of concept above.

I've been experimenting with creating a TS plugin that will allow this type of thing. https://github.com/microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin. What do you think about including a TS plugin to get the developer experience just right?

willemneal commented 3 years ago

@mehtaphysical That looks perfect! It can help with decorators across the board and even maybe handle new syntax like a macro system.