near / near-sdk-js

Tools for building NEAR smart contracts in JavaScript
https://near.github.io/near-sdk-js/
MIT License
192 stars 65 forks source link

ext_contract feature in sdk-js #243

Open exalate-issue-sync[bot] opened 1 year ago

exalate-issue-sync[bot] commented 1 year ago

Bo Yao commented:

it's possible but looks very hacky to implement in JS. Basically, it's a code generation like NearBindgen. But it cannot be a decorator as JS restrict where a decorator can apply, so it must be a function-like "macro". And JS doesn't have macro. Babel can do, but it's going to be magical to user and I'm not sure this is better than Promise.new.functionCall.

exalate-issue-sync[bot] commented 1 year ago

Bo Yao commented:

possible snippet:

import {PromiseOrValue, call, ExtContract, NearBindgen, near, Gas} from 'near-sdk-js';

// Prepaid gas for a single (not inclusive of recursion) `factorial` call.
const FACTORIAL_CALL_GAS: Gas = 20_000_000_000_000n;

// Prepaid gas for a single `factorial_mult` call.
const FACTORIAL_MULT_CALL_GAS: Gas = 10_000_000_000_000n;

const ext = ExtContract(class ExtCrossContract{
    factorial: (n: number) => PromiseOrValue

  ;
    factorial_mult: (n: number, cur: number) => number;
})

@NearBindgen({})
class ExtCrossContract{
    @call({})
    factorial(n: number): PromiseOrValue

    

    {
        if (n <= 1) {
            return 1;
        }
        let accountId = near.currentAccountId();
        let prepaidGas = near.prepaidGas() - FACTORIAL_CALL_GAS;

        return ext.factorial(n-1, accountId, 0, prepaidGas - FACTORIAL_MULT_CALL_GAS)
            .then(ext.factorial_mult(n, accountId, 0, FACTORIAL_MULT_CALL_GAS))
    }
    @call({privateFunction: true, callbacks: ['cur']})
    factorial_mult(n: number, cur: number): number {
        near.log(`Received ${n} and ${cur}`);
        let result = n * cur;
        near.log(`Multiplied ${result}`);
        return result;
    }
}